how to mess up a sequence of numbers?

2820 views java
-3

I need a sort of algorithm or a library that can do this stuf:

I suppose to have an integer sequence of numbers that starts with 0 and ends with n number, such as:

0,1,2,3,4,5,6,7,8,9,10,11

I want to mess up this sequnce of numbers by a numeric key, so i use as key 378 and the algoritm give me this new sequence of numbers:

7,5,3,11,0,9,4,1,8,10,2

so my question is. There is a sort of algoritm or library that can do this in java?

answered question

what do you mean by this? you want to shuffle the list?

i want this exactly!

I don't think is an exact duplicate, as the OP wants to pass in a custom source of randomness.

@JacobG. You can seed the random number generator, for repeatable results. You can even supply your own implementation of Random if a specific randomization algorithm is desired.

@Andreas Yes, that's what I specified in my answer. However, the duplicate question mentions nothing about that. It seems the duplicate of the duplicate mentions it, but in a different context.

1 Answer

11

Collections.shuffle allows you to pass in your own source of randomness, so you can use 378 as the seed and always receive the same shuffled list:

var numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

Collections.shuffle(numbers, new Random(378));

System.out.println(numbers);

Output:

[4, 10, 3, 2, 0, 7, 9, 11, 5, 6, 1, 8]

posted this

Have an answer?

JD

Please login first before posting an answer.