简体   繁体   English

如何在二维数组的随机位置中放置一定数量的整数?

[英]How can I put a certain amount of integers in random locations in a 2d array?

I'm trying to put a certain amount of integers into an array in random spots without putting them in the same place. 我试图将一定数量的整数随机放置到数组中,而不将它们放在同一位置。

My combine method concatenates two given integers and returns the Int. 我的Combine方法连接两个给定的整数并返回Int。 Places is an arrayList to keep the locations of the integers already put into the array. Places是一个arrayList,用于保留已放入数组中的整数的位置。 The random method returns a random integer in between the two given ints. random方法返回两个给定int之间的随机整数。

The combine method works and so does the random method, but I'm not sure why it isn't working. 合并方法有效,随机方法也有效,但是我不确定为什么它不起作用。

public void fillOne(int b)
{
    for(int x = 0; x < b; x++)
    {
        int kachow = random(0, 5);
        int kachigga = random(0, 5);
        int skrrt = combine(kachow, kachigga);
        if(notInArray(skrrt))
        {
            locations[kachow][kachigga] = 1;
            places.add(skrrt);
        }
    }
}

You haven't really explained what isn't working. 您还没有真正解释什么不起作用。 But an obvious flaw in your algorithm is that it isn't guaranteed to set b elements to 1 . 但是算法中的一个明显缺陷是不能保证将b元素设置为1 If your algorithm generates a duplicate position then it will set fewer than b elements. 如果您的算法生成重复位置,则它将设置少于b元素。

Your logic for storing the combined positions is overly complex. 您存储组合头寸的逻辑过于复杂。 One solution would be to reverse the logic: generate a single integer representing both dimensions then divide it into two when you are setting the location. 一种解决方案是颠倒逻辑:生成代表两个维度的单个整数,然后在设置位置时将其分为两个。 That makes the checks a lot simpler. 这使检查变得更加简单。

For example, if your array is 5x5: 例如,如果您的数组是5x5:

Set<Integer> positions = new HashSet<>();
while (positions.size() < n)
    positions.add(random.nextInt(25));
for (int p: positions)
    locations[p/5][p%5] = 1;

Because positions is a set it automatically excludes duplicates which means the code will keep adding random positions until their are n distinct positions in the set. 因为positions是一个集合,所以它会自动排除重复项,这意味着代码将继续添加随机位置,直到它们在集合中成为n不同的位置为止。

Even simpler, if you are using Java 8: 如果使用的是Java 8,则更为简单:

random.ints(0, 25)
    .distinct().limit(n)
    .forEach(p -> locations[p/5][p%5] = 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM