Remove a number (integer) out of an array

Previous topic - Next topic

JohnnyB

What is the best solution?

i cannot use foreach with non-types, can I?!

MrPlow

Comp:
Speccy-48k, Speccy-128k, Amigas, PCs

MrPlow

Just be careful of deletes in the said array.
I often 'mark' array items and delete them later.
Comp:
Speccy-48k, Speccy-128k, Amigas, PCs

JohnnyB

so technically, I save IDs in an array: 7, 14, 9, whatever

so which loop to use to get rid of, let's say 14?

Should I simply use a counter and then use DIMDEL after the loop (I think using it within could cause problems)?

Or DELETE within the loop?!

Moru

Use DELETE inside a FOREACH loop.

Type "DELETE" in the editor and press F1 and then ENTER. Gives you the manual with a nice example how to do it:

Code (glbasic) Select

// Make an array of numbers
DIMDATA a[], 3,4,5,  12,13,  6

// Enumerate the numbers
FOREACH num IN a[]
   // throw out numbers bigger than 10, and continue
   IF num>10 THEN DELETE num
   a$=a$ + num + ", "
NEXT
PRINT a$, 0,0

SHOWSCREEN
MOUSEWAIT



dreamerman

Imho if You want to delete elements by index/id in basic type array (int, float, string) and want to preserve elements position do something like this:

Code (glbasic) Select
// compile in Debug mode

GLOBAL myarray%[], elems2del%[], i1%, i2%, txt$
DIM myarray%[0]
DIM elems2del%[0]

SEEDRND 1
txt$ = ""
FOR i1 = 0 TO 20
i2 = RND(100)
DIMPUSH myarray[], i2
INC txt$, i2 + ", "
NEXT
txt$ = LEFT$(txt$, LEN(txt$) - 2)

DEBUG txt$ + "\n"


DIMDATA elems2del[], 7, 14, 9 // or use DimPush
SORTARRAY elems2del[], 0 // ascending order

FOR i1 = LEN(elems2del[]) - 1 TO 0 STEP -1
DIMDEL myarray[], elems2del[i1]
NEXT


txt$ = ""
FOR i1 = 0 TO LEN(myarray[]) - 1
INC txt$, myarray[i1] + ", "
NEXT
txt$ = LEFT$(txt$, LEN(txt$) - 2)

DEBUG txt$ + "\n"


END


For dealing with UDT's I use 'toDelete%' flag, or approach similar to this, separate array with indexes to delete - depending on game logic, and if I don't need to preserve elements order just do elem[del_id] = elem[len[elem]-1], dec elem_count -> as this should be faster than multiple dimdel/push on large arrays.
Check my source code editor for GLBasic - link Update: 20.04.2020