Home > Software engineering >  Create a 'counting' array of an array of conditions(bools) in any language
Create a 'counting' array of an array of conditions(bools) in any language

Time:04-17

How would you go about creating this array, [1,2,3,4,-1,-2,-3,1,2,-1,-2,-3,-4,-5,1,2,3]

from this array: [1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]

In any programming language that you like. Or multiple if you like to show a difference in language.

To show you what the created array is, here they are displayed in a more parallel fashion:

[1,1,1,1,     0 ,0 ,0,      1,1,      0, 0, 0, 0, 0,     1,1,1]
[1,2,3,4,     -1,-2,-3,     1,2,     -1,-2,-3,-4,-5,     1,2,3]

It should be counting while the array index is true(1) and also when negative, but in a negative count. Very curious what you guys come up with and how simple the code is, because I am stuck.

Thanks for any inspiration.

CodePudding user response:

Python solution, using itertools.groupby:

from itertools import groupby

a = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]

b = []
for k, g in groupby(a):
    b.extend(i * (k or -1) for i, _ in enumerate(g, 1))

print(b)

Prints:

[1, 2, 3, 4, -1, -2, -3, 1, 2, -1, -2, -3, -4, -5, 1, 2, 3]

CodePudding user response:

input_arr = [1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]
res = [1] if input_arr[0] else [-1]

for i in range(1, len(input_arr):
  if input_arr[i]:
    if res[-1] > 0: res.append(res[-1] 1)
    else: res.append(1)
  else:
    if res[-1] < 0: res.append(res[-1]-1)
    else: res.append(-1)

print(res)

Here's another python solution. The logic is straightforward and doesn't need much of an explanation.

CodePudding user response:

Here is the sample solution in JavaScript

const countArr = (arr) => {

  // Checks if the arr contains 1 and 0s only
  const isValid = arr.every(a => a === 1 || a === 0);
  if (!isValid) return 'collection should have 1 and 0 values only';

  let counter = 0; // Counting variable

  return arr.map(a => {
      // Reset counter IF
      // current item (a) = 1 and counter is in negative
      // OR
      // current item (a) = 0 and counter is in positive
      if ((a === 1 && counter < -1) || (a === 0 && counter > 1)) { 
          counter = 0
      };

      // Counter increment/decrement
      counter = a === 1 ? counter   1 : counter - 1;

      return counter;
  });
}

const collection = [1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]; // Collection

console.log(collection);
console.log(countArr(collection));

  • Related