考研复试时候一道暴简单的算法题,就是没有调出来。4个数算24。晕啊
今天在两个小时(一小时思考一小时编程)里就轻松完成了唉。感觉自己的coding还是不熟练,代码写的也比较幼稚,嗯,需要强化。
偷了点懒没有写注解。
import java.io.IOException;
class Cal {
String[] buf = new String[4];
int count = 0;
public boolean bingo24(double[] number) {
if(number.length==1) {
if(Math.abs(number[0] - 24) < 0.01) return true;
else return false;
} else {
for(int i=0;i<number.length;i++)
for(int j=i+1;j<number.length;j++) {
double[] temp = new double[number.length-1];
for(int k=0;k<j;k++) temp[k]=number[k];
for(int k=j;k<number.length-1;k++) temp[k]=number[k+1];
temp[i]=number[i]+number[j];
if(bingo24(temp)) {
buf[count++] = number[i] + "+" + number[j] + "=" + temp[i] + ";/n";
return true;
}
temp[i]=number[i]-number[j];
if(bingo24(temp)) {
buf[count++] = number[i] + "-" + number[j] + "=" + temp[i] + ";/n";
return true;
}
temp[i] = number[j] - number[i];
if (bingo24(temp)) {
buf[count++] = number[j] + "-" + number[i] + "=" + temp[i] + ";/n";
return true;
}
temp[i]=number[i]*number[j];
if (bingo24(temp)) {
buf[count++] = number[i] + "*" + number[j] + "=" + temp[i] + ";/n";
return true;
}
if(number[j]!=0){
temp[i] = number[i] / number[j];
if (bingo24(temp)) {
buf[count++] = number[i] + "/" + number[j] + "=" + temp[i] + ";/n";
return true;
}
}
if (number[i] != 0) {
temp[i] = number[j] / number[i];
if (bingo24(temp)) {
buf[count++] = number[j] + "/" + number[i] + "=" + temp[i] + ";/n";
return true;
}
}
}
}
return false;
}
public static void main(String args[]) {
byte[] buffer = new byte[64];
System.out.print("请输入四个整数,我给出算法得出24,数字之间用空格隔开,输完回车:");
try {
System.in.read(buffer);
} catch (IOException e){
System.err.print(e);
}
double[] number = new double[4];
int readCount = 0;
StringBuffer readNumberBuf = new StringBuffer();
for (int i=0;i<buffer.length;i++) {
if(buffer[i]>='0'&&buffer[i]<='9') readNumberBuf.append((char)buffer[i]);
else if(buffer[i] == '/n'){
number[readCount++] = Double.parseDouble(readNumberBuf.toString());
readNumberBuf = new StringBuffer();
break;
} else {
number[readCount++] = Double.parseDouble(readNumberBuf.toString());
readNumberBuf = new StringBuffer();
}
}
Cal cl = new Cal();
if(cl.bingo24(number)) {
for(int i=2;i>=0;i--) System.out.print(cl.buf[i]);
}
else System.out.print("no solution!");
}
}