Adding non-repeating numbers into an array
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.
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.
Adding non-repeating numbers into an array
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?
Re: Adding non-repeating numbers into an array
If the array should contain the numbers from x to x + array length, you can simply shuffle the array:
Otherwise you can use something like this:
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.
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]);
}
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;
}