-1

Sorry if this is a duplicate question. I did a search but wasn't sure exactly what to search for.

I'm writing an app that performs a scan. When the scan is complete we need to decide if an item was found or not. Whether or not the item is found is decided by a threshold that the user can set: 0% of the time, 25% of the time, 50% of the time, 75% of the time or 100% of the time.

Obviously if the user chooses 0% or 100% we can use true/false but for the frequency but I'm drawing a blank on how this should work for the other thresholds.

I assume I'd need to store and increase some value every time a monster is found.

Thanks for any help in advance!

jblaker
  • 147
  • 4
  • If you find three and have no idea what the maximum is, you can't say that this is 3% or 30% or 77%. Or, let's put it another way: if I specify 100%, how many items must be found? – laune Jul 27 '14 at 11:22

2 Answers2

0

Generate a random number between 0 and 100. If the number is greater than the threshold, an item is found. Otherwise, no item is found.

user3553031
  • 5,990
  • 1
  • 20
  • 40
0

As @nix points out it sounds like you want to generate a random number and threshold based on the percentage of the time you wish to have 'found' something.

You need to be careful that the range you select and how you threshold achieve the desired result as well as the distribution of the random number generator you use. When dealing in percentages an obvious approach is to generate 1 of 100 uniformly distributed options and threshold appropriately e.g. 0-99 and check that the number is less than your percentage.

A quick check shows us that you will never get a number less than 0 so 0% achieves the expected result, you will always get a number less than 100 so 100% achieves the expected result and there a 50 options (0-49) less than 50 out of 100 options (0-99) so 50% achieves the expected result as well.

A subtly different approach, given that the user can only choose ranges in 25% increments, would be to generate numbers in the range 0-3 and return True if the number is less than the percentage / 25. If you were to store the user-selection as a number from 0-4 (0: 0%, 1: 25% .. 4: 100%) this might be even simpler.

Various approaches to pseudo-random number generation in Objective-C are discussed here: Generating random numbers in Objective-C.

Note that mention is made of the uniformity of the random numbers potentially being sensitive to the range depending on the method you go with.

To be confident you can always do some straight-forward testing by calling your function a large number of times, keeping track of the number of times it returns true and comparing this to the desired percentage.

Community
  • 1
  • 1