Skip to content

Instantly share code, notes, and snippets.

@readyyyk
Created September 30, 2023 19:09
Show Gist options
  • Save readyyyk/a0367db643ee2ab60ba605ba8dfc9166 to your computer and use it in GitHub Desktop.
Save readyyyk/a0367db643ee2ab60ba605ba8dfc9166 to your computer and use it in GitHub Desktop.
Task
/*
@readyyyk
Write a function that finds way from point "FORM" to point "TO"
function takes 3 args -
- point "from"
- point "to"
- function "getPaths" that returns places that can be reached from provided point
*/
// getRoutes implemetation
const shuffle=(s)=>s.sort(_=>0.5-Math.random());
let letters = ["x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
const getRoutes = () => {
const n = Math.floor(Math.random()*Math.min(6, letters.length));
let r = [];
for (let i = 0; i < n; i++){
letters = shuffle(letters);
r.push(letters.shift());
}
return r;
}
/* solve */
const updatePaths = (oldPaths, available) => available.length ? oldPaths.map(el=>available.reduce(
(acc, cur) => [...acc, [...el, cur]], [])).flat() : oldPaths;
const findPath = (from, to, _getRoutes) => {
letters = letters.sort(el=>el!==to);
const stack = [from];
const visited = [from];
let paths = [[from]];
let cnt = 0;
while(stack.length) {
cnt++;
const cur = stack.shift();
const available = _getRoutes(cur);
if(available.includes(to)) {
return [cnt, [...paths.find(el=>paths.at(-1) == el), to]];
}
paths = updatePaths(paths, available);
stack.push(...available.filter(el=>!(el in visited)));
}
return [cnt, new Error("No way")];
}
const [cnt, res] = findPath("A", "B", getRoutes);
console.log(cnt, res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment