一、数字组合
给定一个数组a,其中元素各不相同且都是0~9之间的数字。
给定一个数字n,要求用数组a中的数组组合出一个大于n的十进制数字来,要求组合出来的数字尽量少,数组a中的元素可以使用多次。
关键点:
- 大于n
这个问题没想到需要扫描两遍,扫描一遍只能得到等于n的数字。
import java.util.*;
import java.util.stream.Collectors;
public class Main {
Random r = new Random(0);
int[] generate() {
int[] b = new int[10];
for (int i = 0; i < b.length; i++) b[i] = i;
for (int i = 0; i < b.length; i++) {
int nex = r.nextInt(b.length - i) + i;
int temp = b[i];
b[i] = b[nex];
b[nex] = temp;
}
return Arrays.copyOf(b, r.nextInt(5) + 2);
}
List<Integer> parse(int n) {
List<Integer> a = new ArrayList<>(11);
while (n > 0) {
a.add(n % 10);
n /= 10;
}
for (int i = 0; i < a.size() / 2; i++) {
int temp = a.get(i);
a.set(i, a.get(a.size() - 1 - i));
a.set(a.size() - 1 - i, temp);
}
return a;
}
int upper_eq(List<Integer> a, int x) {
int l = 0, r = a.size();
while (l + 1 < r) {
int mid = (l + r) >> 1;
if (a.get(mid) < x) {
l = mid;
} else if (a.get(mid) >= x) {
r = mid;
}
}
return a.get(r);
}
int upper(List<Integer> a, int x) {
int l = 0, r = a.size();
while (l + 1 < r) {
int mid = (l + r) >> 1;
if (a.get(mid) <= x) {
l = mid;
} else if (a.get(mid) > x) {
r = mid;
}
}
return r;
}
int pack(List<Integer> a) {
int s = 0;
for (int i : a) {
s = s * 10 + i;
}
return s;
}
int solve(int a[], int n) {
if (a.length == 0) return -1;
if (a.length == 1 && a[0] == 0) return -1;
List<Integer> arr = new ArrayList<>(a.length + 1);
for (int anA : a) arr.add(anA);
arr.sort(Comparator.comparing(x -> x));
int first = arr.get(0) == 0 ? arr.get(1) * 10 : arr.get(0) * 10 + arr.get(0);
arr.add(first);
List<Integer> bits = parse(n);
boolean flag = false;
for (int i = 0; i < bits.size(); i++) {
if (flag) {
bits.set(i, arr.get(0));
} else {
int x = upper_eq(arr, bits.get(i));
if (x != bits.get(i)) {
flag = true;
}
bits.set(i, x);
}
}
for (int i = bits.size() - 1; i >= 0 && !flag; i--) {
int x = upper(arr, bits.get(i));
if (x < 10) {
flag = true;
bits.set(i, x);
}
}
if (!flag) {
bits.set(0, arr.get(arr.size() - 1));
}
return pack(bits);
}
String tos(int[] a) {
return "[" + Arrays.stream(a).mapToObj(x -> x + "").collect(Collectors.joining(",")) + "]";
}
Main() {
for (int i = 0; i < 10; i++) {
int[] a = generate();
int n = r.nextInt(10000000);
System.out.println(tos(a) + " " + n + " " + solve(a, n));
}
}
public static void main(String[] args) {
new Main();
}
}
二、max(x,y)的期望
已知x和y都是0到1上的均匀分布,求max(x,y)的期望。
$\int_{0}^{1} 1-m^2 dm=\frac{2}{3}$
$m^2$表示当x<m
且x<m
的概率,用1减去它表示max(x,y)不小于m的概率。
import java.util.*;
import java.util.stream.Collectors;
public class Main {
Random r = new Random(0);
Main() {
double s = 0;
int cnt = 0;
for (int i = 0; i < 10000; i++) {
double x = r.nextDouble(), y = r.nextDouble();
s += Math.max(x, y);
cnt++;
}
System.out.println(s / cnt);
}
public static void main(String[] args) {
new Main();
}
}
原文地址:https://www.cnblogs.com/weiyinfu/p/9627459.html
时间: 2024-11-05 22:39:24