arrays - Random element generation without duplicates Java -
this question has answer here:
- creating random numbers no duplicates 15 answers
- best way pick random subset collection? 10 answers
i trying code run without duplicates having no success researching area.
its start of question doing ask user input missing element. however, when generate random elements getting duplicates
import java.util.random; public class questiononea2 { public static void main(string[] args) { string[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"}; random numbergenerator = new random(); (int = 0; < 5; i++) { int nextrandom = numbergenerator.nextint(6); system.out.println(fruit[nextrandom]); } } }
there many different approaches can consider, depending on how flexible algorithm should be.
taking 5 random elements list of 6, same selection 1 element list of 6 don't choose. inflexible, easy.
another approach delete element list, , decrease maximum random number. in cause advice not use string[]
.
Comments
Post a Comment