















前几天无聊, 舍友拿来一玩具"九连环". 把玩之中, 觉得过程类似"汉诺塔", 遂考虑写个程序模拟一下.
其实过程挺简单的, 关键在于, "九连环"中除了第一个环, 其它所有的环都套着它前面的环, 因此, 要操作第 n 个环 (安装或者拆卸), 则第 n-1 个环必须在上面, 而第 n-2 个之前的所有环都不能在上面.
两个关键函数:
1. 装上所有的环:
Fill(int rings) {
// 两个基本情况
if rings == 1 then
把第一个装上;
endif
if rings == 2 then
把第一个装上;
把第二个装上;
endif
// 第
把第
rings 个装上;把前
rings-2 个都装上; // 调用 Fill(rings-2)2.
卸下所有的环:if rings == 2 then
把第
rings 个卸下;
// 卸掉第 rings-1 个, 需要将前 rings-2 个都在装上
把前
import java.io.*;
import java.util.*;public class NineRingsNew {private Vector<Integer> rings;
private void fill(int nRings) {
if (nRings == 1) {
rings.add(1);
System.out.println("Put ON Ring<1> ---> " + rings.toString());
return;
} else if (nRings == 2) {
rings.add(1);
System.out.println("Put ON Ring<1> ---> " + rings.toString());
rings.insertElementAt(2, rings.indexOf(1));
System.out.println("Put ON Ring<2> ---> " + rings.toString());
return;
}
fill(nRings - 1);
clean(nRings - 2);
rings.insertElementAt(nRings, rings.indexOf(nRings - 1));
System.out.println("Put ON Ring<" + nRings + "> ---> " + rings.toString());
fill(nRings - 2);
}
clean(nRings - 2);
rings.removeElement(nRings);
System.out.println("Put OFF Ring<" + nRings + "> ---> " + rings.toString());
fill(nRings - 2);
clean(nRings - 1);
}
System.out.println("\n" +
"----------------------------------------------------------\n" +
"--------------------- NINE RINGS ---------------------\n" +
"----------------------------------------------------------\n" +
" This program is to simulate a Chinese traditional \n" +
" intellectual toy called \"Jiu Lian Huan\". \n" +
" Please input two values:\n" +
" Num of Rings: an integer belongs in [1, 9];i\n" +
" Operation : a String \"on\" or \"off\" indicates\n" +
" whether you want to put all rings\n" +
" ON or OFF (ignore case)\n" +
" Input \"q\" to quit.\n" +
"----------------------------------------------------------");
Scanner sc =
new Scanner(System.in);nrn.opRings(nRings, on_off);
System.out.println();
System.out.print("Do you want to quit(q/y/n)? ");
quit = sc.next();
System.out.println("---------------------------------------------");
System.out.println("Thank you for using this program. Goodbye!\n"
);}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。