changing an unknown large number and changing it to a number within a specific range

Started by
6 comments, last by Evil Steve 14 years, 1 month ago
hoping someone can help me with this =) i am writting a program that will take a string and the ascii value of each character is added togeather, i then want to alter that number with some random element and make it a number within a set range (preferably 0 - 100). getting the total value of the string is simple enough but i am having problems working out the calculation to take that + a random number and make it a number within range. any help would be much appreciated
Advertisement
What are you trying to do?

You are going to irrevocably lose data if you try to cram a (large arbitrary integer + random) to a smaller integer range.

Also, it doesn't make sense to change a range of one number by an arbitrary amount. And if you're using a random factor, you cannot reverse the process in a meaningful way. And if you sum all the characters of a string to an integer, you can't reverse the process anyway. Assuming you are writing some kind of an encrypting application, these all are dealbreakers.

Usual applications of range compression take the maximum value of an array and divides all the elements of that array by said maximum value in order to make the range of said array to 0...1.

Niko Suni

it's a part of a game i plan on making, the player will select a music file on their computer which is used to generate a weapon, to do this i have decided to use the name of the file so it's all for show really. the random element is so that it couldnt be cheated too easily but someone finding out the name of x will always give y weapon.

i posted in general programming because i didn't really feel it was game specific though i guess i could have posted in maths..
int number_within_range = (total_value ^ random_number) % 101;
This should do it (untested, assuming C++):
int CalculateRandom(const std::string& str, int nMin, int nMax){   // Sum filename ASCII   int nSum = 0;   for(size_t i=0; i<str.length(); ++i)      nSum += str;   // Add random   nSum += rand();   // Move into range nMin..nMax   return (nSum % (nMax-nMin)) + nMin;}
Assuming the range is closed:
return (nSum % (nMax-nMin+1)) + nMin;
The problem with this scheme is that the result of something plus (or xor) something random is random. So the dependency on the filename won't be noticeable.

How would you tell that this code is not doing what you want?
  return rand()%100;

Quote:Original post by DevFred
Assuming the range is closed:
return (nSum % (nMax-nMin+1)) + nMin;
Whoops - good point [smile]

This topic is closed to new replies.

Advertisement