The challenge Directions Reduction ask you to find shortest route from array of directions.
Input -> Output ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] -> ["WEST"] /* Because moving "NORTH" and "SOUTH", or "EAST" and "WEST", is unnecessary. */ /* Case: omit the first "NORTH"-"SOUTH" pair ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] -> ["SOUTH", "EAST", "WEST", "NORTH", "WEST"] Case: omit the "EAST"-"WEST" pair -> ["SOUTH", "NORTH", "WEST"] Case: omit the "NORTH"-"SOUTH" pair -> ["WEST"] */ // this case cannot be reduced: ["NORTH", "WEST", "SOUTH", "EAST"] -> ["NORTH", "WEST", "SOUTH", "EAST"]
function dirReduc(plan) { var opposite = { 'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}; return plan.reduce(function(dirs, dir){ if (dirs[dirs.length - 1] === opposite[dir]) dirs.pop(); // Remove last direction if it's the opposite else dirs.push(dir); // Otherwise, add current direction to the stack return dirs; }, []); }
This is a LIFO (Last-in-First-out) approach implemented using reduce.
function dirReduce(arr) { let str = arr.join(''), pattern = /NORTHSOUTH|EASTWEST|SOUTHNORTH|WESTEAST/; while (pattern.test(str)) str = str.replace(pattern,''); // Remove pairs while they exist return str.match(/(NORTH|SOUTH|EAST|WEST)/g)||[]; }
Alternative Version:
function dirReduc(arr) { const pattern = /NORTHSOUTH|EASTWEST|SOUTHNORTH|WESTEAST/; let str = arr.join(''); while (pattern.test(str)) { str = str.replace(pattern, ''); // Remove pairs while they exist } const result = str.match(/(NORTH|SOUTH|EAST|WEST)/g); return result || []; }
I believe the minimum case for this solution is as follows:
1. ["SOUTH", "EAST", "WEST", "NORTH"] -> [] 2. ["NORTH", "WEST", "SOUTH", "EAST"] -> ["NORTH", "WEST", "SOUTH", "EAST"]
I prefer Solution 2, as it is concise and uses regular expressions in a clever way. Initially, I couldn't imagine solving it with regular expressions, but the use of join, match, while, replace, and test methods to eliminate pairs is impressive.
If you're curious about these solutions or want to explore more challenges, visit here.
Welcome to leave a comment below!
Thank you for reading ?
The above is the detailed content of TIL: LIFO Solution and Regular Exprresion Techniques【CodeWars】. For more information, please follow other related articles on the PHP Chinese website!