### Author Topic: Remove a number (integer) out of an array  (Read 904 times)

#### JohnnyB

• Mc. Print
• Posts: 33
##### Remove a number (integer) out of an array
« on: 2019-May-14 »
What is the best solution?

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

#### MrPlow

• Prof. Inline
• Posts: 1697
##### Re: Remove a number (integer) out of an array
« Reply #1 on: 2019-May-14 »
Yes - for any array.
Comp:
Speccy-48k, Speccy-128k, Amigas, PCs

#### MrPlow

• Prof. Inline
• Posts: 1697
##### Re: Remove a number (integer) out of an array
« Reply #2 on: 2019-May-14 »
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

• Mc. Print
• Posts: 33
##### Re: Remove a number (integer) out of an array
« Reply #3 on: 2019-May-14 »
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

• Prof. Inline
• Posts: 1787
##### Re: Remove a number (integer) out of an array
« Reply #4 on: 2019-May-14 »
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 numbersDIMDATA a[], 3,4,5,  12,13,  6// Enumerate the numbersFOREACH num IN a[]   // throw out numbers bigger than 10, and continue   IF num>10 THEN DELETE num   a\$=a\$ + num + ", "NEXTPRINT a\$, 0,0SHOWSCREENMOUSEWAIT`

#### dreamerman

• Global Moderator
• Dr. Type
• Posts: 338
##### Re: Remove a number (integer) out of an array
« Reply #5 on: 2019-May-15 »
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 modeGLOBAL myarray%[], elems2del%[], i1%, i2%, txt\$DIM myarray%[0]DIM elems2del%[0]SEEDRND 1txt\$ = ""FOR i1 = 0 TO 20 i2 = RND(100) DIMPUSH myarray[], i2 INC txt\$, i2 + ", "NEXTtxt\$ = LEFT\$(txt\$, LEN(txt\$) - 2)DEBUG txt\$ + "\n"DIMDATA elems2del[], 7, 14, 9 // or use DimPushSORTARRAY elems2del[], 0 // ascending orderFOR i1 = LEN(elems2del[]) - 1 TO 0 STEP -1 DIMDEL myarray[], elems2del[i1]NEXTtxt\$ = ""FOR i1 = 0 TO LEN(myarray[]) - 1 INC txt\$, myarray[i1] + ", "NEXTtxt\$ = 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