【问题标题】:Java How to print all Array of Strings, random ,with no duplicatesJava如何打印所有随机的字符串数组,没有重复
【发布时间】:2017-02-25 11:36:46
【问题描述】:

你能告诉我如何随机打印所有字符串数组,但不重复。我不想使用列表,Collecton.shuffle。

我试试:

String names[] = { "name1", "name2", "name3", "name4", "name5" };
System.out.println(names[rand.nextInt(groupMembers.length - 1)]);

我想打印所有的名字,但只是洗牌一次。 像这样的:

名字4,名字1,名字2,名字5,名字3

【问题讨论】:

  • Collections.shuffle 有什么问题?
  • 只洗牌一次是什么意思?你的意思是你希望它继续从列表中打印一个随机名称?或者你想让它以随机顺序打印整个列表,一行接一行??

标签: arrays string random


【解决方案1】:

这是代码,但您要问的是不必要的复杂代码:

public static void main(String [] args) {
        String names[] = { "name1", "name2", "name3", "name4", "name5" }; 
        int upper = names.length;
        int lower = 0;
        int r=0;

        Set<Integer> uniqueList = new HashSet<Integer>();//This is the set which is used to make sure elements in the array are printed only once
        for(int count=0;count<names.length;count++){
            uniqueList.add(count);
        }

        while(!uniqueList.isEmpty()){
            r =  (int) (Math.random() * (upper - lower)) + lower;//generate a random number
            if(uniqueList.contains(r)){//if the random number lies between array length, then print the random name and remove it from set so that it wont print duplicate

                uniqueList.remove(r);
                System.out.println(names[r]);
            }   
        }
    }

【讨论】:

  • 如果它有助于给予支持,或者如果这是您正在寻找的答案,请接受它作为答案
【解决方案2】:

尝试使用javascript解决这个问题,感觉这个逻辑很有趣。

这是我尝试的算法: 找到

  1. 介于 0 和数组中的项目数之间的随机数 (n) 尚未打印。
  2. 在该位置打印项目 (names[n])
  3. 用数组最后一项切换元素
  4. 重复直到我们完成数组中的所有项目。

此算法将仅使用单个数组,并且在打印所有项目后,我们将以相反的顺序得到一个更新的列表。

var names = ["name1", "name2", "name3", "name4", "name5"];

function switchItem(arr, from, to) {
  let temp = arr[from];
  arr[from] = arr[to];
  arr[to] = temp;
  return names;
}

function getRandomUniqueValues(values) {
  for(var i = 0; i < values.length; i++) {
    let randomPosition =  Math.floor(Math.random() * Math.floor(values.length - i -1));
    console.log(values[randomPosition]);
    values = switchItem(values,randomPosition,values.length - 1 - i)
  }
}

getRandomUniqueValues(names);

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多