Home > OS >  adding and subtracting in a 'for' loop
adding and subtracting in a 'for' loop

Time:09-13

I'd like to start by saying that I am still new to JavaScript and this is a CodeWars Kata Number of people in the Bus.

Also I know there is a simpler way of completing this task but If I just googled the answer, I feel that I wont have learned anything so here goes:

Hi All, at the end of a loop, how do I get it to add a, minus b on repeat? what is that called?

i.e.

[ 10, 0, 3, 5, 5, 8 ]

should work math like:

[ 10 - 0   3 - 5   5 - 8 ]

it's a codewars kata and I know there is a simple way of doing it but I have gone around it the long way.

Here is the code I am up to (and the console.log that is the test case)

var number = function (busStops) {
  let newBusStops = [];
  for (let i = 0; i < busStops.length; i  ) {
    newBusStops = newBusStops.concat(busStops[i]);
  }
  //   return newBusStops;
  let passengers = 0;
  for (let i = 0; i < newBusStops.length; i  ) {
    passengers  = newBusStops[i];
  }
  return passengers;
};
// var number = function (busStops) {
//   let passengers = 0;
//   for (let i = 0; i < busStops.length; i  ) {
//     passengers  = parseInt(number[i]);
//     busStops.toString();
//     return busStops;
//   }
// };

// var number = function (busStops) {
//   for (let i = 0; i < busStops.length; i  ) {
//     return busStops[i][0] - busStops[i][1];
//   }
// };
// return busStops[0][0];

console.log(
  number([
    [10, 0],
    [3, 5],
    [5, 8],
  ])
);
console.log(
  number([
    [3, 0],
    [9, 1],
    [4, 10],
    [12, 2],
    [6, 1],
    [7, 10],
  ])
);

I've managed to flatten the 2d array but I am only able to add the flattened array, I can't figure out how to do add a minus b. I don't know what that is called so I can search it

CodePudding user response:

I would go through the array with a counting index (like you do). Depending on this index, I would add or substract the value from the last result.

First Hint: Loop over an array with key-value pairs like this

for (const [key, value] of array) {console.log(key, value);}

Second Hint: A subtraction is a addition with a negativ number

5-3 == 5 (3*-1)

Third Hint: Have a look at the modul Operator %

console.log(1%2);
console.log(2%2);
console.log(3%2);

Solution:

var number = function (busStops) {

var total = 0;

for (const [i, value] of busStops){

total = value*(i%2?1:-1);

}

return total;

}

CodePudding user response:

Though I suggest that you first try to solve your Kata by yourself, I'd like to present some solutions based on your code and an alternative solution with the reduce method.

2d array and for loop.

You were on the right track with this one. The only thing missing was that you weren't adding or subtracting from any number. Besides that return statement stopped the loop before you could complete your calculations.

var number = function (busStops) {
  let passengers = 0;
 
  for (let i = 0; i < busStops.length; i  ) {
    passengers  = busStops[i][0] - busStops[i][1];
  }
  
  return passengers;
};

console.log(
  number([
    [10, 0],
    [3, 5],
    [5, 8],
  ])
);

console.log(
  number([
    [3, 0],
    [9, 1],
    [4, 10],
    [12, 2],
    [6, 1],
    [7, 10],
  ])
);

Flattened array with for loop and %

As suggested by @Marcus, you could use a modulo operator to see if you're in an even or odd iteration in the loop and therefor decide wether to add or subtract. Also, flattening can be done with the flat method that every array has.

var number = function (busStops) {
  let passengers = 0;
  const flattenedBustStops = busStops.flat();
   
  for (let i = 0; i < flattenedBustStops.length; i  ) {
    if (i % 2 === 0) {
      passengers  = flattenedBustStops[i];
    } else {
      passengers -= flattenedBustStops[i];
    }
  }
  
  return passengers;
};

console.log(
  number([
    [10, 0],
    [3, 5],
    [5, 8],
  ])
);

console.log(
  number([
    [3, 0],
    [9, 1],
    [4, 10],
    [12, 2],
    [6, 1],
    [7, 10],
  ])
);

2d array and reduce

With the reduce method you can loop over your array and change the output completely. In this case we pass a starting value of 0, which is our accumulator acc. Then we loop over each entry in the array, add, and subtract the values before returning the accumulator. This method can get complicated pretty fast, but makes a lot of sense with this scenario.

const number = (busStops) => 
  busStops.reduce((acc, [add, remove]) => 
    acc  = add - remove
  , 0);

console.log(
  number([
    [10, 0],
    [3, 5],
    [5, 8],
  ])
);

console.log(
  number([
    [3, 0],
    [9, 1],
    [4, 10],
    [12, 2],
    [6, 1],
    [7, 10],
  ])
);

  • Related