根据上排给出十个数,在其下排填出对应的十个数, 要求下排每个数都是上排对应位置的数在下排出现的次数。上排的数:0,1,2,3,4,5,6,7,8,9。
答案:先明确两点:
下排数字所有和肯定为10
下排数字对应位置的值大于1。
明白后看程序:
public class T {
public static void main(String [] args) {
int a[] = new int[10];
int result[]=new int[10];
Arrays.fill(a, 0);
Arrays.fill(result, 0);
int count =0;
int next =0;
for(int j=0;j<10;j++){
a[0] = j; //逐一试探a[0]位置的值,肯定位于0-9
next = a[0];//下一个位置
count=a[0]; //当前数组所有值的和
while(count<10){
a[next]++; //跳到一下个位置,令其值+1
count++; //总和加1
next = a[next];//确定下一个位置
}
for(int k =0;k<10;k++){
result[a[k]]++; //核对数组中的值
}
if(Arrays.equals(a, result)){ //如果相等,证明是对的,打印
System.out.println(Arrays.toString(a));
break;
}
else{ //否则重置result 和a数组,继续下一轮试探。
Arrays.fill(result, 0);
Arrays.fill(a, 0);
}
}
}
}