Yahoo奇摩知識+ 將於 2021 年 5 月 4 日 (美國東部時間) 終止服務。自 2021 年 4 月 20 日 (美國東部時間) 起，Yahoo奇摩知識+ 網站將會轉為唯讀模式。其他 Yahoo奇摩產品與服務或您的 Yahoo奇摩帳號都不會受影響。如需關於 Yahoo奇摩知識+ 停止服務以及下載您個人資料的資訊，請參閱說明網頁。

# JAVA做Hanoi tower及pseudo-random

Create a Java program to solve the problem of Hanoi tower which gets the number of disks (N) from the keyboard and print out the execution time. Test the program for: 1. N = 50 2. N = 100

Write the code to print out how long it takes to generate the pseudo-random integer 11111 if the initial seed is 100 and the range of pseudo-random integers is 0 through 20000.

### 1 個解答

• 8 年前
最佳解答

請參考我的做法

import java.util.*;

public class Y4391 {

public static void main(String args[]) {

int n;

Scanner scan = new Scanner(System.in);

System.out.print("Enter the number of disks: ");

n = Integer.parseInt(scan.nextLine());

long start = System.currentTimeMillis();

move(n, 'A', 'B', 'C');

long end = System.currentTimeMillis();

System.out.println("Execution time: " +

(end - start) / 1000D + " seconds");

// Pseudo-random

pseudoRandomTime(100, 20000, 11111);

}

public static void move(int n, char a, char b, char c) {

if (n == 1)

; // System.out.println("Disk " + n + " from " + a + " to " + c);

else {

move(n - 1, a, c, b);

// System.out.println("Disk " + n + " from " + a + " to " + c);

move(n - 1, b, a, c);

}

}

public static void pseudoRandomTime(int seed, int high, int target) {

long start = System.currentTimeMillis();

Random r = new Random(seed);

while (true) {

int x = r.nextInt(high);

if (x == target) break;

}

long end = System.currentTimeMillis();

System.out.println("Pseudo-Random execution time: " +

(end - start) / 1000D + " seconds");

}

}

2013-04-02 17:05:46 補充：

我試著跑了一下, 應該沒有錯...不用改吧