Adding non-repeating numbers into an array

Archive of the old editing forum
Forum rules
Before asking on how to use a ZDoom feature, read the ZDoom wiki first. This forum is archived - please use this set of forums to ask new questions.
Locked
User avatar
Nash
 
 
Posts: 17501
Joined: Mon Oct 27, 2003 12:07 am
Location: Kuala Lumpur, Malaysia
Contact:

Adding non-repeating numbers into an array

Post by Nash »

I need a function that simply adds a number to a simple 1D array (for example numbers[80]), but I only want it to add numbers that don't exist in that list yet. So at the end, there will be 80 unique numbers in that list, not one of them repeating. Can anyone help me?
boris
Posts: 776
Joined: Tue Jul 15, 2003 3:37 pm

Re: Adding non-repeating numbers into an array

Post by boris »

If the array should contain the numbers from x to x + array length, you can simply shuffle the array:

Code: Select all

#include "zcommon.acs"

#define ARRAY_SIZE 10

int numbers[ARRAY_SIZE];
int tmp_numbers[ARRAY_SIZE];

script 1 open
{
    for(int i=0; i < ARRAY_SIZE; i++)
        tmp_numbers[i] = i+1;
        
    int last_element = ARRAY_SIZE-1;
    
    for(int pos=0; last_element >= 0; pos++, last_element--) {
        int n = random(0, last_element);
        
        numbers[pos] = tmp_numbers[n];
        tmp_numbers[n] = tmp_numbers[last_element];
    }
    
    for(i=0; i < ARRAY_SIZE; i++)
        print(d:numbers[i]);    
}
Otherwise you can use something like this:

Code: Select all

#include "zcommon.acs"

#define ARRAY_SIZE 10

int numbers[ARRAY_SIZE];

script 1 open
{
    int min = 10;
    int max = 100;

    for(int i=0; i < ARRAY_SIZE; i++) {
        int num = 0;
        
        do {
            num = random(min, max);
        } while(number_in_numbers_array(num));
        
        numbers[i] = num;
    }

    for(i=0; i < ARRAY_SIZE; i++)
        print(d:numbers[i]);
}

function bool number_in_numbers_array(int num)
{
    for(int i=0; i < ARRAY_SIZE; i++)
        if(numbers[i] == num)
            return true;
            
    return false;
}
The latter one is rather quick and dirty, since it just randomly tries out numbers (also ones it already tried). There are surely better methods.
User avatar
Nash
 
 
Posts: 17501
Joined: Mon Oct 27, 2003 12:07 am
Location: Kuala Lumpur, Malaysia
Contact:

Re: Adding non-repeating numbers into an array

Post by Nash »

Thanks!
Locked

Return to “Editing (Archive)”