Leo
Leo

Reputation: 1809

Get random list from an array?

so, my code like that:

import java.util.Random;
String[] arr= (vars.get("Types")).split(";");
int idx = new Random().nextInt(arr.length);
String type = (arr[idx]);
vars.put("b_type", type);

The array looks like this

` arr = {"id":1, "type_1":1},{"id":2, "type_2":2},{"id":3, "type_3":3},{"id":4, "type_4":4},...'

Could anyone help? I need to get random arr2 from the array 'arr'.

It could be one element like

`arr1 = {id:value, type_1:value}`

or some of them, i.e.

`arr1 = [{"id":1, "type_1":1},{"id":4, "type_4":4}]`

or equivalent arr1 = arr

Upvotes: 1

Views: 807

Answers (1)

Hojjat
Hojjat

Reputation: 825

First you need an random integer value indicating the number of elements of array, then produce random elements and insert into new array.

//number of elements in result array
int count = new Random().nextInt(arr.length);


ArrayList<String> result = new ArrayList<String>();
for(int i=0; i<count; i++){
    //random index of element that must be added to result
    int index = new Random().nextInt(arr.length);
    result.add(arr[index]);
}

just make sure your elements in result array isn't repetitive.

Here's a solution for that: Insert your array element to an ArrayList so you can edit elements

ArrayList<String> myarray = new ArrayList<String>();
for(int i=0; i<arr.length; i++){
    myarray.add(arr[i]);
}

Then inside the for:

for(int i=0; i<count; i++){
    //random index of element that must be added to result
    int index = new Random().nextInt(myarray.length);
    result.add(myarray[index]);
    myarray.remove(index);
}

Upvotes: 2

Related Questions