This question already has answers here:
Generating random numbers in Objective-C
(13 answers)
Closed 9 years ago.
I have one piece of code that is giving me some trouble and is confusing.
Here is the piece of code...
int r = rand() % 100;
printf("Random number: %u", r);
Why does it print 7 every time? According to the book it should print any number 0-100 I believe... am I wrong with this?
You have to seed it first:
srandom(time(NULL));
It is actually better to just use arc4random:
int r = arc4random() % 100;
printf("Random number: %u", r);
Random numbers are pseudo-random. To make them seem random, they are seeded at arbitrary times based on your design. If you want seeding and "random" number generation to happen simultaneously, use arc4random instead, which also provides other benefits.
Related
This question already has answers here:
Understanding The Modulus Operator %
(10 answers)
Closed 2 years ago.
I am learning kotlin and in a snipped of code iterating through a list i have this line:
currentIndex = (currentIndex + 1) % myList.size
I am confused by the % sign. Does it mean that you should increment currentIndex by 1 until you get to the size of myList?
I couldnt find anything in documentation about it and the text book just seems to assume I should know!
Modulus operator. Take a look to the next links:
https://kotlinlang.org/docs/reference/operator-overloading.html
https://www.programiz.com/kotlin-programming/operators
EDIT 1: Sorry, I forgot to answer your question really.
What it makes that statement is to increment the currentIndex by 1 at each iteration, until it ranges the whole list. When that happens, the currentIndex is initialized to 0 again. When currentIndex = 9, the next iteration will be set to zero again.
Cheers.
This question already has an answer here:
Out of bounds Problem with attributedSubstringFromRange
(1 answer)
Closed 6 years ago.
I am getting this output:
[NSConcreteData getBytes:range:]: range {2605022, 2605022} exceeds data length 3907534'
From this statement:
for(uint i = data.length*2/3; i<data.length; i++){
// NSLog(#"i: %u",i);
[data getBytes:buffer range:NSMakeRange(i,i)];
}
What I am doing wrong? I have never used Objective-C before, so I really don't know what I'm doing.
For those in my shoes, NSMakeRange is not start and end. It is start and length. A similar question was posed here: http://idevapps.com/forum/showthread.php?tid=181
This question already has answers here:
Why are variables "i" and "j" used for counters?
(23 answers)
Closed 9 years ago.
I assume there is some historical/mathematical reason that whenever I write I for loop, I use i:
for (var i=0; i<10; i++) {
// do something 10 times
}
I know i is used in mathematics for summations (Σ) and products (∏). Does it just mean "index", or is there some more significant meaning?
I believe it does just mean "index" in the example mentioned.
I know it's not answering your question and probably stating the obvious but I personally would always try to give the variable name some meaning for readability and avoid this confusion when reading others code e.g.
for (int productCounter = 0; productCounter<10; productCounter++){
// do something 10 times
}
In Fortran, variables starting with letters I through M were automatically of type INTEGER, so people could write:
DO 10 J = 1, 10
...do something 10 times...
10 CONTINUE
Labels were numeric in columns 1-5; column 6 was for the continuation character (if needed), and the code started in column 7 (originally up to column 72; column 73-80 on the punched card were for the card's sequence number in the deck).
Single letter names are convenient. In Fortran, you didn't have to declare the variables before you used them.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
why do i always get the same sequence of random numbers with rand()?
I am confounded by the fact that even using different programs (on the same machine) to run /compile, and after nilling the vaues (before and after) the function.. that NO MATTER WHAT.. I'll keep getting the SAME "random" numbers… each and every time I run it. I swear this is NOT how it's supposed to work.. I'm going to illustrate as simply as is possible…
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
int rPrimitive = 0; rPrimitive = 1 + rand() % 50;
NSNumber *rObject = nil; rObject = [NSNumber numberWithInt:rand() % 10];
NSLog(#"%i %#", rPrimitive, rObject);
rPrimitive = 0; rObject = nil;
NSLog(#"%i %#", rPrimitive, rObject);
return 0;
}
Run it in TextMate:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
Run it in CodeRunner:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
Run it a million times, if you'd like. You can gues what it will always be. Why does this happen? Why oh why is this "how it is"?
This is why (from the rand man page):
If no seed value is provided, the rand() function is automatically
seeded with a value of 1.
Since it is always seeded with the same number it will always produce the same sequence of numbers. To get it to produce a different sequence each time it runs, you need to use a different seed each time it runs. You can use srand() to set the seed.
Because the numbers aren't random, they're pseudorandom. They're generated according to an algorithm which will always produce the same output, given the same initial seed. You're not seeding the PRNG, so it uses a default, constant seed.
If you seed the PRNG using something less predictable (such as the current time and/or PID), you will get different results each time. In the case of rand(3), you need to seed it with srand(3).
The reason it is like that is because rand is a pseudo-random-number-generator, meaning it doesn't generate true random numbers (which is actually a very difficult thing to do). It generates the next number in the sequence using the “seed”, and at the start of execution the seed is always set to the same value (1 or so), so if you don't change the seed, you'll always get the same sequence of random numbers. You can use something like srand(time(NULL)); to seed the random number generator based on the time, or you can use a random number generator that is considered strong enough for cryptographic purposes, arc4random.
You might thing “why is it like this?”, but there are some cases where you want to generate the same series of “random numbers” multiple times.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Recognizing when to use the mod operator
What are the practical uses of modulus? I know what modulo division is. The first scenario which comes to my mind is to use it to find odd and even numbers, and clock arithmetic. But where else I could use it?
The most common use I've found is for "wrapping round" your array indices.
For example, if you just want to cycle through an array repeatedly, you could use:
int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
// ... use a[i] ...
}
The modulo ensures that i stays in the [0, 10) range.
I usually use them in tight loops, when I have to do something every X loops as opposed to on every iteration..
Example:
int i;
for (i = 1; i <= 1000000; i++)
{
do_something(i);
if (i % 1000 == 0)
printf("%d processed\n", i);
}
One use for the modulus operation is when making a hash table. It's used to convert the value out of the hash function into an index into the array. (If the hash table size is a power of two, the modulus could be done with a bit-mask, but it's still a modulus operation.)
To print a number as string, you need the modulus to find the value of a digit.
string number_to_string(uint number) {
string result = "";
while (number != 0) {
result = cast(char)((number % 10) + '0') ~ result;
// ^^^^^^^^^^^
number /= 10;
}
return result;
}
For the control number of international bank account numbers, the mod97 technique.
Also in large batches to do something after n iterations. Here is an example for NHibernate:
ISession session = sessionFactory.openSession();
ITransaction tx = session.BeginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.Save(customer);
if ( i % 20 == 0 ) { //20, same as the ADO batch size
//Flush a batch of inserts and release memory:
session.Flush();
session.Clear();
}
}
tx.Commit();
session.Close();
The usual implementation of buffered communications uses circular buffers, and you manage them with modulus arithmetic.
For languages that don't have bitwise operators, modulus can be used to get the lowest n bits of a number. For example, to get the lowest 8 bits of x:
x % 256
which is equivalent to:
x & 255
Cryptography. That alone would account for an obscene percentage of modulus (I exaggerate, but you get the point).
Try the Wikipedia page too:
Modular arithmetic is referenced in number theory, group theory, ring theory, knot theory, abstract algebra, cryptography, computer science, chemistry and the visual and musical arts.
In my experience, any sufficiently advanced algorithm is probably going to touch on one more of the above topics.
Well, there are many perspectives you can look at it. If you are looking at it as a mathematical operation then it's just a modulo division. Even we don't need this as whatever % do, we can achieve using subtraction as well, but every programming language implement it in very optimized way.
And modulu division is not limited to finding odd and even numbers or clock arithmetic. There are hundreds of algorithms which need this module operation, for example, cryptography algorithms, etc. So it's a general mathematical operation like other +, -, *, /, etc.
Except the mathematical perspective, different languages use this symbol for defining built-in data structures, like in Perl %hash is used to show that the programmer declared a hash. So it all varies based on the programing language design.
So still there are a lot of other perspectives which one can do add to the list of use of %.