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

## Recommended Posts

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

##### Share on other sites
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.

##### Share on other sites
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..

##### Share on other sites
int number_within_range = (total_value ^ random_number) % 101;

##### Share on other sites
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[i];   // Add random   nSum += rand();   // Move into range nMin..nMax   return (nSum % (nMax-nMin)) + nMin;}

##### Share on other sites
Assuming the range is closed:
return (nSum % (nMax-nMin+1)) + nMin;

##### Share on other sites
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;

##### Share on other sites
Quote:
 Original post by DevFredAssuming the range is closed:return (nSum % (nMax-nMin+1)) + nMin;
Whoops - good point [smile]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628349
• Total Posts
2982210

• 10
• 9
• 24
• 11
• 9