找出随机抽查数字

  闲来无事,做一个简单随机查找数字小程序,闲的发慌,因为具体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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值