简体   繁体   English

在Java中随机播放两个数组

[英]shuffle two arrays in java

Sorry, I am beginner in java. 抱歉,我是Java的初学者。 I have defined two arrays. 我定义了两个数组。 one of the types is string and the other is integer. 一种类型是字符串,另一种是整数。 now, i want to shuffle them.Assume id = {12, 45, 78, 23} and name = {"math", "physic", "art", "computer"}. 现在,我想对它们进行洗牌。假设id = {12,45,78,23},名称= {“数学”,“物理”,“艺术”,“计算机”}。 for example after shuffling the arrays will become id = {78,45,23,12} and name = {"physic", "art", "math", "computer"}. 例如,在改组后,数组将变为id = {78,45,23,12},名称= {“物理”,“艺术”,“数学”,“计算机”}。 i wrote the below code which does not work. 我写了下面的代码不起作用。 how can i fix it? 我该如何解决?

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]);
    }
}  
}

Could take those arrays and add them to the List and then use the shuffle methods from the Collections: 可以将这些数组添加到列表中,然后使用Collections中的shuffle方法:

Collections.shuffle(List myList);

see the same answer for a different question on: How can I make this into a loop? 在以下问题上看到相同的答案: 如何将其循环?

As you do have a two value information, why not use a Map 因为您确实有两个值信息,所以为什么不使用Map

    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);
    }

You should do: 你应该做:

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

You have the 3rd line different. 您的第三行有所不同。

numbers[i] = randomPosition;

The same applies to names. 名称也一样。

You had a few other bugs too. 您也有其他一些错误。

Here is your code fixed. 这是您的固定代码。
Compare it with yours. 与您的比较。
You will see what was changed. 您将看到更改的内容。

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]);
        }
    }
}
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;
    }
  }
}

All you need is 所有你需要的是

Arrays.sort(numbers, randomComparator);

where randomComparator is an instance of Comparator who will randomly choose the order between 2 elements: 其中randomComparator是Comparator的实例,它将在2个元素之间随机选择顺序:

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

What does this do? 这是做什么的? Math.random() * 2 - 1 will generate a number between -1 and 1. The key is that it can generate a negative, positive number or zero. Math.random() * 2 - 1 2-1将生成一个介于-1和1之间的数字。关键是它可以生成一个负数,正数或零。 The Math.signum translates it to -1, 0, 1. Math.signum将其转换为-1、0、1。

That's all, enjoy! 就这样,尽情享受吧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM