Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- public class KnightMain {
- static int getnewx(int oldx, int rand) {
- int newx = oldx;
- switch (rand) {
- case 0: // NNE
- newx += 1;
- break;
- case 1: // NE
- newx += 2;
- break;
- case 2: // SE
- newx += 2;
- break;
- case 3: // SSE
- newx += 1;
- break;
- case 4: // SSW
- newx -= 1;
- break;
- case 5: // SW
- newx -= 2;
- break;
- case 6: // NW
- newx -= 2;
- break;
- case 7: // NNW
- newx -= 1;
- break;
- default:
- ;
- }
- return newx;
- }
- static int getnewy(int oldy, int rand) {
- int newy = oldy;
- switch (rand) {
- case 0: // NNE
- newy -= 2;
- break;
- case 1: // NE
- newy -= 1;
- break;
- case 2: // SE
- newy += 1;
- break;
- case 3: // SSE
- newy += 2;
- break;
- case 4: // SSW
- newy += 2;
- break;
- case 5: // SW
- newy += 1;
- break;
- case 6: // NW
- newy -= 1;
- break;
- case 7: // NNW
- newy += 2;
- break;
- default:
- ;
- }
- return newy;
- }
- public static void main(String[] args) throws IOException {
- File f = new File("/home/matze/knight.csv");
- BufferedWriter bw = new BufferedWriter(new FileWriter(f));
- long sum = 0;
- for (int i = 0; i < 1000000; i++) {
- int x = 0;
- int y = 0;
- int rand = 0;
- int movecounter = 0;
- do {// move until starting position
- while (true) { // make valid random move
- double drand = Math.random() * 8;
- rand = (int) Math.floor(drand);
- int newx = getnewx(x, rand);
- int newy = getnewy(y, rand);
- if (newx >= 0 && newx < 8 && newy >= 0 && newy < 8) {
- x = newx;
- y = newy;
- break;
- }
- }
- movecounter++;
- } while (x != 0 && y != 0);
- bw.write(i+"," + movecounter);
- bw.newLine();
- sum += movecounter;
- }
- bw.close();
- System.out.println(sum/1000000.0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement