1 / 6

Simulation 直接模擬 (I)

Simulation 直接模擬 (I). Date: June 3, 2009 Introducer: Hsing-Yen Ann. 問題. 給定數值 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 …

asta
Download Presentation

Simulation 直接模擬 (I)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. 圖解 • O(P0.5) time side 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

  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. 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++; }

More Related