Random number, then pick string out of an array depending on number?
#1

Ok so what i want is that i make a random number between 1 and 5 with my own function

rand(1, 5) --- duh

Then we have an array here:

pawn Code:
new Names[] = {"Michael", "John", "Katey", "Richard", "Robbin"};
Then if it outputs 5 or any other number, select that string from the array.
Like if rand(1, 5) outputs 2, then send the player a message with the name John in it.
If it outputs 3, send the player a message with the name Katey in it.

Can somebody explain me how?

Thanks!
Reply
#2

First this wont work
pawn Code:
new Names[] = {"Michael", "John", "Katey", "Richard", "Robbin"};
because you create an array for arrays also you need two dimensions not one
pawn Code:
new Names[][] =
{ //just made the brace around the names to see better that they are arrays too
    {"Michael"},
    {"John"},
    {"Katey"},
    {"Richard"},
    {"Robbin"}
};
Than to your random problem

pawn Code:
new string[128];
format(string, sizeof(string), "%s says hello to you!", Names[random(sizeof(Names))]);
SendClientMessage(playerid, 0xFFFFFFAA, string);
//we get the array size with sizeof(Names) - the size of the first dimension is 5
//so we do indirect random(5); which will return a number from -1 till 5 (0, 1, 2, 3 or 4)
//so when random as example return 3 it will be Names[3] and that is "Richard"
Reply
#3

never thought much about that but didnt you forgot the commas at your second pawn code ?

And that are for sure only two dimensions XD
pawn Code:
new Names[][] =
{
    {'M', 'i', 'c', 'h', 'a', 'e', 'l'},
    {'J', 'o', 'h', 'n'},
    {'K', 'a', 't', 'e', 'y'},
    {'R', 'i', 'c', 'h', 'a', 'r', 'd'},
    {'R', 'o', 'b', 'b', 'i', 'n'}
};
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)