Home > Back-end >  I've been getting some problems with this code can somebody check why?
I've been getting some problems with this code can somebody check why?

Time:10-22

function solve(commands){
let array = commands.shift();
commands.pop();
for(let command of commands){
    let tokens = command.split(" ");
    let currentCommand = tokens[0];  
    switch(currentCommand){
        case "swap":
            let index1 = array[tokens[1]];
            let index2 = array[tokens[2]];
            array[tokens[1]] = index2;
            array[tokens[2]] = index1;
            break;
        case "multiply":
            let index1 = array[tokens[1]];
            let index2 = array[tokens[2]];
            array[tokens[1]] = index1 * index2;
            break;
        case "decrease":
            array.map((x)=>{
                return x - 1;
            });
            break;
    }
}
console.log(array);

} solve([ '23 -2 321 87 42 90 -123', 'swap 1 3', 'swap 3 6', 'swap 1 0', 'multiply 1 2', 'multiply 2 1', 'decrease', 'end' ])

CodePudding user response:

You forgot to split the array, and you cant declare the same variables twice.

function solve(commands) {
  let array = commands.shift()
  array = array.split(" ");
  commands.pop();
  for (let command of commands) {
    let tokens = command.split(" ");
    let currentCommand = tokens[0];
    let index1, index2
    switch (currentCommand) {
      case "swap":
        index1 = array[tokens[1]];
        index2 = array[tokens[2]];
        array[tokens[1]] = index2;
        array[tokens[2]] = index1;
        break;
      case "multiply":
        index1 = array[tokens[1]];
        index2 = array[tokens[2]];
        array[tokens[1]] = index1 * index2;
        break;
      case "decrease":
        array.map((x) => {
          return x - 1;
        });
        break;
    }
  }
  console.log(array);
}
solve([
  "23 -2 321 87 42 90 -123",
  "swap 1 3",
  "swap 3 6",
  "swap 1 0",
  "multiply 1 2",
  "multiply 2 1",
  "decrease",
  "end",
]);
  • Related