Home > Back-end >  Directions Reduction JavaScript - I can not find my error
Directions Reduction JavaScript - I can not find my error

Time:07-25

In this problem we have to transform an array of moves to avoid going back to the same place while keeping only the important instructions. The problem is that once I thought I had solved it, the result is not what I expected, could someone guide me about the error in my code?

function dirReduc(arr){
  let y = 0,
      index = 0,
      directions = [];
  
  arr.forEach(function(movement){
    if(movement == "NORTH"){
      if(directions.includes("SOUTH")){
        index = directions.indexOf("SOUTH")
        directions.splice(index, 1)
      } else{
        directions.push("NORTH")
      }
    } 
    
    else if(movement == "SOUTH"){    
      if(directions.includes("NORTH")){
        index = directions.indexOf("NORTH")
        directions.splice(index, 1)
      } else{
        directions.push("SOUTH")
      }
    } 
    
    else if(movement == "EAST"){
      if(directions.includes("WEST")){
        index = directions.indexOf("WEST")
        directions.splice(index, 1)
      } else{
        directions.push("EAST")
      }
    } 
      
      else if(movement == "WEST"){
      if(directions.includes("EAST")){
        index = directions.indexOf("EAST")
        directions.splice(index, 1)
      } else{
        directions.push("WEST")
      }
    }
  });
  
  return directions
}

CodePudding user response:

Here is an alternative way of doing it, canceling out opposite moves and listing them in an ordered way:

const dirs=["north","north","west","south","west","north","east","north","west","south"];

const rd=dirs.reduce((a,c)=>(  a[c],a),
 {north:0,east:0,south:0,west:0});
let ns=rd.north-rd.south,
  ew=rd.east-rd.west;
const res=(ns?Array(Math.abs(ns)).fill(ns>0?"north":"south"):[])
   .concat(ew?Array(Math.abs(ew)).fill(ew>0?"east":"west"):[]);

console.log(res)

  • Related