package zuoye;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//编写程序求123456789之间随机位置放加减,使表达式的和为100,求出这样的表达式
public class Demo2002 {
public static void main(String[] args) {
/*int i = 0;
while (true) {
String str = getstr();
int sum = getsum(str);
if (sum == 100) {
System.out.println(str + "=" + sum);
++i;
}
if (i == 10) {
break;
}
}
*/
Set<String> set = new HashSet<>();
while (set.size() <= 10) {
String str = getstr();
int sum = getsum(str);
if (sum == 100) {
set.add(str + "=" + String.valueOf(sum));
}
}
System.out.println(set);
}
//获取式子
public static String getstr() {
StringBuilder sb = new StringBuilder();
String[] ss = {"+", "-", ""};
Random rd = new Random();
for (int i = 1; i < 9; i++) {
sb.append(i).append(ss[rd.nextInt(ss.length)]);
}
sb.append(9);
return sb.toString();
}
//求和方法
public static int getsum(String str) {
Pattern pt = Pattern.compile("-?\\d+");
Matcher matcher = pt.matcher(str);
int sum = 0;
while (matcher.find()) {
//转成整数并求和
sum += Integer.parseInt(matcher.group());
}
return sum;
}
}
Java 编写程序求123456789之间随机位置放加减,使表达式的和为100,求出这样的表达式
最新推荐文章于 2024-08-19 16:01:20 发布