Presentation is loading. Please wait.

Presentation is loading. Please wait.

Simulation 直接模擬 (I) Date: June 3, 2009 Introducer: Hsing-Yen Ann.

Similar presentations


Presentation on theme: "Simulation 直接模擬 (I) Date: June 3, 2009 Introducer: Hsing-Yen Ann."— Presentation transcript:

1 Simulation 直接模擬 (I) Date: June 3, 2009 Introducer: Hsing-Yen Ann

2 2 問題 給定數值 P ,計算 P 所在的座標位置。 … 13 12 11 10 25 第一層:紅色 14 3 2 9 24 第二層:紫色 … 15 4 1 8 23 … 第三層:綠色 16 5 6 7 22 以此類推 17 18 19 20 21 … 方框內的值= n 2 n = 1,3,5,7,9… 則 n 2 < P <= (n+2) 2 。

3 3 解法 直接模擬,一次一格,需要 O(P) time 。 直接模擬,一次一行,需要 O(P 0.5 ) time 。 用數學公式計算出 P 在螺旋狀的第幾層, 需要 O(1) time 。

4 4 圖解 O(P 0.5 ) time 31 30 29 28 27 26 49 32 00 00 00 00 25 48 33 00 00 00 00 00 47 34 00 00 00 00 00 46 35 00 00 00 00 00 45 36 00 00 00 00 00 44 37 38 39 40 41 42 43 line column side

5 5 Sample Code (1/2) x = y = 0; curP = sideLen = 1; // simulation while (curP < P) { // side 1 y += Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 2 x -= Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 3 y -= Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 4 x += Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); sideLen++; }

6 6 Sample Code (2/2) // 用數學公式算出 P 在螺旋狀的第幾層 // (x, y, curP, sideLen) // simulation while (curP < P) { // side 1 y += Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 2 x -= Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 3 y -= Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); // side 4 x += Math.min(sideLen, P - curP); curP += Math.min(sideLen, P - curP); sideLen++; }


Download ppt "Simulation 直接模擬 (I) Date: June 3, 2009 Introducer: Hsing-Yen Ann."

Similar presentations


Ads by Google