-3

I have to write a program that generate random integers from 0 to 9 for 1000 times and count repeated numbers. So output should be like:

0 used 123 times, 1 used 89 times, 2 301 times, . . 9 used 23 times

I must use math.random for this. I can generate numbers but how can I use array and loop for this?

Thanks.

2

2 Answers 2

1

If you can use java.util.Random, you don't need array and loop. Try this.

System.out.println(new Random().ints(1000, 0, 10)
    .boxed()
    .collect(Collectors.groupingBy(i -> i, Collectors.counting()))
    .entrySet().stream()
    .map(e -> String.format("%d used %d times", e.getKey(), e.getValue()))
    .collect(Collectors.joining(", ")));

result

0 used 109 times, 1 used 97 times, 2 used 81 times, 3 used 107 times, 4 used 121 times, 5 used 100 times, 6 used 97 times, 7 used 96 times, 8 used 80 times, 9 used 112 times
Sign up to request clarification or add additional context in comments.

1 Comment

Nice demonstration of the power of streams and lambdas. Plus 1
0

Try this code you will get your desired output:

**import** java.util.HashMap;  
**import** java.util.Map;

public **class** RandomCounting  
{

    static **Map**<Integer,Integer> result=new **HashMap**<Integer,Integer>();
    static int[] a=new int[10];
    public static void main(String[] args)
    {
        for (int i = 0; i < 1000; i++)
        {
            int value=(int)(Math.random()*10);
            //System.out.print(value+" ");
            switch(value)
            {
            case 0:result.put(0,a[0]++);break;
            case 1:result.put(1,a[1]++);break;
            case 2:result.put(2,a[2]++);break;
            case 3:result.put(3,a[3]++);break;
            case 4:result.put(4,a[4]++);break;
            case 5:result.put(5,a[5]++);break;
            case 6:result.put(6,a[6]++);break;
            case 7:result.put(7,a[7]++);break;
            case 8:result.put(8,a[8]++);break;
            case 9:result.put(9,a[9]++);break;
            }
            //System.out.print(value+" ");
        }

        for (int i = 0; i < 10; i++)
        {
            System.out.println(i+" used "+result.get(i)+" times");
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.