1. Hey! Guest! The 35th GMC Jam will take place between November 28th, 12:00 UTC - December 2nd, 12:00 UTC. Why not join in! Click here to find out more!
    Dismiss Notice

Array function to ignore duplicates / remove duplicates

Discussion in 'Programming' started by William Roberts, Apr 10, 2019.

  1. William Roberts

    William Roberts Member

    Joined:
    May 11, 2018
    Posts:
    12
    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"
     
  2. obscene

    obscene Member

    Joined:
    Jun 21, 2016
    Posts:
    2,445
    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.
     
  3. William Roberts

    William Roberts Member

    Joined:
    May 11, 2018
    Posts:
    12
    Thank you and I really appreciate it. This will help greatly.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice