There is an array of 1 to 100 numbers, random extraction of 99 numbers, how to get the number not drawn

Posted by SoulAssassin on Fri, 11 Oct 2019 18:26:45 +0200

In fact, the problem is very simple. It's written in two arrays.
Think more and you'll come out.
Two classes are used

package cn.kgc.springtest2.demo3;

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

public class FindNum {
    public int find(int[] arr) {
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        //Initialize, put 1-100 in map, value initial value is 0
        for (int i = 1; i <= 100; i++) {
            map.put(i, 0);
        }
        //Traverse the array, find a number, and update the corresponding vaule to 1
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], 1);
        }
        //Traversing through the map, if value is found to be 0, the abandoned number is found and returned
        for (Map.Entry<Integer, Integer> m : map.entrySet()) {
            if (m.getValue() == 0) {
                return m.getKey();
            }
        }
        //No return 0 was found
        return 0;
    }
}

There are notes in it. Let's take a good look at one.
Here's a test class

package cn.kgc.springtest2.demo3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class test {
    //test
    public static void main(String[] args){
        List<Integer> list=new ArrayList<Integer>();
        int[] arr=new int[99];
        Random rd=new Random();
        //Randomly generate an array of length 99, without duplicate numbers
        while(list.size()<99){
            int a=rd.nextInt(100)+1;
            if(!list.contains(a)){
                list.add(a);
            }
        }
        //Assign values in list s to arrays
        for(int i=0;i<99;i++){
            arr[i]=list.get(i);
        }
        //Sort the array for inspection
        Arrays.sort(arr);
        //View 99 generated numbers
        System.out.println(Arrays.toString(arr));
        int x=new FindNum().find(arr);
        //The console prints out the required number
        System.out.println(x);
    }
}

So we can get it.
Let's see the results.

You can see that there is no 47 arrows.
In fact, there are other ways
We can get the sum of 1 to 100, and then we can get the sum of 99 random numbers, and then subtract the sum of 99 random numbers. Their difference is the number that they did not draw.
You can write this by yourself.

Topics: Java