java - What is a good algorithm for mapping random (barcode values) numbers to an String in a collection? -
say application has finite number of "stuff", in case items in game purposes of question i'll use strings.
say have 5 strings :
- james
- dave
- john
- steve
- jack
there set list of them, increase list in future.
question : algorithm can use, go random number (generated barcode) 1 of values above?
for example, if have value 4523542354254, algorithm use map onto dave? if have same number again, need make sure maps dave , not else each time.
one option did consider taking last digit of barcode , using 0-9 map onto 10 items, not future proof if added 11th item.
any suggestions?
with clarification "if have same number again, need make sure maps dave , not else each time." applies long set of strings doesn't change.
simplest maverik says, name = names[barcode % names.length];
a java long big enough store upc barcode, int isn't, assume here barcode long. note last digit of upc barcode base-11, can x. leave exercise reader how map barcodes numbers. 1 option discard check digit once you've established it's correct - it's computed others, doesn't add information or discriminate between otherwise-equal codes.
but stephen c says, barcodes aren't random, might not give uniform distribution across names.
to better distribution, first hash barcode. example name = names[string.valueof(barcode).hashcode() % names.length];
this still might not entirely uniform -- there better slower hash functions string.hashcode -- avoids major biases there may in real-life barcodes.
also, can't remember whether java modulus operator returns negative results negative input - if need coerce positive range:
int idx = string.valueof(barcode).hashcode() % names.length; if (idx < 0) idx += names.length;
Comments
Post a Comment