Created
April 3, 2012 18:23
-
-
Save gpolitis/2294420 to your computer and use it in GitHub Desktop.
Renaming algorithm implementation
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 java.util.ArrayList; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
class DummyRunnable implements Runnable { | |
public static void main(String[] args) { | |
init(); | |
start(); | |
} | |
private static void start() { | |
for (int i = 0; i < N; i++) | |
new Thread(new DummyRunnable(100 + i, i)).start(); | |
} | |
private static void init() { | |
N = 100; | |
STATE = new int[N][2 * N - 1][2][N]; | |
} | |
private static int N; | |
private static int[][][][] STATE; | |
private static int getState(int x, int first, int dir, int i) { | |
if (dir == -1) | |
dir = 0; | |
return STATE[x - 1][first - 1][dir][i]; | |
} | |
private static void setState(int x, int first, int dir, int i, int val) { | |
if (dir == -1) | |
dir = 0; | |
STATE[x - 1][first - 1][dir][i] = val; | |
} | |
public DummyRunnable(int id, int i) { | |
this.id = id; | |
this.i = i; | |
} | |
private final int id, i; | |
@Override | |
public void run() { | |
int new_id = rename(N, 1, 1); | |
System.out.println(i + ": (old id, new id) = (" + id + ", " + new_id | |
+ ")"); | |
} | |
private int rename(int x, int first, int dir) { | |
int last = first + dir * (2 * x - 2); | |
System.out.println(i + ": (x, first, dir, last) = (" + x + ", " + first | |
+ ", " + dir + ", " + last + ")"); | |
setState(x, first, dir, i, id); | |
Set<Integer> competing = collectCompeting(x, first, dir); | |
if (competing.size() == x) { | |
int maxCompeting = max(competing); | |
if (id == maxCompeting) | |
return last; | |
else | |
return rename(x - 1, last - dir, -dir); | |
} else { | |
return rename(x - 1, first, dir); | |
} | |
} | |
private Set<Integer> collectCompeting(int x, int first, int dir) { | |
Set<Integer> collection = new HashSet<Integer>(); | |
for (int i = 0; i < N; i++) { | |
int val = getState(x, first, dir, i); | |
// Ids > 100. | |
if (val > 0) | |
collection.add(val); | |
} | |
return collection; | |
} | |
private static int max(Iterable<Integer> elms) { | |
int max = 0; | |
for (int i : elms) | |
if (i > max) | |
max = i; | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment