Skip to content

Instantly share code, notes, and snippets.

@majudhu
Last active November 29, 2020 16:37
Show Gist options
  • Save majudhu/a56ef31b4952d47ed7d60aa5f21941df to your computer and use it in GitHub Desktop.
Save majudhu/a56ef31b4952d47ed7d60aa5f21941df to your computer and use it in GitHub Desktop.
function process(input) { // takes (string) -› returns int
let scan_t = [0, 0]; // scan init
let graph = input
.split('')
.map((c) => {
switch (c) {
case '<': return [-1, 0];
case '^': return [0, 1];
case '>': return [1, 0];
case 'v': return [0, -1];
default: throw `Unexpected input "{$input}"`;
}
}).map(([x, y]) => { // javscript doesn't have scan()
scan_t = [scan_t[0] + x, scan_t[1] + y];
return [...scan_t]; // return a copy, js passes arrays by ref
}).reduce(
(acc, [x, y]) => {
pos_s = `${x}:${y}`; // can't use arrays as keys, stringify it "x:y"
acc.set(pos_s, (acc.get(pos_s) ?? 0) + 1);
return acc;
},
new Map([["{0:0}", 1]]),
);
return graph.size;
}
// https://twitter.com/chrisbiscardi/status/1332832739578396672
fn process(input: &str) -> usize {
let grid = input
.chars()
.map(|c| match c {
'<' => (-1, 0),
'^' => (0, 1),
'>' => (1, 0),
'v' => (0, -1),
input => panic!("Unexpected input `{}`", input),
})
.scan((0, 0), |state, (x, y)| {
*state = (state.0 + x, state.1 + y);
Some(*state)
})
.fold(
{
let mut map = HashMap::new();
// the first step on the route
map.insert((0, 0), 1);
map
},
|mut acc, (x, y)| {
acc.entry((x, y)).and_modify(|e| *e += 1).or_insert(1);
acc
},
);
grid.len()
}
@NizarOukhchi
Copy link

JavaScript has reduce, it's the equivalent of fold in rust ;)

@majudhu
Copy link
Author

majudhu commented Nov 29, 2020

JavaScript has reduce, it's the equivalent of fold in rust ;)

oh, I forgot about that, just updated to use reduce, thanks

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