15

I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.

Here's what I've done so far:

import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {
        return new double[10];
    }
    
    public static void print(){
        System.out.println(String.join(" ", anArray);
    }

    public static double randomFill() {
        return (new Random()).nextInt();
    }
    
    public static void main(String args[]) {
        // TODO
    }
}

I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!

0009laH
  • 1,960
  • 13
  • 27
JaAnTr
  • 896
  • 3
  • 16
  • 28

15 Answers15

16

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.

idmean
  • 14,540
  • 9
  • 54
  • 83
Samir Ouldsaadi
  • 1,404
  • 2
  • 9
  • 3
9

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 
Mengjun
  • 3,159
  • 1
  • 15
  • 21
3

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

  • Think about a construct that can help you iterate over the array. Is there some sort of construct (a loop perhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill() to the current location of the array.

Note: Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
3

Arrays#setAll

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        double[] anArray = new double[10];
        Arrays.setAll(anArray, i -> Math.random());
        System.out.println(Arrays.toString(anArray));
    }
}

Output of a sample run:

[0.1182317850027168, 0.9437573020895418, 0.2690505524813662, 0.6771923722130754, 0.04893586074165357, 0.42483010937765653, 0.16310798731469023, 0.2541941051963008, 0.9838342001474454, 0.8595732419005068]

Alternatively,

import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        double[] anArray = new double[10];
        
        anArray = IntStream.range(0, anArray.length)
                    .mapToDouble(i -> Math.random())
                    .toArray();
        
        System.out.println(Arrays.toString(anArray));
    }
}

Alternatively,

import java.util.Arrays;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        double[] anArray = new Random().doubles(10).toArray();
        System.out.println(Arrays.toString(anArray));
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

Try this:

public void double randomFill() {
    Random rand = new Random();
    for (int i = 0; i < this.anArray.length(); i++)
        this.anArray[i] = rand.nextInt();
}
ib.
  • 27,830
  • 11
  • 80
  • 100
hawks
  • 114
  • 1
  • 4
2

You could loop through the array and in each iteration call the randomFill method. Check it out:

import java.util.Random;

public class NumberList {
    private static double[] anArray;

    public static double[] list() {  
        return new double[10];
    }

    public static void print() {
        System.out.println(String.join(" ", anArray));
    }


    public static double randomFill() {
        return (new Random()).nextInt();
    }

    public static void main(String args[]) {
        list();
        for(int i = 0; i < anArray.length; i++)
            anArray[i] = randomFill();

        print();
    }
}
0009laH
  • 1,960
  • 13
  • 27
jarz
  • 732
  • 7
  • 20
2

People don't see the nice cool Stream producers all over the Java libs.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
1

You can call the randomFill() method in a loop and fill your array in the main() method like this.

public static void main(String args[]) {
    for (int i = 0; i < anArray.length; i++) {
        anArray[i] = randomFill();
    }
}

You would then need to use rand.nextDouble() in your randomFill() method the array to be filled is a double array. The below snippet should help you get random double values to be filled into your array.

double randomDoubleValue = rand.nextDouble();
return randomDoubleValue;
Rahul
  • 44,383
  • 11
  • 84
  • 103
1

Probably the cleanest way to do it in Java 8:

private int[] randomIntArray() {
   Random rand = new Random();
   return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}
Jeff smith
  • 147
  • 7
1

I tried to make this as simple as possible in Java. This makes an integer array of 100 variables and fill it with integers between 0 and 10 using only three lines of code. You can easily change the bounds of the random number too!

int RandNumbers[]=new int[100];
for (int i=0;i<RandNumbers.length;i++)
    RandNumbers[i]=ThreadLocalRandom.current().nextInt(0,10);
Nolan
  • 11
  • 1
1

Fast and Easy

double[] anArray = new Random().doubles(10).toArray();
Julian
  • 334
  • 4
  • 18
0

You can simply solve it with a for-loop

private static double[] anArray;

public static void main(String args[]) {
    anArray = new double[10]; // create the Array with 10 slots
    Random rand = new Random(); // create a local variable for Random
    for (int i = 0; i < 10; i++) // create a loop that executes 10 times
    {
        anArray[i] = rand.nextInt(); // each execution through the loop
                                        // generates a new random number and
                                        // stores it in the array at the
                                        // position i of the for-loop
    }
    printArray(); // print the result
}

private static void printArray() {
    for (int i = 0; i < 10; i++) {
        System.out.println(anArray[i]);
    }
}

Next time, please use the search of this site, because this is a very common question on this site, and you can find a lot of solutions on google as well.

0

If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.

package edu.iu.common;

import java.util.ArrayList;
import java.util.Random;

public class RandomCentroidLocator {

public static void main(String [] args){
 
 int min =0;
 int max = 10;
 int numCentroids = 10;
 ArrayList<Integer> values = randomCentroids(min, max, numCentroids); 
 for(Integer i : values){
  System.out.print(i+" ");
 }
 
}

private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {

 boolean status = true;
 int count=0;
 for(Integer i : arr){
  if(i==num){
   count++;
  }
 }
 if(count==1){
  status = true;
 }else if(count>1){
  status =false;
 }
 

 return status;
}

// generate random centroid Ids -> these Ids can be used to retrieve data
// from the data Points generated
// simply we are picking up random items from the data points
// in this case all the random numbers are unique
// it provides the necessary number of unique and random centroids
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {

 Random random = new Random();
 ArrayList<Integer> values = new ArrayList<Integer>();
 int num = -1;
 int count = 0;
 do {
  num = random.nextInt(max - min + 1) + min;
  values.add(num);
  int index =values.size()-1;
  if(unique(values, num, numCentroids)){    
   count++;
  }else{
   values.remove(index);
  }
  
 } while (!( count == numCentroids));

 return values;

}

}
0

This will give you an array with 50 random numbers and display the smallest number in the array. I did it for an assignment in my programming class.

public static void main(String args[]) {
    // TODO Auto-generated method stub

    int i;
    int[] array = new int[50];
    for(i = 0; i <  array.length; i++) {
        array[i] = (int)(Math.random() * 100);
        System.out.print(array[i] + "  ");

        int smallest = array[0];

        for (i=1; i<array.length; i++)
        {
        if (array[i]<smallest)
        smallest = array[i];
        }



    }

}

}`

0

Java 8+

You can use ThreadLocalRandom with the Random#doubles method to generate a certain number of random doubles.

import java.util.concurrent.ThreadLocalRandom;
//...
public static double[] list() {
    return anArray = ThreadLocalRandom.current().doubles(10).toArray();
    //Generate 10 random doubles
}

To generate random doubles within a certain range, you can provide two more arguments to Random#doubles.

import java.util.concurrent.ThreadLocalRandom;
//...
private static final double MIN = 0, MAX = 10;
public static double[] list() {
    return anArray = ThreadLocalRandom.current().doubles(10, MIN, MAX).toArray();
    //Generate 10 random doubles between MIN (inclusive) and MAX (exclusive)
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80