Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
👨🏫 educationalized solution in Clear category for Fast Train by vincent.tscherter
function fastTrain(numbers) {
let v, i, j, t;
// create max velocity per track unit and insert left and right zero sentinels
// [[5,5], [4,2], [5, 5]] => [0, 5, 5, 5, 5, 5, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 0]
t = numbers.reduce( (a, [l,m]) => a = [...a, ...Array(l).fill(m)], [] );
t.unshift(0); t.push(0);
// reduce the max velocities according to the allowed acceleration pattern
v = 1;
while (v < t.length) {
// l2r [0,5,5,5,5,5,2,2,2,2,5,5,5,5,5,0] => [0,1,2,2,3,3,2,2,2,2,3,3,3,4,4,0]
i = 1;
while (i < t.length) {
if (t[i-1] == v-1 && t[i-1] [0,1,2,2,3,3,2,2,2,2,3,3,2,2,1,0]
i = t.length-2;
while (0 <= i) {
if (t[i+1] == v-1 && t[i]>t[i+1]) {
j = 0;
while (j [1,2,2,3,3,2,2,2,2,3,3,2,2,1]
t.pop(); t.shift();
// count tics (j)
j = 0;
while (t.length > 0) {
j++;
i = (v = t.shift()) - 1;
while(i>0 && t.length>0 && t[0]>=v) t.shift(), i--;
} return j;
}
Oct. 28, 2020
Comments: