1
votes

Can you tell me how to print all array of Strings , randomly , but without duplicates. I dont want to use Lists, Collecton.shuffle.

I try:

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

I want to print all names, but shuffled and only once. Something like this:

name4, name1, name2, name5, name3

2
What is wrong with Collections.shuffle? - Tim Biegeleisen
What do you mean shuffled only once? Do you mean you want it to keep on printing a random name from the list? Or do you want it to print the entire list in a random order, one line after the other?? - Lakshya Goyal

2 Answers

0
votes

Here is the code, but what you are asking is unnecessarily complicating code:

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

Trying resolve this using javascript, felt very interesting about this logic.

This is the algorithm I was trying: find

  1. a random number (n) in between 0 and number of items in array which is not printed yet.
  2. print the item in that position (names[n])
  3. switch the element with the last item in array
  4. Repeat until we finish all the items in array.

This algorithm will use only single array and after printing all items we will have a updated list in the reverse order its printed.

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