【问题标题】:shuffle two arrays in java在java中打乱两个数组
【发布时间】:2014-02-26 08:08:09
【问题描述】:

对不起,我是java初学者。我定义了两个数组。其中一种类型是字符串,另一种是整数。现在,我想对它们进行洗牌。假设 id = {12, 45, 78, 23} 和 name = {"math", "physic", "art", "computer"}。例如,在洗牌后,数组将变为 id = {78,45,23,12} 和 name = {"physic", "art", "math", "computer"}。我写了下面的代码,它不起作用。我该如何解决?

public class RandomNumber {

public static void main(String[] args) 
{
    long[] numbers = new long[4];
    Scanner input = new Scanner(System.in);
    Random id = new Random(4);
    String[] name = new String[4];

    for (int i=0; i<=numbers.length; i++)
    {
        System.out.print("Enter the numbers: ");
        numbers[i] = input.nextLong();
    }
    for (int i=0; i<=numbers.length; i++)
    {
        int randomPosition = id.nextInt(4);
        long temp = numbers[i];
        numbers[i] = randomPosition;
        numbers[randomPosition] = temp;
    }
    for (int i=0; i<name.length; i++)
    {
        System.out.println("Enter the name: ");
        name [i] = input.nextLine();
    }
    for (int i=0; i<name.length; i++)
    {
        int randomPosition = id.nextInt(4);
        String temp = name[i];
        name[i] = randomPosition;
        name [randomPosition] = temp;
    }
    for (int i=0; i<numbers.length; i++)
    {
        System.out.println(i + " ID = " + numbers[i] + " and name = " + name[i]);
    }
}  
}

【问题讨论】:

  • for (int i=0; i&lt;=numbers.length; i++) - 为什么是=
  • 对,我删掉它。
  • 仅供参考:“不起作用”不是一个有效的陈述——当你执行你的代码时会发生什么,你期望它做什么,你试图解决你的问题是什么?
  • 当我输入数字时,我无法输入名字

标签: java arrays random


【解决方案1】:

可以将这些数组添加到列表中,然后使用集合中的随机播放方法:

Collections.shuffle(List myList);

对于不同的问题,请参阅相同的答案: How can I make this into a loop?

【讨论】:

【解决方案2】:

既然你有一个二值信息,为什么不使用地图

    Map<Integer, String> toRandomize = new HashMap<Integer, String>();
    toRandomize.put(1, "One");
    toRandomize.put(2, "Two");
    toRandomize.put(3, "Etc");

    Random r = new Random();

    List<Integer> keys = new ArrayList<Integer>(toRandomize.keySet());
    while (!keys.isEmpty()) {
        Integer key = keys.remove(r.nextInt(keys.size()));
        String val = toRandomize.get(key);
        System.out.println("key=" + key + ", val=" + val);
    }

【讨论】:

    【解决方案3】:

    你应该这样做:

        int randomPosition = id.nextInt(4);
        long temp = numbers[i];
        numbers[i] = numbers[randomPosition];
        numbers[randomPosition] = temp;
    

    你有不同的第 3 行。

    numbers[i] = randomPosition;
    

    这同样适用于名称。

    您还有一些其他错误。

    您的代码已修复。
    将其与您的进行比较。
    您将看到发生了什么变化。

    import java.util.Random;
    import java.util.Scanner;
    
    public class RandomNumber {
    
        public static void main(String[] args) {
            long[] numbers = new long[4];
            Scanner input = new Scanner(System.in);
            Random id = new Random(4);
            String[] name = new String[4];
    
            System.out.print("Enter the numbers: ");
    
            for (int i = 0; i < numbers.length; i++) {
                numbers[i] = input.nextLong();
            }
    
            for (int i = 0; i < numbers.length; i++) {
                int randomPosition = id.nextInt(4);
                long temp = numbers[i];
                numbers[i] = numbers[randomPosition];
                numbers[randomPosition] = temp;
            }
    
            System.out.println("Enter the names: ");
    
            for (int i = 0; i < name.length; i++) {
                name[i] = input.next();
            }
    
            for (int i = 0; i < name.length; i++) {
                int randomPosition = id.nextInt(4);
                String temp = name[i];
                name[i] = name[randomPosition];
                name[randomPosition] = temp;
            }
            for (int i = 0; i < numbers.length; i++) {
                System.out.println(i + " ID = " + numbers[i] + " and name = " + name[i]);
            }
        }
    }
    

    【讨论】:

      【解决方案4】:
      Using Collections to shuffle an array of primitive types is a bit of an overkill...
      
      It is simple enough to implement the function yourself, using for example the http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
      
      import java.util.*;
      
      class Test
      {
        public static void main(String args[])
        {
          int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
      
          shuffleArray(solutionArray);
          for (int i = 0; i < solutionArray.length; i++)
          {
            System.out.print(solutionArray[i] + " ");
          }
          System.out.println();
        }
      
        // Implementing Fisher–Yates shuffle
        static void shuffleArray(int[] ar)
        {
          Random rnd = new Random();
          for (int i = ar.length - 1; i > 0; i--)
          {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
          }
        }
      }
      

      【讨论】:

        【解决方案5】:

        你只需要

        Arrays.sort(numbers, randomComparator);
        

        其中 randomComparator 是 Comparator 的一个实例,它将随机选择 2 个元素之间的顺序:

        // assuming T is your array type:
        int compare(T o1, T o2) {
          return (int)Math.signum(Math.random() * 2 - 1);
        }
        

        这是做什么的? Math.random() * 2 - 1 会生成一个介于 -1 和 1 之间的数字。关键是它可以生成负数、正数或零。 Math.signum 将其转换为 -1、0、1。

        就是这样,尽情享受吧!

        【讨论】:

        • 我认为 Comparator 违反合同可以被视为丑陋的黑客攻击。
        • 这不是一个丑陋的hack,它也经常用于Javascript世界。 :) 另外,合同的含义应该是您的目标,而不是传道者的意见。
        • It's not an ugly hack, it is often used in Javascript world too ... 好吧,你已经证明了我的观点:D 无论如何,我认为只有在特殊情况下才应该打破 JDK 类的合同并正确评论。考虑阅读该代码的其他人不知道比较器接口,因此他检查了 javadoc,并在第一行阅读了A comparison function, which imposes a total ordering on some collection of objects。相当混乱。您的解决方案可能在这里工作,但如果有人想在不同的上下文中重用“洗牌”比较器将很难失败。
        • 这个比较器的 Javadoc 会清楚地说明,如果在我的代码中的某个地方使用它,它会用于随机排序,当然。 :)
        猜你喜欢
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-29
        • 2017-08-15
        相关资源
        最近更新 更多