settingsAccountsettings
Menusettings

Q: Set values to indexes in an array

+6 votes

You will be given N – an integer specifying the length of an array. Then you will start receiving an index and a value. For each received line you must set the value at the given index to the given value. When you’ve processed all input data, print the array’s elements each on a new line.

Examples:

Input

Output

 

Input

Output

 

Input

Output

3

0 - 5

1 – 6

2 – 7

5

6

7

 

2

0 – 5

0 – 6

0 – 7

7

0

5

0 – 3

3 - -1

4 – 2

3

0

0

-1

2

 

asked in JavaScript category by user richard8502

1 Answer

+1 vote
 
Best answer

Here is the answer:

function set(arr) {
  let count = parseInt(arr[0]);
  let numbers = [];//New array

  for (let i = 0; i < count; i++) {
    numbers[i] = 0;
  }

  for (var i = 1; i < arr.length; i++) {
    let pair = arr[i].split(' - ').map(Number);
    let index = parseInt(pair[0]);
    let value = parseInt(pair[1]);

    numbers[index] = value;
  }
  console.log(numbers.join('\n'));
}

// set('3',
//   ['0 - 5',
//     '1 - 6',
//     '2 - 7']
// );

 

answered by user sam
selected by user golearnweb
...