Logo

dev-resources.site

for different kinds of informations.

TIL: LIFO Solution and Regular Exprresion Techniques【CodeWars】

Published at
12/5/2024
Categories
javascript
codewars
algorithms
todayilearned
Author
kohki_takatama
Author
14 person written this
kohki_takatama
open
TIL: LIFO Solution and Regular Exprresion Techniques【CodeWars】

Overview 🔍

The challenge Directions Reduction ask you to find shortest route from array of directions.

Examples:

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"]

Enter fullscreen mode Exit fullscreen mode

Solutions 1: LIFO

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;
    }, []);
}
Enter fullscreen mode Exit fullscreen mode

This is a LIFO (Last-in-First-out) approach implemented using reduce.

Steps:

  1. Declare an empty stack (dirs)
  2. For each direction in the input array (plan), check if the last element of the stack (dirs) is the opposite of the current direction
  3. If they are opposites, pop the last element from the stack (and skip current direction). Otherwise, push the current direction onto the stack.
  4. Repeat this process until all directions have been processed.

Solutions 2: Regular Expression

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)||[];
}
Enter fullscreen mode Exit fullscreen mode

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 || [];
}
Enter fullscreen mode Exit fullscreen mode

Steps:

  1. Join the input array (arr) into a single string so we can manipulate it using regular expressions.
  2. Define a regular expression (pattern) that matches opposite direction pairs (e.g., 'NORTHSOUTH', 'EASTWEST').
  3. Use the replace method in a loop to remove any direction pairs found by the regular expression.
  4. After all pairs have been removed, use the match method to extract the remaining directions from the string and return them as an array.

Discussion and Insights 💭

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"]
Enter fullscreen mode Exit fullscreen mode

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 🙌

todayilearned Article's
30 articles in total
Favicon
My First Post and Introduction
Favicon
Guess what? You can make a game inside a PDF!
Favicon
TIL: Tag Function / Tagged Template Literals
Favicon
update notepad++
Favicon
TIL: Styling Obsidian text paragraphs
Favicon
Today I Learned...
Favicon
Outlook tìm mail nhận trong khoảng thời gian xác định
Favicon
TIL: using --no-deps with docker compose
Favicon
TIL: LIFO Solution and Regular Exprresion Techniques【CodeWars】
Favicon
Scrum Fundamentals Certification (SFC) | Study Notes - Part I: Introduction
Favicon
Downloading the same file 102+ times
Favicon
Build Golang from Source for v1.23+
Favicon
3 Myths, 3 Facts, and 3 Strategies to Scale Node.js Apps
Favicon
How to Validate Inputs Using Only HTML
Favicon
Turning a Customer Security Concern into a Feature
Favicon
Opposite Colours Tool
Favicon
Work Life Balance
Favicon
Is This a Good Way to Reduce Operational Costs?
Favicon
TIL: How to Trim Trailing Zeros【CodeWars】
Favicon
Why 1% - 1% Isn't Zero in Your Calculator (And What It Really Means)
Favicon
What I’ve Learned from Building a Calculator with Vue.js
Favicon
Starting to Rust
Favicon
TIL C11 Annex K exists but you shouldn't use it
Favicon
Be careful with join type typos
Favicon
The Role of AI in Financial Services: Opportunities and Challenges
Favicon
Starting to Rust
Favicon
Getting Started with the TMDB API: A Beginner's Guide
Favicon
TIL emalloc() auto-exits on out-of-memory errors
Favicon
TIL: How To Use the Specification Pattern in C# To Simplify Repositories
Favicon
Devops Foundation - Day1

Featured ones: