找出随机抽查数字

  闲来无事,做一个简单随机查找数字小程序,闲的发慌,因为具体user没有给出下一阶段的工作信息。

1 - 10000 随机自然数字(无重复10000个数字), 随机删除其中一个数字, 怎么快速找出你刚才删除的那个数字?

 

package com.suanfa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zhaoxiaobo
 * @createdTime:Aug 16, 2012
 * description :
 *  1 - 10000 随机自然数字(无重复10000个数字), 随机删除其中一个数字, 怎么快速找出你刚才删除的那个数字?
 * method1: 找出按照排序的规律,两者之间偏差在大于1以上的就是,即位于他们之间的就是。
 * method2: 既然是数字,我们顺利就要考虑数字的特殊性,比如数字计算内在规则,数字之间的等差关系,存在和差既定性。
 */
public class SearchRandomDigit {

    private static final int TOTAL_NUMBER = 10000; // total number 1 - 10000
    private static final List<Integer> randomList = new ArrayList<Integer>();

    public static void main(String[] args) {
        //generate random 1-10000 digits
        generateRandomDigit();
        //generate one random (1 <= digit <= 10000)
        Integer random = getRandomDigit();
        //System.out.println("count 1=== " + randomList.size());
        Integer result = 0;
        System.out.println("Random digit === " + random);
        if (removeRandomDigit(random)) {
            result = findRandomDigitMethod1();
            result = findRandomDigitMethod2();
        }

        System.out.println("Find result === " + result);
    }

    private static void generateRandomDigit() {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < TOTAL_NUMBER; i++) {
            list.add(i + 1);
        }
        Collections.shuffle(list);
        for (Integer integer : list) {
            //System.out.println(integer);
            randomList.add(integer);
        }
    }

    private static int findRandomDigitMethod1() {
        int len = randomList.size();
        int result = 0;
        Collections.sort(randomList);
        for (int i = 0; i < len - 1; i++) {
            if (randomList.get(i + 1) - randomList.get(i) == 2) {
                result = (randomList.get(i + 1) + randomList.get(i)) / 2;
                break;
            }
        }
        return result;
    }

    private static int findRandomDigitMethod2() {
        //all data summation
        int sum = 0;
        //all data summation which removed one data
        int sum_ = 0;
        for (int i = 1; i <= TOTAL_NUMBER; i++) {
            sum += i;
        }
        for (Integer atom : randomList) {
            sum_ += atom;
        }
        return sum - sum_;
    }

    private static boolean removeRandomDigit(Integer random) {
        return randomList.remove(random);
    }

    private static Integer getRandomDigit() {
        return (int)(Math.random() * TOTAL_NUMBER) + 1;
    }
}

 

你可能感兴趣的:(数字)