How can one randomly change the position of each of the four elements ui? - algorithm for 24 possibilities

I have a program with four different buttons. I want to randomly change the position of the buttons. For example: 1 2 3 4 Later: 3 4 1 2 Later: 1 3 2 4

Are there any algorithms for this? The only way I can think of is to make a random number from 1 to 24 (24 possibilities), and then encode all possible knocks.

     int foo = arcrandom() % 23;
      switch(foo){
       case 0:
        button1postiton = 100; //just an example
        button2position = 200;
        button3position = 300;
        button4position = 400;
        break;
       case 2:
        button1postiton = 200;
        //blablabla and so on and so on
}

But is there a more efficient way?

Thank!

+3
source share
4 answers

Thanks for all your answers! I used Shisher Fisher-Yates! I found a good tutorial here on how to use the algorithm in Objective-C: gorbster.net

0

, . -.

+5

(. perm2), char, , , , mjv-.

http://www.cs.princeton.edu/introcs/23recursion/Permutations.java.html

Java , ....

, , , , , . ,

=...// , , ints {0,1,2,3}

//The panel
JPanel  pane;
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

//Choose one permutation at random
int foo = arcrandom() % 23;
int current[] = permutations.get(foo);

//Add the buttons in the chosen order
button = new JButton("Button 1");
c.gridx = current[0];
c.gridy = 0;
pane.add(button, c);

button = new JButton("Button 2");
c.gridx = current[1];
c.gridy = 0;
pane.add(button, c);

button = new JButton("Button 3");
c.gridx = current[2];
c.gridy = 0;
pane.add(button, c);

button = new JButton("Button 4");
c.gridx = current[3];
c.gridy = 0;
pane.add(button, c);

, !

+1

0 <= r < 24

. rr = r% 4 r = r/4. 4.

. 0 .

rr = r% 3 r = r/3. , , 0, 1 2, (1).

1 rr + 1.

rr = r% 2 r = r/2. , , 0 1, (2).

2 rr + 2.

3 .

. . , .

This is probably a Fischer-Yate shuffle - I had no idea what this name was until today.

+1
source

Source: https://habr.com/ru/post/1735668/


All Articles