public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
Answer from Chris Dennett on Stack Overflowpublic static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
You can use the Random generator to generate a random index and return the element at that index:
//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
Videos
You can use IntStream ints() or DoubleStream doubles() available as of java 8 in Random class. something like this will work, depends if you want double or ints etc.
Random random = new Random();
int[] array = random.ints(100000, 10,100000).toArray();
you can print the array and you'll get 100000 random integers.
You need to add logic to assign random values to double[] array using randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray;
}
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray;
}
Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.
public static void main(String args[]) {
list();
print();
}
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7
Use the Random.nextInt(int) method:
final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};
Random random = new Random();
int index = random.nextInt(proper_noun.length);
System.out.println(proper_noun[index]);
This code is not completely safe: one time out of four it'll choose Richard Nixon.
To quote a documentation Random.nextInt(int):
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
In your case passing an array length to the nextInt will do the trick - you'll get the random array index in the range [0; your_array.length)
if you use List instead of arrays you can create simple generic method which get you random element from any list:
public static <T> T getRandom(List<T> list)
{
Random random = new Random();
return list.get(random.nextInt(list.size()));
}
if you want to stay with arrays, you can still have your generic method, but it will looks bit different
public static <T> T getRandom(T[] list)
{
Random random = new Random();
return list[random.nextInt(list.length)];
}
you can try something like this:
import java.util.ArrayList;
import java.util.Random;
public class RandomArrayTest {
public static void main(String[] args) {
System.out.println(RandomArrayTest.randomArrayOfColors(10)); // for example
}
public static ArrayList<String> randomArrayOfColors(int lenOfArray){
String[] colors = {"RED", "GREEN", "BLUE"};
ArrayList<String> rndArray = new ArrayList<String>();
Random rnd = new Random();
for(int i=0; i<lenOfArray; i++){ // populate the array
rndArray.add(colors[rnd.nextInt(colors.length)]);
}
return rndArray;
}
}
The output for example:
[GREEN, GREEN, BLUE, GREEN, RED, BLUE, GREEN, RED, RED, BLUE]
Pseudocode:
colours <- {red, blue, green}
length <- random (0 to maxLength)
repeat length times
colour <- pick random from colours
append colour to outputArray
end repeat
return outputArray
Was that really so difficult?
Your for loop should be
for (int i = 0; i < r; i++)
This is one place I would definitely use streams. They have been around since Java 8 and everyone should be familiar with them. Even those new at coding in Java.
Random r = new Random();
int nElements = 10;
int maxElement = 50;
List<Integer> nums = r.ints(nElements, 1, maxElement+1).boxed().sorted()
.collect(Collectors.toList());
System.out.println(nums);
Here is the explanation.
- The first element to
r.intsis the quantity. The next two arestartandendingrange. Since the range is exclusive, 1 must be added to include themaxElementas a possibility. - Boxed() maps the ints to Integer objects to be collected into a List.
- Sorted() does what you would expect.
- And the collector puts them into a
List
If you want to generate random integer array from an interval, here are the options
Copy// generate 100 random number between 0 to 100
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
//generate 100 random number between 100 to 200
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100) + 100).limit(100).toArray();
You can take input from the user by using a scanner like this -
CopyScanner input= new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = input.nextInt();
Now create a function generateRandomArray(int n) like this -
Copypublic List<Integer> generateRandomArray(int n){
ArrayList<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(1000));
}
return list;
}
Here - random.nextInt(1000) will generate a random number from the range 0 to 1000. You can fix the range as you want.
Now you can call the function with the value n get from the user -
CopyArrayList<Integer> list1 = generateRandomArray(n);
ArrayList<Integer> list2 = generateRandomArray(n);
Hope it will help.
anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.
Might want to re-write it like:
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator;
private ArrayList<Item> catalogue;
public Catalogue()
{
catalogue = new ArrayList<Item>();
randomGenerator = new Random();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item item = catalogue.get(index);
System.out.println("Managers choice this week" + item + "our recommendation to you");
return item;
}
}
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}