A
A
Andrey2018-11-12 18:41:34
C++ / C#
Andrey, 2018-11-12 18:41:34

How to "add/remove" an array element?

Given ordered real numbers A1, A2,..., An, a natural number k and a real number P. Remove the element with number k and insert it into the sequence P so that the order is not violated

It turned out to be done only for a special case (under a certain array). If another array is used, the algorithm no longer works :(
Help:)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arseniy Efremov, 2018-11-13
@arusef

Beware, pseudocode.
Didn't check, but the logic should work with any input array.

let input = [ a1, a2, ... , aN ] // ordered ascending, N > 1
let k, P // assume k > 0, 1-based indexing
// remove at k, 0-based indexing
for (let i = k; i < N; ++i)
   input[i - 1] = input[i]
// insert P preserving order
for (let i = N - 1; i >= 0; --i) {
   if (i == 0 || P >= input[i - 1]) {
      for (let j = N - 1; j > i; --j)
         input[j] = input[j-1]
      input[i] = P
      break
   } else continue
}
// finish
print(input)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question