Created
August 27, 2021 02:44
-
-
Save yanfeng42/d4baa8b779b5f4c25813e51dcb3a940d to your computer and use it in GitHub Desktop.
1.1.39 关于随机数碰撞的警示
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package life.yanfeng.study.algorithm; | |
import edu.princeton.cs.algs4.In; | |
import edu.princeton.cs.algs4.StdOut; | |
import java.util.Arrays; | |
import java.util.Random; | |
import java.util.concurrent.ThreadLocalRandom; | |
// for 1.1.39 | |
class BinarySearchCase { | |
// 二分查找. 数据必须有序. | |
static int binarySearch(int key, int[] a) { | |
// 数据必须是有序的. | |
int lo = 0; | |
int hi = a.length -1; | |
while (lo <= hi) | |
{ | |
// 被查找的键, 要么不存在, 要么必须存在于 a[lo..hi] 之中. | |
int mid = lo + (hi - lo) / 2; | |
if (key < a[mid]) hi = mid -1; | |
else if (key > a[mid]) lo = mid + 1; | |
else return mid; | |
} | |
return -1; | |
} | |
static void findN(int T) { | |
int[] items = {(int) Math.pow(10, 3), (int) Math.pow(10, 4), (int) Math.pow(10, 5), (int) Math.pow(10, 6)}; | |
for (int i = 0; i < items.length; i++) { | |
int N = items[i]; | |
int sameTotal = 0; | |
for (int j = 0; j < T; j++) { | |
int [] a = new int[N]; | |
int [] b = new int[N]; | |
int min = 100000; | |
int max = 1000000; | |
for (int k = 0; k < N; k++) { | |
a[k] = ThreadLocalRandom.current().nextInt(min, max + 1);; | |
b[k] = ThreadLocalRandom.current().nextInt(min, max + 1);; | |
} | |
sameTotal += countSames(a, b); | |
} | |
double ava = (double) sameTotal / (double) T; | |
StdOut.printf("N=%d\t\tT=%d\t\tava=%g\t\tava/N=%g\n", N, T, ava, ava/(double) N); | |
} | |
StdOut.println("-------"); | |
} | |
static int countSames(int[] a, int[] b) { | |
int count = 0; | |
for (int i = 0; i < a.length; i++) { | |
if (binarySearch(a[i], b) != -1) { | |
count += 1; | |
} | |
} | |
return count; | |
} | |
public static void main(String[] args) { | |
int[] itemTs = {(int) Math.pow(10, 1), (int) Math.pow(10, 2), (int) Math.pow(10, 3)}; | |
for (int i = 0; i < itemTs.length; i++) { | |
findN(itemTs[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
一些有趣的推论: