0
public class Main {
    public static void main(String[] args) {
     String[] piuHigh = { "Destri", "fff", "qbf", "imprinting", "site",
               "Hyn", "error", "gloria", "paved", "fullmoon",
               "don't remember kpop", "creedFull"};
    }
}

Here's the list and I'm trying to choose 4 random items from the array

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35

2 Answers2

1

You can use Random to retrieve the random numbers from 0 to piuHigh.length - 1.

public static void main(String... args) {
    String[] piuHigh = { "Destri", "fff", "qbf", "imprinting", "site",
            "Hyn", "error", "gloria", "paved", "fullmoon",
            "don't remember kpop", "creedFull" };
    String[] fourRandomItems = getRandomItems(piuHigh, 4);
}

public static String[] getRandomItems(String[] arr, int total) {
    String[] res = new String[total];
    Random random = new Random();

    for (int i = 0; i < res.length; i++)
        res[i] = arr[random.nextInt(arr.length)];

    return res;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

If you want to chose them randomly but not repeat any, then this would be one way to do it. This avoids shuffling the entire list which isn't necessary for small sample sizes. So it only does as much of a shuffle as required to ensure you don't get repeats. This does alter the list order but does not modify the contents.

String[] piuHigh = { "Destri", "fff", "qbf", "imprinting", "site",
           "Hyn", "error", "gloria", "paved", "fullmoon",
           "don't remember kpop", "creedFull"};

    
String[] items = getItems(6,  piuHigh);

for (String s : items) {
    System.out.println(s);
}

prints something like

paved
Destri
error
fff
creedFull
don't remember kpop
  • first check to ensure there are enough items.
  • then select one item at random.
  • save it for return
  • then swap that with the one at the end of the given list
  • last is then updated to avoid re-choosing the item just chosen.
public static String[] getItems(int amount, String[] source) {
    if (amount > source.length) {
        throw new IllegalArgumentException("Insufficient items");
    }
    String[] selection = new String[amount];
    Random r = new Random();
    int last = source.length;
    for (int i = 0; i < amount; i++) {
        int select = r.nextInt(last);
        String item = source[select];
        selection[i] = item;
        source[select] = source[--last];
        source[last] = item;
    }
    return selection;
}
WJS
  • 36,363
  • 4
  • 24
  • 39