-4

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]);

    }
}
nitishagar
  • 9,038
  • 3
  • 28
  • 40
Mert
  • 3
  • 2
  • 1
    Can you include what you have tried? –  Dec 14 '14 at 03:28
  • You can ask us help. But you can't order us write code, unless you pay. – Oriol Dec 14 '14 at 03:29
  • 1
    We are not here to do your assignment for you. Please post the code you have written so far and a more specific question. – Marv Dec 14 '14 at 03:30
  • Sorry, I forgot it. Here I used edit. – Mert Dec 14 '14 at 03:32
  • Okay. Now what is your question? – Marv Dec 14 '14 at 03:35
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – worldofjr Dec 14 '14 at 03:36
  • it does not work properly. I would like t create an array by user given limit and it needs to be between -limit and limit such as -3,-2,-1,0,1,2,3 and I would like to take a value randomly from these numbers lets say -2 and 3. And lastly I would like to print my array and the random values seperately. – Mert Dec 14 '14 at 03:39
  • Are you allowed to use Math.Random()? – kamoor Dec 14 '14 at 03:49
  • There is no restriction I think :) so, we can use. – Mert Dec 14 '14 at 03:50
  • then answer is given below. Good lk – kamoor Dec 14 '14 at 04:38

1 Answers1

0
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.

kamoor
  • 2,909
  • 2
  • 19
  • 34