Create Java Random from the size of the List -
i have created method randomize list:
public <t> list<t> randomize(list<t> list) { linkedlist<t> randomizedlist = new linkedlist<>(); random random = new random(list.size()); (int = random.nextint(); < list.size(); i++) { randomizedlist.add(list.get(i)); } homecoming randomizedlist; }
the list passing method contains e.g. 5 elements. when creating random random = new random(list.size());
expect when phone call random.nextint()
homecoming me random integer index of list element.
but when phone call random.nextint();
instead of returning number interval [0, 4]
(which expect returned) returns me value of e.g.: -349120689
. gives me java.lang.indexoutofboundsexception: index: -349120689, size: 5
.
why happening , how solve this?
new random(list.size());
sets seed of random number generator list.size();
suggest changing new random()
(which give seed based on current time of system). preferably though, you'd want reuse same random object @ times.
random.nextint();
here you'd want set random.nextint(list.size());
give number 0 list.size() - 1.
even above changes, code give sublist of list starting @ random index , going until end. utilize collections.shuffle(list)
instead.
to real shuffling, need "remember" elements have inserted or not. in pseudo-code, following:
copy original list new one, let's phone call "orig" create new, empty, list, let's phone call "result" as long orig list has elements, element @ random index , add together result list. remove chosen element orig list. return result list. java list random
No comments:
Post a Comment