汉诺塔、猴子吃桃、数组移除、排列组合

来源:互联网 发布:linux 电路设计软件 编辑:程序博客网 时间:2024/05/20 05:26

汉诺塔:

static void move(int count, String from, String cache, String to) {
if (count < 1) return;
if (count == 1) {
System.out.println(from + " to " + to);//如果小于2个盘子,直接移动到目标塔
} else {//如果大于或等于2个盘子
move(count - 1, from, to, cache);//将除最下面的盘子以外的其它盘子移动(以目标塔为缓冲塔)到缓冲塔
move(1, from, cache, to);//将剩余的一个盘子移动到目标塔
move(count - 1, cache, from, to);//将缓冲塔上的盘子移动(以源塔为缓冲塔)到目标塔
}
}

猴子吃桃:一个猴子摘了一堆桃子,第一天吃了桃子的一半后又吃了一个,第二天也吃了剩下的桃子的一半后又吃了一个,以此吃下去,到了第十天还剩下一个桃子,问当初猴子总摘了多少个桃子?

static int getCount(int totalDay) {
int count = 1;
while (--totalDay > 0) {
count = (count + 1) * 2;
}
return count;
}

数组移除:

//移除数组中指定坐标的元素
static Object[] remove(Object[] os, int index) {
if (index >= os.length || index < 0)
return null;
Object[] dest = new Object[os.length - 1];
System.arraycopy(os, 0, dest, 0, index);
System.arraycopy(os, index + 1, dest, index, os.length - index - 1);
return dest;
}

排列组合:

//打印数组的排列组合
static void plzh(String prefix, Object[] arr, int tarCount) {
// ArrayHelper arrayHelper = ArrayHelper.getInstance();
if (tarCount == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < arr.length; i++) {
//plzh(prefix + arr[i], arrayHelper.remove(arr, i), tarCount - 1);
plzh(prefix + arr[i], remove(arr, i), tarCount - 1);
}
}
}