Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Last active April 23, 2020 19:50
Show Gist options
  • Save junminstorage/e70d34fc40365bb1d9873248f6be5e4f to your computer and use it in GitHub Desktop.
Save junminstorage/e70d34fc40365bb1d9873248f6be5e4f to your computer and use it in GitHub Desktop.
class State {
int pos;
int speed;
String instr;
State(int p, int s, String str) {
pos = p; speed = s; instr = str;
}
public int hashCode() {
return pos*31 + speed + 31*31;
}
public boolean equals(Object s) {
if(s == null)
return false;
if(!(s instantof State))
return false;
State other = (State)s;
if(this.pos == other.pos)
return this.speed == other.speed;
return false;
}
}
//return the mininum-length instruction seuquences to reach dest from 0
public String mini(int dest) {
Queue<State> q = new ArrayDeque<>();
Set<State> visited = new HashSet<>(); //we can use Arrays.toList(state.pos, state.speed) as key as well
State start = new State(0, 1, "");
q.offer(start);
visited.add(start);
while(!q.isEmpty()) {
Start curr = q.poll();
if(curr.pos == dest) { //reach the destination
return curr.instr;
}
for(State nextState : new State[]{ new State(curr.pos + speed, speed * 2, curr.instr + "A"),
new State(curr.pos + speed, speed>0?-1:1, curr.instr + "R") } ) {
if(!visited.contains(nextState)) {
visited.add(nextState);
q.offer(nextState);
}
}
}
return null; //notice this is probably never reached since we will always find a way to reach destination
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment