#rand() help

29 messages · Page 1 of 1 (latest)

subtle trout
#

How would i make the getRandomInteger() returned integer, with a range of 4, print a word associated with each random integer? If the printed random number is 1, how would i make it print "dog" instead of 1, where 1 = "dog", and so on for each number in the range?

azure loomBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

subtle trout
#

Sorry if that doesn’t make sense

#

I want to associate a word with each random integer, and print that instead of the integer

#

Obviously doing int 1 = “Dog”; doesn’t work

proud tree
#

create an array of string literals generate a random index and print whatever word in said index

subtle trout
#

Ok so the directions are to print the word in a separate function named printImage(). “Print the name of an image when passed its number as an argument”

proud tree
#

i don't see how that changes things

subtle trout
#

So I’d create an array of every word I want to use, and printing a word for whatever random integer is selected from the array position?

proud tree
#

well... yes

subtle trout
#

Got no idea how to do that but okay

#

Thanks

azure loomBOT
#

@subtle trout Has your question been resolved? If so, type !solved :)

proud tree
#

consider:

static int generate_rand(int max, int min) {
  ...
}

static void foo(char **words, size_t size) {
  if (!words || !size) return;

  size_t idx = (size_t)generate_rand(4, 0);

  assert(idx < size);

  puts(words[idx]);
}

int main(void) {
  // seed your rand here

  char *words[] = {"1", "2", "3", "4"};  // this array can also be local within foo if you so desire
  foo(words, sizeof words / sizeof *words); 
}```
or something along these lines
subtle trout
#

Just figured it how to do it with if statements

proud tree
#

thats also an option (though not as flexible)

subtle trout
#

Yea idk what I’m doing

#

@proud tree

proud tree
#

if you are taking the this approach - you might want to rethink your design here. if getRandomInteger well, gives you a random integer - does it needs to print the word associated with said integer too?

subtle trout
#

Got it working

#

Rudimentary, at least

#

formatting is wrong but its printing 3 random predefined words

proud tree
#

great. i highly suggest you reformat your getRnadomInteger making it resposible for one thing. other functions can take care of the rest if necessary

#

generally speaking the more (side effects) each of your functions do the harder they are to debug / reason about