Effectively remove empty spaces within a set of numbers

I will use the syntax and Python objects to represent the problem, but it is actually intended for a model in SQL databases, with the Python API and ORM.

I have a list of numbers like this:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

From time to time, some numbers are deleted, and voids remain:

[0, 1, 2, None, None, 5, 6, None, None, None, 10]

What I need to do is effectively pack this set of numbers at the maintenance stage, performed periodically, in both ordered and disordered ways, so there should not be spaces between numbers:

So, in an orderly manner, I need this list:

[0, 1, 2, 5, 6, 10, None, None, None, None, None]

And when disordered, it really doesn't matter where each number goes, unless there are zero spaces between them.

, , , , .

, , . , 5, 6 2 , 10 5 .

[0, 1, 2, None, None, 5, 6, None, None, None, 10]

[0, 1, 2, 5, 6, None, None, None, None, None, 10]

[0, 1, 2, 5, 6, 10, None, None, None, None, None]

, , , , . , , 0, 1, 2 6 10:

[None, None, None, None, None, 5, 6, 0, 1, 2, 10]

, . , , .

, , , . ?

+3
3

, - , . , , , . , A * ( ) . - , , A */branch bound - , , , .

, , - , , X%, X.

, , , - max ( , , ) , .

- , . , - , , , . gappy , , . , , . : n + 1 , k- , n + 1-k , . , , , .

+3

, , . ( , ) . , , . , . . , , -. bean , . , , , .

, . :

  • . - 0 1. isNull (a), 1 0 . , , Selection Sort . O (n), O (n 2), , . , ! , , :

    • , . , ( ) , . , , , .. Abs (len (zeroBlock) - len (oneBlock)). .
    • , , , .
    • , .
  • . , , , . SO , . .

!

+2
#include <stdio.h>
#include <string.h>

#define IS_EMPTY(c) ((c) <= '@')

unsigned moverup(char buff[], unsigned size)
{
unsigned src,dst,cnt;

for (src=dst=cnt=0; src < size; src++ ) {
        if (!IS_EMPTY(buff[src])) { cnt++; continue; }
        if (!cnt) continue;
ugly:
        memmove(buff+dst, buff+src-cnt, cnt );
        dst += cnt;
        cnt = 0;
        }
if (cnt) goto ugly;
return dst;
}

int main(void)
{
unsigned result;
char array[] = "qwe@rty@ui#op";

printf("Before:%s\n", array );

result = moverup (array, strlen (array) );

printf("result:%u\n", result );
// entries beyond result will contain garbage now.
// array[result] = 0;
printf("After:%s\n", array );

return 0;
}
+1
source

All Articles