【问题标题】:Android, Random do not repeat same number twice in a rowAndroid,随机不要连续两次重复相同的数字
【发布时间】:2015-01-29 23:48:36
【问题描述】:

我需要用整数填充一个向量,但我有一些麻烦,我需要用随机数填充它,而不是连续两个数字。 (例如,不是这样:1,4,4,3,5,9) 我制作了这段代码,但效果不佳:

  • @第一次loja=1;
  • 但直到比赛结束:loja++;
  • int[] con;

随机方法:

private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}

工作代码:

    int i;
    con = new int [loja];
    for (i=0; i<loja; i++)
    {
        con[i] = nasiqim(8);
        if(i>0){
        while(con[i]==con[i-1])
        {
        con[i] =nasiqim(8); 
        }
        }
        i++;
    }

结果是这样的:

  1. 1
  2. 1,4
  3. 1,4,1
  4. 1,4,1,4
  5. 1,4,1,4,1
  6. 5,3,5,3,5,3
  7. 5,3,5,3,5,3,5

这不是我需要的,我需要的数字是真正随机的,不是这样的, 如果列表是这样的,那就太好了:1,5,6,7,3,0,2,4,1,0,2,3...

谢谢!!

【问题讨论】:

  • 您的随机生成器在方法内部,将其提取为您的类的静态成员。
  • 我也试过了,是一样的:(或者你的意思是随机声明在外面?
  • @chais 可能是对的,作为静态成员它可以解决问题。因为目前,无论何时调用nasiqim,它都会为 Random() 创建一个新对象,因此它会忘记以前的值,这当然会导致重复。
  • 是的,nasiqimi 变量的声明必须在类级别(在所有方法之外)
  • 非常感谢它运行良好,但现在,数字又连续出现两次,例如 1,3,4,4,4,3,2.. 有什么想法吗?跨度>

标签: android random numbers duplicates generator


【解决方案1】:
private int[]           con         = null;

private final Random    nasiqimi    = new Random();

/**
 * Test run random.
 */
@Test
public void testRunRandom() {
    int loja = 10;
    con = new int[loja];
    for (int i = 0; i < loja; i++) {
        int nextRandom = 0;
        while (true) {
            nextRandom = nasiqim(8);
            if (i == 0 || con[i - 1] != nextRandom) {
                con[i] = nextRandom;
                break;
            }
        }
    }

}

/**
 * Gets the random.
 * 
 * @param max the max
 * @return the random
 */
private int nasiqim(int max) {
    return nasiqimi.nextInt(max);
}

【讨论】:

  • 谢谢我刚刚复制了这段代码,现在我得到了我想要的一切!也没有重复:D
【解决方案2】:

我创建了一个示例类

import java.util.*;

public class Foo {

    static Random r = new Random();
    static int[] con;
    static int loja = 8;

    private static int randomInt(int max) {
        return r.nextInt(max);
    }

    public static void main(String args[]) {
        int i;
        con = new int[loja];
        for (i = 0; i < loja; i++) {
            con[i] = randomInt(8);
            if (i > 0) {
                while (con[i] == con[i - 1]) {
                    con[i] = randomInt(8);
                }
            }
        }

        System.out.println( Arrays.toString(con));
    }
}

所有变量都是静态的,注意我去掉了 i++;在 for 循环结束时递增。

【讨论】:

  • 谢谢你,你真的帮了我! :)
猜你喜欢
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2014-03-05
相关资源
最近更新 更多