• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Array function to ignore duplicates / remove duplicates

W

William Roberts

Guest
I can't seem to find a function that exists in GMS to remove duplicates from an array or a way to build an array but not add if the entity already exists. So, I decided to write a small script that would remove duplicates when called, but it doesn't seem to work either. Does anyone else have experience with this issue?

I tried to apply my script on a more simplistic level with a string to help understand my logic. The same process would apply is removing duplicate letters from a word. For this script, I'd like to take the word "test" and have it return the letters "tes" (since the "t" is a duplicate). Thanks for the help in advance.

Code:
var letters = "";
var word = "test";
var i, j;

for (i = 0; i < string_length(word); i++) {
   
    var tmpLtr = string_char_at(word, i);
   
    if (string_length(letters) == 0) {
        letters += tmpLtr;
    }
   
    if (string_length(letters) > 0) {
        for (j = 0; j < string_length(letters); j++) {
            if ( tmpLtr != string_char_at(letters, j) ) {
                letters += tmpLtr;
            }
        }
    }

}

return letters;
(this code doesn't work as expected)... the results of this is "teessss"
 

obscene

Member
You'd be better off using a ds_list which has functions to do this. Then you could move the data into an array after finished if you need.

ds_list_create will create the list.
ds_list_find_index will check if the data is already in the list.
ds_list_add will add data to the list.

Then if you want to put this into an array instead...
ds_list_size will tell you how big the list is so you can make a for loop.
ds_list_find_value will read back a value so you can write it into an array.

ds_list_destroy and you're done.
 
W

William Roberts

Guest
Thank you and I really appreciate it. This will help greatly.
 
Top