A set of random values in an int array of a user specified size

859 Views Asked by At

Write a method to generate and return a set of random values in an int array of a user specified size. The values should all be between +/- N, where N is a constant such as 100. Thank you. Here's Mine;

import java.util.*;

public class Test
{

    public static void main(String[] args) 
    {
        int limit, numbers;
        Random random = new Random();
        Scanner scan = new Scanner(System.in);

        System.out.print ("Enter your limit value for your array: ");           //Needs to be positive.
        limit = scan.nextInt();

        int[] list = new int[limit];

        for (int i = 0; i < list.length; i++) 
        {
            System.out.print(list[i] + ", ");
        }

        numbers = random.nextInt(limit - (0 - limit)) + (0 - limit);
        System.out.println (numbers);

        System.out.println (list[numbers]);

    }
}
1

There are 1 best solutions below

0
On
public List<Integer> random(int range, int count){
    List<Integer> result = new ArrayList<Integer>();
    for(int i=0;i<count;i++){
        if(Math.random() > 0.5){
            //adding positive value with probability of 0.5
            result.add((int)(Math.random() * (double)range));
        }else{
            //adding negative value with probability of 0.5
            result.add(-1 * (int)(Math.random() * (double)range));
        }

    }
    return result;
}

If you want to create your own random number generator, the easiest one to implement will be Linear Congruential Generator. Read from wiki and try yourself. Ask here if you need help.