【问题标题】:Loop through random letters without repeats循环遍历随机字母而不重复
【发布时间】:2015-02-02 01:26:06
【问题描述】:

对于我通过循环创建的每一行 JRadioButtons,我发现很难确保每一行没有重复的字母。我不介意相同的字母是否存在于不同的行中。

有什么想法吗?

提前致谢。

下面是相关代码:

    //loop for making flow layout for each line of random letters
    //counter for having number of the row next to each row in order of selection
    int counter = x;
    //array of booleans 
    boolean[] responses = new boolean[x];
    for(int i = 0; i < x; i++)
    {

        //new jpanel created for every row needed for the word
        JPanel jpLine = new JPanel(new FlowLayout());

        //new jlabel made with counter number for each row
        JLabel count = new JLabel(Integer.toString(counter));
        jpLine.add(count);
        counter--;
        //random number from 0-5 generated for each row
        Random number = new Random();
        int low = 0;
        int high = 5;
        int ranNumber = number.nextInt((high - low) + low);

        //buttongroup outside loop so only one button can be pressed for each row
        ButtonGroup bg = new ButtonGroup();

        //get selected button's index in any group with bg.getSelection().getActionCommand()
        final int row = i;

        ActionListener listener = new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {

                String action = e.getActionCommand();

                if (action.equals("Incorrect")) {
                    responses[row] = false;
                }
                else {
                    responses[row] = true;
                    //System.out.println("row " + row);
                    //System.out.println("btn " + action);
                }

                if(checkAnswers(responses) == true)
                {
                    correct.setText("<html><font color = 'white'>correct</font></html>");
                }

            }
        };

        //loop for making the number of letters in each row - always going to be 6 letters to choose from in each row
        for(int j = 0; j < 5; j++)
        {
            //if the random number generated for each row equals the loop
            //then new radiobutton will be created for the ith letter of the reversed
            //answer, starting from charAt 0 and going to the last character
            if(ranNumber == j)
            {
                JRadioButton answerLetter = new JRadioButton("<html><font color = 'white'>" + answerForGrid.charAt(i) + "</font></html>");

                bg.add(answerLetter);
                answerLetter.setBackground(Color.decode("#566771"));
                answerLetter.setOpaque(true);
                jpLine.add(answerLetter);

                //use setActionCommand("" + j) on each button to associate each button with its index
                answerLetter.setActionCommand("" + j);
                answerLetter.addActionListener(listener);

            }

            //ranLetter is generated randomly from the alphabet string, so random letters are
            //created for each jradiobutton
            final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            final int N = alphabet.length();

            Random letter = new Random();
            char ranLetter;

            while(true) 
            {
                ranLetter = alphabet.charAt(letter.nextInt(N));
                break;
            }

            JRadioButton k = new JRadioButton("<html><font color = 'white'>" + ranLetter + "</font></html>");

            bg.add(k);
            k.setBackground(Color.decode("#566771"));
            k.setOpaque(true);
            jpLine.add(k);
            k.setActionCommand("Incorrect");
            k.addActionListener(listener);


        }
        //add each row of letters (jpLine) to this loops jpanel
        jpCenterCenter.add(jpLine);


    }

【问题讨论】:

    标签: java loops random


    【解决方案1】:
    1. 使用ArrayList&lt;Character&gt; 的字母,您可以从中选择。
    2. 根据每一行的列表size()为列表生成一个随机索引。
    3. remove 从列表中选择的字母

    例如:

    // One possible way of creating your list
    // Reset your list within each "i" loop, just before the "j" loop, 
    //   or you'll never repeat letters across rows
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    ArrayList<Character> possibleLetters = new ArrayList<Character>(alphabet.length);
    for (char c : alphabet) possibleLetters.add(c);
    
    // now select randomly "without replacement"
    for (int j = 0; i < 5; j++) {
        int index = number.nextInt(possibleLetters.size());
        String letter = possibleLetters.remove(index);
    }
    

    你也可以这样做:

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    ArrayList<Character> possibleLetters = new ArrayList<Character>(alphabet.length);
    for (char c : alphabet) possibleLetters.add(c);
    Collections.shuffle(possibleLetters); // optionally: shuffle(possibleLetters, number)
    
    for (int j = 0; i < 5; j++) {
        String letter = possibleLetters.get(j);
    }
    

    如果你这样做了,你不需要每次都重置它,你可以每次shuffle它。

    【讨论】:

    • 如果您要使用ArrayList,您可以使用Collections.shuffle 随机化List,然后按顺序运行列表。实际上,您可以为每一行使用 Collections.shuffle 并维护 List 的单个实例...
    • @AndyBrown 我了解您要执行的操作,但我发现很难将其实现到我的代码中,因为在 j 循环的单独部分中选择了其中一个 JRadioButtons 所以它可以是答案中的字符,然后使用字母字符串创建其他 5 个 JRadioButtons。
    • @AEkon。听起来你想要第一种方法,但是在你的j循环之前你知道你的answerForGrid.charAt(i)的值,所以只做possibleLetters.remove(answerForGrid.charAt(i)),然后你的答案JRadioButton你不需要选择一个随机字母(注意 - 您可能需要确保它是 Character,或者列表是 Strings)。
    • @AndyBrown 我仍然在尝试实现这一点时遇到困难,抱歉打扰了,您认为您可以发布相关的更改代码吗?顺便感谢大家的帮助。
    • @AEkon。我认为,如果您的随机选择没有重复工作,那么将最后一点作为一个新问题发布。除此之外,我刚刚关闭了我的电脑,我无法通过手机提供帮助,抱歉。
    【解决方案2】:

    您可以使用ListCollections.shuffle 的组合来随机化可用字符列表,例如...

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    List<String> values = new ArrayList<>(Arrays.asList(alphabet.split("")));
    for (int row = 0; row < 10; row++) {
    
        Collections.shuffle(values);
        for (int col = 0; col < 5; col++) {
            System.out.print(values.get(col));
        }
        System.out.println("");
    
    }
    

    因为每个字符只在List 中出现一次,所以不可能得到重复,但是Collections.shuffle 的使用负责每一行的随机化过程。

    当然,这取决于您被允许使用这些库的事实;)

    【讨论】:

      【解决方案3】:

      在不深入研究 JRadioButtons 和其他东西的代码的情况下,我认为随机排列是您锁定的目标。

      【讨论】:

        猜你喜欢
        • 2013-06-16
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2018-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多