How to generate a random number with Java from given list of numbers

14,720

Solution 1

Put the numbers in an ArrayList and use Collections.shuffle(arrayList);

Solution 2

If you just want to select one random number only, or want to select multiple random numbers with reinsertion (i.e. allow possibility of selecting the same number multiple times), you can generate a random index:

List<Integer> lst = ....;
int index = new Random().nextInt(lst.size());
Integer randomeValue = lst.get(index);

You can use an array instead as well. This requires O(1) for each selection.

If you need to select multiple distinct random numbers from the list, then using Collections.shuffle() and iterating through the list would be a better solution. This requires O(n) for all the queries.

Share:
14,720
Tharindu Madushanka
Author by

Tharindu Madushanka

Full Name : Horagoda Tharindu Madushanka Gamage Name with Initials: H T M Gamage Age : 33+ Education : University of Kelaniya, Sri Lanka - MPhil in Computer Science (2018-Present) University of Moratuwa , Sri Lanka - BSc (Hons) in Information Technology (2006-2010) School: Nalanda College, Colombo 10 Blog: Tharindu Madushanka Head of Mobile at: Vesess (Mar 2018 – Present) Mobile Engineer at: Vesess (Jan 2016 – Present) Developer, iOS at: RebelMouse (Feb 2013 – Aug 2016) Remote Technical Lead, iOS at: ElegantMedia (Feb 2013 – June 2013) Senior Software Engineer / Software Engineer, iOS at: Cyber LMJ / Elephanti (Feb 2011 – Mar 2013) Software Engineer, iOS at: Silk Outsourcing (Pvt.) Ltd (Aug 2010 – Feb 2011) Associate Software Engineer / Intern at: hsenid – hSenid Mobile (Apr 2008 – May 2010)

Updated on July 14, 2022

Comments

  • Tharindu Madushanka
    Tharindu Madushanka almost 2 years

    Assume I have an array/vector of numbers like 1,3,7,9 then I need to guess a number from this list randomly. Using Random class in Java it seems like not possible to do this. Could anyone kindly help me to tell a way to do this kind of thing. I have to change the list of numbers used to generate random number. I am trying to implement a strategy to play battleship game automatically as an assignment. Kindly help me to do this ?