学会制作对数器
题目一
假设有一个数组arr,用户总是频繁的查询arr中某一段的累加和
你如何组织数据,能让这种查询变得便利和快捷?
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
int[] arr = randomArr(1, 5, 10);
long a = sum(arr, 2, 7);
long b = arrSum2(arr, 2, 7);
if (a != b)
System.out.println("错了");
}
}
static long sum(int[] arr, int begin, int end) {
int sum = 0;
for (int i = begin; i <= end; i++) {
sum += arr[i];
}
return sum;
}
static long arrSum(int[] arr, int begin, int end) {
int sum = 0;
int[] a = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
a[i] = sum;
}
if (begin == 0) {
return a[end];
} else {
return a[end] - a[begin - 1];
}
}
static long arrSum2(int[] arr, int begin, int end) {
long[][] a = new long[arr.length][arr.length];
for (int j = 0; j < arr.length; j++) {
for (int i = j; i < arr.length; i++) {
a[j][i] = arrSum(arr,j,i);
}
}
return a[begin][end];
}
static int[] randomArr(int min, int max, int length) {
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * (max - min + 1)) + min;
}
return arr;
}
}
题目二
如果利用Math.random()函数,
定义一个方法,传入x(0<x<1),随机传出一个x的平方的相近数
public class A {
public static void main(String[] args) {
double a = Math.random();
System.out.println(a * a);
System.out.println(f(a));
}
static double f(double x) {
double count = 0;
int times = 1000000;
for (int i = 0; i < times; i++) {
if (x > Math.max(Math.random(), Math.random()))
count++;
}
return count / times;
}
}
题目三
用一个能随机生成int类型1-5的方法生成一个能随机生成int类型1-7的方法和随机生成int类型4-87的方法
用01不等概率发生器生成01等概率发生器
public class Random {
public static void main(String[] args) {
double count = 0;
int times = 1000000;
for (int i = 0; i < times; i++) {
if (f0t1_() == 0)
count++;
}
System.out.println(count / times);
}
static int f1t5() {
return (int) (Math.random() * 5) + 1;
}
static int f0t1() {
int num = -1;
do {
num = f1t5();
} while (num == 3);
return num < 3 ? 0 : 1;
}
static int f1t7() {
int a = -1;
do {
a = (f0t1() << 2) + (f0t1() << 1) + f0t1();
} while (a == 7);
return a + 1;
}
static int f4t87() {
int a = -1;
do {
a = (f0t1() << 6) + (f0t1() << 5) + (f0t1() << 4) + (f0t1() << 3) + (f0t1() << 2) + (f0t1() << 1) + f0t1();
} while (a > 83);
return a + 4;
}
static int no() {
if (f1t5() > 4)
return 0;
return 1;
}
static int f0t1_() {
int a = -1;
int b = -1;
do {
a = no();
b = no();
} while ((a == 1 && b == 1) || (a == 0 && b == 0));
if (a == 1 && b == 0)
return 0;
return 1;
}
}