0

Here is a problem I can't manage, it comes from codingGame. I saw a solution but I tried to use a different syntax in order to better understand.

Context

/** Horse Racing Duals (easy) https://www.codingame.com/training/easy/horse-racing-duals
 * This puzzle shows that sometimes, the simplest solution is not performant
 * enough. You will also learn to handle large arrays and gain experience
 * with their processing time.
 *
 * STATEMENT:
 * In this problem you have to find the two numbers that are closest to each
 * other among a list of numbers. The list might be really large and force
 * you to search for the best possible algorithmic complexity for your
 * solution.
 *
 * STORY:
 * To make a race between two horses interesting, you will have to find the
 * horses with the closest strength.
**/
print(
    new Array(+readline())
        .fill()             
        .map(() => +readline())   
        .sort((a, b) => a > b)
        .map((x, i, arr) => Math.abs(x - arr[i + 1])) 
        .sort((a, b)  => a > b) [0] 
);

Why can't I do this:

let tab = new Array(+readline())
tab.fill()
tab.map(() => +readline())
tab.sort((a, b) => a > b)
tab.map((x, i, arr) => Math.abs(x - arr[i + 1])) 
tab
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • *map* returns a new array, it doesn't modify the array it's called on so when you do `tab.map(() => +readline())`, *tab* is not modified, so the unmodified array is passed to *sort* in the next statement. In `.map(() => +readline()).sort((a, b) => a > b)` the new array is passed to *sort*. So you are effectively removing the two *map* operations. – RobG Nov 21 '18 at 20:28
  • It should work like `const tab1 = new Array(+readline()); tab1.fill(); const tab2 = tab1.map(() => +readline()); tab2.sort(…); const tab3 = tab2.map(…); return tab3` – Bergi Nov 21 '18 at 21:22

2 Answers2

2

Why can't I do this:

Because some the map method returns a new array with the changes, instead of making the changes in-place.

In your example, only sort mutate the array in-place, so your code is really equivalent to:

let tab = new Array(+readline())
tab.sort((a, b) => a > b)

Note that the sort callback is supposed to return a positive number, negative number or 0. It should not return a Boolean.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

In order for it to be the same, it would need reassigning tab when the method does not mutate in place. like this:

let tab = new Array(+readline())
tab.fill()
tab = tab.map(() => +readline())
tab.sort((a, b) => a > b)
tab = tab.map((x, i, arr) => Math.abs(x - arr[i + 1])) 
print(tab)
iagowp
  • 2,428
  • 1
  • 21
  • 32