【发布时间】:2010-10-23 01:36:29
【问题描述】:
下面是我被要求做的一个练习的实现(参见 cmets)。它有效,我发布它的原因是函数 checkMiracle 看起来应该包含在一个更小的代码循环中 - 我正在写出同样的东西加上十次。问题是,我似乎找不到更短的方法。那么我的问题是,有人可以指出我减少此清单中代码的任何方向,也许需要考虑一些使其更紧凑或“聪明”的编码方式。任何帮助表示赞赏。 (练习表在 JCF 上,所以他强迫我们使用集合来编写代码)
/*A 10-digit decimal number N is said to be miraculous if it contains each of the ten decimal digits, and if
the 2-digit number consisting of the first two (most significant, i.e. leftmost) digits of N is divisible by
2, the 3-digit number consisting of the first three digits of N is divisible by 3, and so on up to and including
that N itself is divisible by 10. Write a program to discover a miraculous number (there really is one).
Proceed by making a list of the ten decimal digits, and repeatedly shuffling them until you chance upon an
arrangement that constitutes a miraculous number.
(Note: Type long rather than int is needed for 10-digit decimal integers.) */
import java.util.*;
public class Miracle {
static private long miracleNum = 0;
static private ArrayList<Integer> listing = new ArrayList<Integer>();
static String castValue = "";
public static void main(String[] args) {
for(int i = 0; i < 10; i++) listing.add(i);
Collections.shuffle(listing);
while(listing.get(0)==0) Collections.shuffle(listing); //make sure the number doesnt start with zero
while(!(checkMiracle(listing))) Collections.shuffle(listing);//keep changing it until we get a miracle number
for(long l : listing) castValue += l;
miracleNum = Long.parseLong(castValue);
System.out.println("Miracle num: " + miracleNum);
}
static public boolean checkMiracle(ArrayList<Integer> l) {
long checkValue = Long.parseLong("" + l.get(0) + l.get(1));
if(checkValue %2 != 0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2));
if(checkValue %3 != 0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3));
if(checkValue %4 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4));
if(checkValue %5 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4) + l.get(5));
if(checkValue %6 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4) + l.get(5) + l.get(6));
if(checkValue %7 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4) + l.get(5) + l.get(6) + l.get(7));
if(checkValue %8 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4) + l.get(5) + l.get(6) + l.get(7)+ l.get(8));
if(checkValue %9 !=0) return false;
checkValue = Long.parseLong("" + l.get(0) + l.get(1) + l.get(2) + l.get(3) + l.get(4) + l.get(5) + l.get(6) + l.get(7)+ l.get(8) + l.get(9));
if(checkValue %10 !=0) return false;
return true;
}
}
【问题讨论】:
标签: java collections logic