【问题标题】:fill an array with integers 1-10 while checking to see if the integer is already in the array用整数 1-10 填充数组,同时检查整数是否已经在数组中
【发布时间】:2014-10-23 06:45:38
【问题描述】:

我正在用随机整数 1 - 10 填充一个数组,但是当我这样做时,我需要检查整数是否已经在数组中。我用整数填充数组没有问题,但我检查重复整数的代码无法正常工作。

  package arrayPackage;
  import java.util.Arrays;
  import java.util.Random;
  public class BruteForce 
  {
//declare an integer array with 10 numbers.
int[] array = new int[10];
Random randomInt = new Random();    //random number generator


public void shuffle()
{ 
    //int prevInt=0;
    for(int i = 0; i < array.length; i++)   //for each integer in the array pick a random integer and place in array
    {
        int temp = 1 + randomInt.nextInt(array.length);
        for(int j = i; j < array.length; j++)
        {
            if(temp != array[j] && temp!= array[i])
            {
                array[i] = temp; 
            }
        }

    }
}

public void displayArray()
{
    System.out.println(Arrays.toString(array));
}

}

【问题讨论】:

  • 用数字 1-10 填充数组,然后洗牌不是更容易吗?
  • 数组没有重复的时候你填temp,但是如果有重复你在哪里处理呢?
  • 实现fisher-yates-knuth shuffle是高效且公正的,否则使用现成的实现(java中的内置方法)

标签: java arrays random duplicates


【解决方案1】:

您似乎想要一个随机分布的 1,2,3,...,10 的数组。

以下解决方案更好,因为它只需要恰好 10 次随机调用:

int array = new int[10];

for (int i = 0; i < 10; i++)
{
  array[i] = i + 1;
}

for (int i = 0; i < 10; i++)
{
  int to = randomInt.nextInt(array.length - i) + i; // get random swap target between i and 9
  swap(array[i], array[to]); // I assume Java has swap function
}

【讨论】:

  • Java 没有swap 方法,所以你必须自己做一个简单的方法:private void swap(int[] array, int i, int to){ int temp = array[to]; array[to] = array[i]; array[i] = temp; } 或进行一些检查:private void swap(int[] array, int i, int to){ if(array != null &amp;&amp; array.length &gt; 2 &amp;&amp; i &lt; array.length &amp;&amp; to &lt; array.length &amp;&amp; i != to){ int temp = array[to]; array[to] = array[i]; array[i] = temp; } }
【解决方案2】:

如果您的目标是拥有一个包含数字 1 到 10 的 int 数组,然后将它们随机排列,请尝试以下操作:

private static int[] array = new int[10];

public static void main(String[] args){     
    // Fill the array
    for(int i = 0; i < array.length; i++)
        array[i] = i + 1;

    shuffle(array);
    System.out.println(Arrays.toString(array));
}

private static void shuffle(int[] array){
    if(array != null && array.length > 2){
        Random randomGenerator = new Random();
        for(int i = array.length - 1; i > 0; i--){
            int randomIndex = randomGenerator.nextInt(i + 1);
            // swap
            int a = array[randomIndex];
            array[randomIndex] = array[i];
            array[i] = a;
        }
    }
}

如果您的目标是拥有一个 int 数组,并且每次您想添加一个随机 int 检查它是否还不存在,请尝试使用此算法来获得一个带有排除项的随机 int:

public int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
    int random = start + rnd.nextInt(end - start + 1 - exclude.length);
    for (int ex : exclude) {
        if (random < ex) 
            break;

        random++;
    }
    return random;
}

有关如何使用它的信息,请参阅this SO answer here。唯一的问题是 excludes-array,它每次都应该改变大小,因此它只包含排除的 int,而不是在创建大小为 10 的 int-array 时默认的 0。否则 exclude.length 总是返回 10 ,使算法无用。

【讨论】:

【解决方案3】:

写一个有缺陷的洗牌算法很容易,这就是为什么有一个好的洗牌器内置:

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)

【讨论】:

    【解决方案4】:

    我找到了this,这可能是您正在寻找的解决方案..

    function shuffle(array) {
      var copy = [], n = array.length, i;
    
      // While there remain elements to shuffle…
      while (n) {
    
        // Pick a remaining element…
        i = Math.floor(Math.random() * array.length);
    
        // If not already shuffled, move it to the new array.
        if (i in array) {
          copy.push(array[i]);
          delete array[i];
          n--;
        }
      }
    
      return copy;
    }
    

    用法:

    public void displayArray()
    {
      var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      shuffle(arr);
      System.out.println(Arrays.toString(arr));
    }
    

    【讨论】:

      【解决方案5】:

      如果您不想在列表中出现重复元素,为什么不使用HashSet&lt;Integer&gt;

      稍后您可以根据自己的意愿将它们转换为数组。

      【讨论】:

      • LinkedHashSet 怎么样?
      猜你喜欢
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多