Skip to content

Instantly share code, notes, and snippets.

@sccheruku
Created August 11, 2022 04:04
Show Gist options
  • Save sccheruku/b3e1292a851df8094484b96e596b9297 to your computer and use it in GitHub Desktop.
Save sccheruku/b3e1292a851df8094484b96e596b9297 to your computer and use it in GitHub Desktop.
challenge 1
// Challenge #1: given this data structure, create a function that will return the route given a step
const steps = [
{ step: "c", next: "b" },
{ step: "b", next: "f" },
{ step: "aa", next: "c" },
{ step: "f", next: "r" },
{ step: "v", next: "z" },
{ step: "r", next: "ka" },
{ step: "ka", next: "v" },
{ step: "g", next: "h" },
{ step: "a", next: "b" },
{ step: "vs", next: "k" },
{ step: "bk", next: "o" },
{ step: "h", next: "i" },
{ step: "ft", next: "rt" },
{ step: "i", next: "bk" },
{ step: "z", next: "a" },
{ step: "k", next: "v" },
{ step: "cs", next: "b" },
{ step: "be", next: "f" },
{ step: "ra", next: "ba" },
{ step: "ga", next: "h" },
{ step: "bka", next: "o" },
{ step: "ha", next: "i" },
{ step: "ia", next: "bk" },
{ step: "za", next: "a" },
...[...new Array(100)].map((a, index) => ({
step: index,
next: Math.round(Math.random() * 100)
}))
];
//Please Write your code as functional as possible,
//you are allowed to create other helper functions to support getRouteByStep
const getRouteByStep = ({ steps, step }: any) => {
//write your logic here
const map = new Map<string, string>(); // step, next
steps.forEach((item: any) => {
map.set(item.step, item.next);
});
console.log("map", map);
let currentStep = step;
const route: string[] = [step];
const routeSet = new Set<string>([step]);
while (true) {
const next = map.get(currentStep);
console.log(`Next step for ${currentStep} is ${next}`);
if (!next) {
break;
}
route.push(next);
currentStep = next;
if (routeSet.has(next)) {
route.push(`loop.${next}`)
break;
}
routeSet.add(next);
}
return route;
};
console.log(getRouteByStep({ steps, step: 1 }));
console.log(getRouteByStep({ steps, step: "b" }));
//We should expect the output to look like this: ["b", "f", "r", "ka", "v", "z", "a", "b", "loop.b"]
@sccheruku
Copy link
Author

I noticed the code I was running earlier today was getting stuck on infinite loops. The reason was that the randomly generated steps on line 28, was generating circular routes.
The premise of the question made me think that we're only interested in loops where the starting step is repeated. eg. b.

However, while looking at the randomly generated routes, it's possible to end up with loops, which do not involve the starting step. eg: 1 -> 4 -> 5 -> 6 -> 4

Anyway, we can just use a Set to make sure every route only appears once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment