I am working on calculator application. For me all operations are cleared except "rand". Could any one tell me how to generate random number of some number by selecting rand.
For example
initially i select one(1) then rand... if so it has to be displayed random number of one(1).
In objective-C you should use (for between 0 and 1)
int r = arc4random() % 10;
float r2 = r/10
Imagine that you want a number between 0 and 50 with decimals, then you should do:
int r = arc4random()%50*100;
float r2 = r/100;
You will get something like 40.123
NSInteger num = (arc4random() % maxnumber) + 1;
Check the synopsis...
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include
u_int32_t
arc4random(void);
void
arc4random_stir(void);
void
arc4random_addrandom(unsigned char *dat, int datlen);
DESCRIPTION
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
bit S-Boxes. The S-Boxes can be in about (2*1700) states. The arc4random() function returns pseudo-
random numbers in the range of 0 to (2*32)-1, and therefore has twice the range of rand(3) and
random(3).
The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
arc4random_addrandom().
There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
initializes itself.
EXAMPLES
The following produces a drop-in replacement for the traditional rand() and random() functions using
arc4random():
#define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
Related
I have a simple problem, but because this "programming language" I am using is 32-bit and only supports basic functions such as addition, subtraction, multiplication, division, and concatenation (literally that's it), I am having some trouble.
For the input, I have a 16 digit number like so: 3334,5678,9523,4567
I want to then subtract 2 other random 16 digit numbers from this number and check if the first and last digits are 1.
For example, if the two other numbers are 1111,1111,1111,1111 and 1234,5678,9123,4565.
My final number would be: 0988,8888,9288,8891.
Here, the last number is 1, but the first number is 0, so the test would fail.
The issue is with 32-bit systems, there are massive errors due to not enough precision provided by the bits. What are some ways to bypass this issue?
If you're using a language like C or Java you should be able to use a long to create a 64 bit integer. If that's not possible you could divide the numbers into two 32 bit numbers, one to hold the upper half and one to hold the lower half.
Something like this:
//Each half is 8 digits to represent 8 of the 16
//Because of this each half should be less than 100000000
int upperHalf = 33345678;
int lowerHalf = 95234567;
//randomInt represents a function to generate a random
//integer equal to or greater than 0 and less than the
//argument passed to it
int randUpperHalf = randomInt(100000000);
int randLowerHalf = randomInt(100000000);
int lowerHalf = lowerHalf - randLowerHalf;
//If lowerHalf was a negative number you need to borrow from the upperHalf
if (lowerHalf < 0) {
upperHalf = upperHalf - 1;
lowerHalf = lowerHalf + 100000000;
}
upperHalf = upperHalf - randUpperHalf;
//Check that the first and last digits are 1
if ((upperHalf / 100000000) == 1 && (lowerHalf % 10) == 1) {
//The first and last digits are 1
}
Edit: Comments have been added to explain the code better. (lowerHalf % 2) == 1 has been changed to (lowerHalf % 10) == 1 and should now be able to tell if the number ends in a 1.
I am calling arc4random in a function in my iOS application to generate random values from -5 to 6.
double num;
for (int i = 0; i < 3; i++) {
num = (arc4random() % 11) - 5;
NSLog(#"%0.0f", num);
}
I get the following output from console.
2012-05-01 20:25:41.120 Project32[8331:fb03] 0
2012-05-01 20:25:41.121 Project32[8331:fb03] 1
2012-05-01 20:25:41.122 Project32[8331:fb03] 4294967295
0 and 1 are values within range, but wowww, where did 4294967295 come from?
Changing arc4random() to rand() fixes the problem, but rand(), of course, requires seeding.
arc4random() returns a u_int32_t -- that's an unsigned integer, one that doesn't represent negative values. Every time arc4random() % 11 comes up with a number 0 ≤ n < 5, you subtract 5 and wrap around to a very large number.
doubles can represent negative numbers, of course, but you're not converting to double until it's too late. Stick a cast in there:
num = (double)(arc4random() % 11) - 5;
to promote the result of the modulo before the subtraction, and everything will be okay.
Try using
arc4random_uniform(11) - 5;
instead.
From the man page:
arc4random_uniform() will return a uniformly distributed random number
less than upper_bound. arc4random_uniform() is recommended over con-
structions like ``arc4random() % upper_bound'' as it avoids "modulo bias"
when the upper bound is not a power of two.
I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?
int r = arc4random() % (9);
NSLog(#"Random Number: %d",r);
int r = (arc4random() % 8) + 1
You can use arc4random_uniform(), as in
arc4random_uniform(9) + 1
Generally, to generate a number between lo and hi (inclusive), you use:
arc4random_uniform(hi - lo + 1) + lo
If you don't want to use arc4random_uniform() and want to stick with arc4random(), noting that the resulting value from using modulus formula is not uniformly distributed, use
(arc4random() % (hi - lo + 1)) + lo
int r = arc4random() % 8 + 1;
See other answers (e.g., one from me) for why you probably don't want to use % for this task, and what you should use instead.
You could simply try repeatedly until you get a number in the range you want, throwing out numbers you don't want. This has the fancy name "acceptance-rejection method" in math. It's simple, and it works.
In case you're worried that this could take a long time, in theory it could. But this approach is used all the time in statistical applications. The probability of going through a while-loop N times decreases rapidly as N increases, so the average number of times through the loop is small.
I am making a game for my C class (actually remaking one) and I have a function that produces random prices. The problem is that I need to call this function 60 times throughout the game and have the numbers regenerate to new ones every time the function is called. Is it possible to do this without ending the the program, and if so then how?
So far I've written a for loop for the funct. but it just prints the same function 60 times which I kindof expected to happen.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int Prices(void)
{
//Random price generator
int Acid = rand() % 10+ 1;
int Coke = rand() % 150+ 101;
int Crack = rand() % 30 + 15;
int Ecstasy = rand() % 8 + 1;
int Herion = rand() % 100 + 46;
int Meth = rand() % 100 + 26;
int Opium = rand() % 65 + 31;
int Pills = rand() % 7 + 1;
int Shrooms = rand() % 30 + 16;
int Speed = rand() % 45 + 11;
int Weed = rand() % 20 + 21;
//Prints the above random prices to the main screen
printf("PRICE PER UNIT:\n\n");
printf("Acid: ""%i\n",Acid);
printf("Coke: ""%i\n",Coke);
printf("Crack: ""%i\n",Crack);
printf("Ecstasy: ""%i\n",Ecstasy);
printf("Herion: ""%i\n",Herion);
printf("Meth: ""%i\n",Meth);
printf("Opium ""%i\n",Opium);
printf("Pills: ""%i\n", Pills);
printf("Shrooms: ""%i\n", Shrooms);
printf("Speed: ""%i\n",Speed);
printf("Weed: ""%i\n",Weed);
printf("********************************************************************************\n");
return Acid && Coke && Crack && Ecstasy && Herion && Meth && Opium && Pills && Shrooms && Speed && Weed;
}
int main(void){
int Prices(void);
int i;
for(i=0; i<60; i++){
Prices();
}
}
Ok So I deleted the srand function and that worked but I also need way to limit this function to being called only 60 times periodically throughout the game and not all at once.
Don't call srand yourself, delete this line:
srand((unsigned)time(NULL)); //Uses time as seed for random numbers
Your time() call only has one second resolution and each run through the loop takes much much less than one second, the result is that you're seeding the random number generator with the same value every time and that yields the same set of random numbers.
Modern rand() implementations take care of seeding the random number generator themselves.
Most random number generators are actually deterministic functions of their seed, your rand() looks like it is one of these. The standard refers to what rand() generates as pseudo-random integers for a good reason.
One option is to use a static variable to signal if your seed has already been set. This snippet would show how to do it:
...
static int srand_flag = 0;
if (!srand_flag) {
srand_flag = 1;
srand((unsigned)time(NULL));
}
...
This will ensure that you only call your seed once and thus that you won't run into the 1-second granularity that most time() implementations give you.
Another option is to use a (usually platform-specific) millisecond timer instead for your seed. What function call gives you that is highly platform-dependent, however. In Linux you'd have to mess around with things like clock_gettime() while in Windows you'd probably be messing around with things like GetTickCount().
A final option, if you absolutely must call srand() each and every time, is to put a delay of one second before each call to srand() to ensure that the counter value is different on every call. (This is not a good option.)
int x = n / 3; // <-- make this faster
// for instance
int a = n * 3; // <-- normal integer multiplication
int b = (n << 1) + n; // <-- potentially faster multiplication
The guy who said "leave it to the compiler" was right, but I don't have the "reputation" to mod him up or comment. I asked gcc to compile int test(int a) { return a / 3; } for an ix86 and then disassembled the output. Just for academic interest, what it's doing is roughly multiplying by 0x55555556 and then taking the top 32 bits of the 64 bit result of that. You can demonstrate this to yourself with eg:
$ ruby -e 'puts(60000 * 0x55555556 >> 32)'
20000
$ ruby -e 'puts(72 * 0x55555556 >> 32)'
24
$
The wikipedia page on Montgomery division is hard to read but fortunately the compiler guys have done it so you don't have to.
This is the fastest as the compiler will optimize it if it can depending on the output processor.
int a;
int b;
a = some value;
b = a / 3;
There is a faster way to do it if you know the ranges of the values, for example, if you are dividing a signed integer by 3 and you know the range of the value to be divided is 0 to 768, then you can multiply it by a factor and shift it to the left by a power of 2 to that factor divided by 3.
eg.
Range 0 -> 768
you could use shifting of 10 bits, which multiplying by 1024, you want to divide by 3 so your multiplier should be 1024 / 3 = 341,
so you can now use (x * 341) >> 10
(Make sure the shift is a signed shift if using signed integers), also make sure the shift is an actually shift and not a bit ROLL
This will effectively divide the value 3, and will run at about 1.6 times the speed as a natural divide by 3 on a standard x86 / x64 CPU.
Of course the only reason you can make this optimization when the compiler cant is because the compiler does not know the maximum range of X and therefore cannot make this determination, but you as the programmer can.
Sometime it may even be more beneficial to move the value into a larger value and then do the same thing, ie. if you have an int of full range you could make it an 64-bit value and then do the multiply and shift instead of dividing by 3.
I had to do this recently to speed up image processing, i needed to find the average of 3 color channels, each color channel with a byte range (0 - 255). red green and blue.
At first i just simply used:
avg = (r + g + b) / 3;
(So r + g + b has a maximum of 768 and a minimum of 0, because each channel is a byte 0 - 255)
After millions of iterations the entire operation took 36 milliseconds.
I changed the line to:
avg = (r + g + b) * 341 >> 10;
And that took it down to 22 milliseconds, its amazing what can be done with a little ingenuity.
This speed up occurred in C# even though I had optimisations turned on and was running the program natively without debugging info and not through the IDE.
See How To Divide By 3 for an extended discussion of more efficiently dividing by 3, focused on doing FPGA arithmetic operations.
Also relevant:
Optimizing integer divisions with Multiply Shift in C#
Depending on your platform and depending on your C compiler, a native solution like just using
y = x / 3
Can be fast or it can be awfully slow (even if division is done entirely in hardware, if it is done using a DIV instruction, this instruction is about 3 to 4 times slower than a multiplication on modern CPUs). Very good C compilers with optimization flags turned on may optimize this operation, but if you want to be sure, you are better off optimizing it yourself.
For optimization it is important to have integer numbers of a known size. In C int has no known size (it can vary by platform and compiler!), so you are better using C99 fixed-size integers. The code below assumes that you want to divide an unsigned 32-bit integer by three and that you C compiler knows about 64 bit integer numbers (NOTE: Even on a 32 bit CPU architecture most C compilers can handle 64 bit integers just fine):
static inline uint32_t divby3 (
uint32_t divideMe
) {
return (uint32_t)(((uint64_t)0xAAAAAAABULL * divideMe) >> 33);
}
As crazy as this might sound, but the method above indeed does divide by 3. All it needs for doing so is a single 64 bit multiplication and a shift (like I said, multiplications might be 3 to 4 times faster than divisions on your CPU). In a 64 bit application this code will be a lot faster than in a 32 bit application (in a 32 bit application multiplying two 64 bit numbers take 3 multiplications and 3 additions on 32 bit values) - however, it might be still faster than a division on a 32 bit machine.
On the other hand, if your compiler is a very good one and knows the trick how to optimize integer division by a constant (latest GCC does, I just checked), it will generate the code above anyway (GCC will create exactly this code for "/3" if you enable at least optimization level 1). For other compilers... you cannot rely or expect that it will use tricks like that, even though this method is very well documented and mentioned everywhere on the Internet.
Problem is that it only works for constant numbers, not for variable ones. You always need to know the magic number (here 0xAAAAAAAB) and the correct operations after the multiplication (shifts and/or additions in most cases) and both is different depending on the number you want to divide by and both take too much CPU time to calculate them on the fly (that would be slower than hardware division). However, it's easy for a compiler to calculate these during compile time (where one second more or less compile time plays hardly a role).
For 64 bit numbers:
uint64_t divBy3(uint64_t x)
{
return x*12297829382473034411ULL;
}
However this isn't the truncating integer division you might expect.
It works correctly if the number is already divisible by 3, but it returns a huge number if it isn't.
For example if you run it on for example 11, it returns 6148914691236517209. This looks like a garbage but it's in fact the correct answer: multiply it by 3 and you get back the 11!
If you are looking for the truncating division, then just use the / operator. I highly doubt you can get much faster than that.
Theory:
64 bit unsigned arithmetic is a modulo 2^64 arithmetic.
This means for each integer which is coprime with the 2^64 modulus (essentially all odd numbers) there exists a multiplicative inverse which you can use to multiply with instead of division. This magic number can be obtained by solving the 3*x + 2^64*y = 1 equation using the Extended Euclidean Algorithm.
What if you really don't want to multiply or divide? Here is is an approximation I just invented. It works because (x/3) = (x/4) + (x/12). But since (x/12) = (x/4) / 3 we just have to repeat the process until its good enough.
#include <stdio.h>
void main()
{
int n = 1000;
int a,b;
a = n >> 2;
b = (a >> 2);
a += b;
b = (b >> 2);
a += b;
b = (b >> 2);
a += b;
b = (b >> 2);
a += b;
printf("a=%d\n", a);
}
The result is 330. It could be made more accurate using b = ((b+2)>>2); to account for rounding.
If you are allowed to multiply, just pick a suitable approximation for (1/3), with a power-of-2 divisor. For example, n * (1/3) ~= n * 43 / 128 = (n * 43) >> 7.
This technique is most useful in Indiana.
I don't know if it's faster but if you want to use a bitwise operator to perform binary division you can use the shift and subtract method described at this page:
Set quotient to 0
Align leftmost digits in dividend and divisor
Repeat:
If that portion of the dividend above the divisor is greater than or equal to the divisor:
Then subtract divisor from that portion of the dividend and
Concatentate 1 to the right hand end of the quotient
Else concatentate 0 to the right hand end of the quotient
Shift the divisor one place right
Until dividend is less than the divisor:
quotient is correct, dividend is remainder
STOP
For really large integer division (e.g. numbers bigger than 64bit) you can represent your number as an int[] and perform division quite fast by taking two digits at a time and divide them by 3. The remainder will be part of the next two digits and so forth.
eg. 11004 / 3 you say
11/3 = 3, remaineder = 2 (from 11-3*3)
20/3 = 6, remainder = 2 (from 20-6*3)
20/3 = 6, remainder = 2 (from 20-6*3)
24/3 = 8, remainder = 0
hence the result 3668
internal static List<int> Div3(int[] a)
{
int remainder = 0;
var res = new List<int>();
for (int i = 0; i < a.Length; i++)
{
var val = remainder + a[i];
var div = val/3;
remainder = 10*(val%3);
if (div > 9)
{
res.Add(div/10);
res.Add(div%10);
}
else
res.Add(div);
}
if (res[0] == 0) res.RemoveAt(0);
return res;
}
If you really want to see this article on integer division, but it only has academic merit ... it would be an interesting application that actually needed to perform that benefited from that kind of trick.
Easy computation ... at most n iterations where n is your number of bits:
uint8_t divideby3(uint8_t x)
{
uint8_t answer =0;
do
{
x>>=1;
answer+=x;
x=-x;
}while(x);
return answer;
}
A lookup table approach would also be faster in some architectures.
uint8_t DivBy3LU(uint8_t u8Operand)
{
uint8_t ai8Div3 = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, ....];
return ai8Div3[u8Operand];
}