Last active
December 3, 2017 09:21
-
-
Save Kornel/b4b8098c7d23100d1a74ec0ae5b81074 to your computer and use it in GitHub Desktop.
Ulam's spiral (sort of, without primes yet)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.lang.Math.sqrt; | |
public class S { | |
public static void main(String[] args) { | |
int[][] s = createSpiral(20); | |
print(s); | |
} | |
private static int[][] createSpiral(int n) { | |
int[][] t = new int[n][n]; | |
int shiftx = n / 2; | |
int shifty = shiftx - 1; | |
int x = 0; | |
int y = 0; | |
for (int i = 1; i <= n * n; ++i) { | |
t[x + shiftx][y + shifty] = i; | |
y = y + dy(turn(i + 1)); | |
x = x + dx(turn(i + 1)); | |
} | |
return t; | |
} | |
private static void print(int[][] s) { | |
for (int i = 0; i < s.length; ++i) { | |
for (int j = 0; j < s.length; ++j) { | |
System.out.print(s[i][j]); | |
System.out.print("\t"); | |
} | |
System.out.println(""); | |
} | |
} | |
private static int turn(int n) { | |
return (int)sqrt(4 * n - 7) % 4; | |
} | |
private static int dx(int turn) { | |
if (turn == 0) return 1; | |
if (turn == 1) return 0; | |
if (turn == 2) return -1; | |
if (turn == 3) return 0; | |
throw new IllegalStateException("Unexpected x turn " + turn); | |
} | |
private static int dy(int turn) { | |
if (turn == 0) return 0; | |
if (turn == 1) return 1; | |
if (turn == 2) return 0; | |
if (turn == 3) return -1; | |
throw new IllegalStateException("Unexpected y turn " + turn); | |
} | |
} |
Author
Kornel
commented
Nov 30, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment