Java代碼編寫:CS455 Random Walk
全文鏈接:tecdat.cn/?p=29602
Requirement
In this assignment you will write a graphics-based program to do a?random walk, sometimes also known as a drunkard’s walk. This random walk simulates the wandering of an intoxicated person on a square street grid. The drunkard will start out in the middle of the grid and will randomly pick one of the four compass directions, and take a step in that direction, then another step from that new location in a random direction, etc.
This assignment will give you practice with creating classes, using loops, using the java library for random number generation, doing console-based IO, and drawing to a graphics window. Also you’ll get practice in general program development.
Analysis
Randow Walk,即隨機(jī)游走問題,類似布朗運動,物體在下一刻走動的方向完全是隨機(jī)的。本題利用隨機(jī)數(shù)生成器來模擬下一刻的方位。框架使用java的awt包實現(xiàn)了UI部分,我們只需要將隨機(jī)算法加入到提供的框架中。
解題的關(guān)鍵是了解隨機(jī)數(shù)生成器的用法,根據(jù)提供的框架,找到對應(yīng)函數(shù)入口,根據(jù)給定的測試集進(jìn)行調(diào)試即可。
Tips
從測試函數(shù)入口入手
private void testTranslate(Impoint loc, int deltaX, int deltaY) { ? ... ? ImPoint p2 = loc.translate(deltaX, deltaY); ? ... } 復(fù)制代碼
因此我們需要實現(xiàn)ImPoint類,以及translate方法,核心代碼如下
class ImPoint { ? private int x; ? private int y; ? ... ? public Impoint translate(int deltaX, int deltaY) { ? ? Random r = new Random(); ? ? int x = deltaX + nextInt(2) - 1; ? ? int y = deltaY + nextInt(2) - 1; ? ? return new Impoint(x, y); ? } ? ... }