Challenge: Sections / generating random possession

#1

hey guys,

i was wondering how the most efficient way would be in terms of generating x instances of possession whose price is higher than 50? i think i used a rather inefficient way so if anyone could give me a pointer i would highly appreciate. this is how i went about it:

i basically just copied the static method randomPossession. within the .h file

• (id)randomPossession:(int)value;

and within the .m file the only thing i changed was the part where the value was calculated:

int randomValue = rand() % (100 - value + 1) + value;

while the outcome did work all the copy/paste just doesn’t seem very efficient to say at least. so what would have been better?

thanks a lot

#2

Hi,

rand() % 51 gives you a number between 0 and 50

so rand() % 51 + 50 will give you a number between 50 and 100.

Gareth

#3

Ah, ok. Though what about the additional static method i used? Isnt there a more elegant way?

#4

Hi,

You could make it a bit more reusable I guess with

• (int)randomPossessionWithFloor: (int) floor ceiling: (int)ceiling

return rand() % (ceiling + 1) - floor;

Gareth

#5

ah ok. thanks a lot! so basically there isn’t any other way than having to create another static method in order to generate possessions with specific value attributes. i was just thinking that there would be some way to reuse the already available static method but couldn’t think of any logical way has to how to include a flexible price attribute.

#6

Hi,

Well there are many ways to do this but given the recommendation to use 2 separate arrays and the fact that we don’t really care about the distribution count of the values you could just leave randomPossession as it is.

Then in the calling function:

call randomPossession

if value > 50