开发者

How to make combined random number matrix

开发者 https://www.devze.com 2023-03-19 01:09 出处:网络
I\'m having a hardtime figuring out on how can I generat开发者_如何学编程e a twice repeating random number ranges from 1-8 and make it a matrix like this:

I'm having a hardtime figuring out on how can I generat开发者_如何学编程e a twice repeating random number ranges from 1-8 and make it a matrix like this:

5 8 2 5

3 6 4 1

7 6 2 3

4 7 8 1

By the way I plan to make this on android.

Thanks in advance.


I assume you want a randomized 4x4matrix containing all the numbers 1-8 twice.

You can easily turn a list of 16 numbers into a 4x4matrix. So what you need is a randomized list of the 1-8 numbers.

List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 8; i++) {
  list.add(i);
  list.add(i);
}
// list  = [1,1,2,2,3,3,..,8,8];
Collections.shuffle(list);
// gives something like [1,4,5,2,4,7,..8,1]

To turn this list in a matrix, just read row by row, 4 numbers at a time.


What you really want is not random numbers. But a specific set of numbers in a random order!

So start with the required set in ascending order

int[] mySet = Array{1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8}

Then do something like

for (x = 1;99,x++) {
    from = (int)(Math.random()*8);
    to = (int)(Math.random()*8);
    if (from != to) {
       int swap = mySet[to];
       mySet[to] = mySet[from];
       mySet[from] = swap;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消