Re-index array
#1

Hey guys how to remove element array and re-index in pawn ?
Example array:

new example_array_number = 0;

array[0] = 69; example_array_number++;
array[1] = 24; example_array_number++;
array[2] = 47; example_array_number++;
array[3] = 34; example_array_number++;
array[4] = 57; example_array_number++;
array[5] = 70; example_array_number++;

array {
0: 69,
1: 24,
2: 47,
3: 34,
4: 57,
5: 70
};

And I need to remove 2. element in array (47)

And how to create script after remove array look this:

array {
0: 69,
1: 24,
2: 34,
3: 57,
4: 70
};

Maybee for loop ?
for(new i=idk; i<example_array_number; i++) {
//reindex_stuff...
}
example_array_number--;

Please help! Sorry I have very bad english skill so I hope u will be understand.
Reply
#2

Based on my little knowledge, if someone experienced can confirm, please do.

Exactly as you thought. However you can not change the size of the array, but the values in it.

PHP код:
array{
69,
24,
47,
34,
57,
70
};
array[
2] = 0;
for(new 
0sizeof array; i++)
{
    if(array[
i] != 0) continue;
    if( 
&& array[i+1] != 0)
    {
        array[
i] = array[i+1]; // this will make the array[2] get the value of array[3]
        
array[i+1] = 0// this will make the array[3] be 0, so the loop starts again and the same will be applied to the next item
    
}

Or something like that, but that'd be the process
Reply
#3

Thanks mate! Its worked!
Reply
#4

I think using one traversal and replacing the elements expect the one need to be deleted is good method as they can be used with multiple occurrence . Together with the type less nature of pawn we can accomplish it like this

PHP код:
Delete ( array[ ] , number )
{
    new
        
i,
        
j,
        
size;
    
    for( 
size strlen ( array ) ; size; ++)
    {
        if( array[ 
] == number )
              continue;
        array[ 
] = array[ ];
        
j++;
    }
    array[ 
] = _:EOS;
    return  
;

The above function also deletes element if they have multiple occurrence.But one should take caution that using sizeof wont work with it use strlen instead for traversal. Because sizeof operator can only insert size of array in script on compile time.

Edit:

Seems like the above function is not valid for elements having 0 value. As EOS is defined as 0 in SAMP. So it would be good if we return the size after deletion like this:

PHP код:
Delete ( array[ ] , number size sizeof array )
{
    new
        
i,
        
0;
    
    for( 
isize ; ++)
    {
        if( array[ 
] == number )
               continue;
        array[ 
] = array[ ];
        
j++;
    }
    return  
;//returns size after deletion

So that we can use this returned size for further traversal.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)