Obj-c wont parse if statement with mod - objective-c

So Im using a simple if statement to increase an object's speed when an score is reached. Im using a very simple if statement that doesnt work. In this context, "pigSpeed" controls the velocity of the object.
float difference = (self.view.bounds.size.height/4) - flyingPig.center.x;
score += -(int)difference;
if (score % 1000 == 0 & score > 0)
{
pigSpeed++;
NSLog(#"pigfaster");
}
I know the score works properly, as it is displayed, as it appears, but the if statement just wont work and nothing happens. What am I doing wrong. I can add more code if needed.

& is the bitwise and operator; && is the logical and that you mean to use here. Your if statement should actually read:
if (score % 1000 == 0 && score > 0)

Further to what #victor ronin said...
float difference = ( self.view.bounds.size.height / 4.0f ) - flyingPig.center.x;
int newScore = score + difference ;
if ( newScore > 0 && ( newScore / 1000 > score / 1000 ) )
{
// did thousands place increment?
++pigSpeed;
}
score = newScore ;

I agree with andyvn22 - you should use && instead of &. However, there is one more problem.
Let's say you have score = 999
after you calculate difference and it's difference = -5
Your score will become 1004. 1004 % 1000 will be 4 (not a zero)
I think you should change your condition some way that even if you jump over 1000 you still increase a speed.

I had to give just a bit of leeway so 'if (score % 1000 == 2 && score > 999)'

Related

WhateverStar `&&` WhateverStar in Perl 6

* > 20 && * %% 5 used in grep seems wrong, does is equal to a WhateverCode lambda that takes 2 arguments? As this explain on SO
> my #a = 1,12,15,20,25,30,35,37;
> #a.grep: * > 20 && * %% 5 # The result seems strange, expected (25 30 35)
(15 20 25 30 35)
> #a.grep: * %% 5 && * > 20
(25 30 35 37)
> #a.grep: { $_>20 && $_ %% 5 }
(25 30 35)
> #a.grep: all(* > 20, * %% 5)
(25 30 35)
> #a.grep: -> $a { all($a > 20, $a %% 5) }
(25 30 35)
> #a.grep: -> $a {$a > 20 && $a %% 5}
(25 30 35)
Golfed
my &or = * == 1 || * == 2 ;
my &and = * == 1 && * == 2 ;
say .signature, .(1), .(2)
for &or, ∧
displays:
(;; $whatevercode_arg_1 is raw)TrueFalse
(;; $whatevercode_arg_4 is raw)FalseTrue
I still don't know what's going on [ed: that is, I didn't at the time I wrote this paragraph; I kept what I wrote in this answer as the mystery unfolded], but it's clear that the signature is for just one arg and the result is as per just the right hand expression for the &and and the left hand for the &or which means the code doesn't seem to have, er, left the result that's, er, right. Investigation continues... (and no, I'm not det remiker).
Mystery solved
So, it looks like the logical ops (&&, ||, and, or, etc.) don't do Whatever-currying. Which is fair enough given that "not all operators and syntactic constructs curry * (or Whatever-stars) to WhateverCode". Logical, even, given their nature. They probably ought to be added to the table of exceptions on that page though.
In the meantime, operators like == do Whatever curry. Again, that's fair enough given "subexpressions may impose their own Whatever star rules".
So it makes sense that &or and &and turn in to...
Aha! Got it. The * == 1 and * == 2 are evaluated at compile-time and turn into WhateverCodes. As WhateverCodes they are just bits of code. They are defined. They are True. (This ignores calling them at run-time.) Then along comes the && and evaluates to the right hand WhateverCode. (The || would evaluate to its left hand WhateverCode.)
Hence the behavior we see.
A solution
Per prompting by #HåkonHægland, the code that would work is therefore code that doesn't rely on logical ops Whatever-currying, i.e.:
my #a = 1,12,15,20,25,30,35,37;
say #a.grep: { $_ > 20 && $_ %% 5 } # (25 30 35)
Now what?
Now we have to figure out what doc edits to propose...
Actually, before we do that, confirm that logical ops are supposed to not Whatever-curry...
And to start that ball rolling, I just trawled the results of a search for TimToady comments on #perl6 about "currying" (there were none on #perl6-dev), looking for ones pertinent to the case we have here.
First, one from 2017 that's arguably relevant to any doc edits:
the design docs actually try to avoid the word "currying" ... but it's hard to get people to use words differently than they do
Next, one from 2015 about && and || and such:
|| and && and such are really control flow operators, turned rather rapidly into 'if' and 'unless' ... those ops can be curried with .assuming, I assume
And finally a couple from 2010 that also seem potentially important (though perhaps one or more are no longer applicable?):
all operators autocurry a WhateverCode, whether or not they curry a Whatever
I think we can keep the current mechanism as a fallback for operators that still want to curry at run time
> my $d = * + * + *
> $d.arity
3
> my $e = * == 1 || * == 2 || * == 3
> $e.arity
1
as the doc say:
Returns the minimum number of positional arguments that must be passed in order to call the code object.
so I think the all three star in * == 1 || * == 2 || * == 3 is the same thing.
> my $e = * == 1 && * == 2 && * > 3
> $e(1)
False
> $e(2)
False
> $e(3)
False
> $e(4)
True

Looping until multiple conditions reached in Objective-C

So i am trying to create a program that can find a number that can be divided by numbers 1-20. I know that i will have to use the following simple code concepts:
I know how loops work and how to create a loop that runs until a condition is met. Is there a simple was to run a loop until several conditions are met?
while ( condition1 && condition2 && condition3... ) {}
or
for ( int i = 0; i < n && condition1 && condition2... ) {}
Obviously these will loop while the conditions are true, not until the conditions are met. Its a simple change in the logic though to get the result you want
EDIT
Ane example of the kind of loop youre looking for could be like:
int number = ...;//initialized somewhere, this is what we're checking
BOOL divisible = YES;
for ( int i = 1; i <= 20 && divisible; ++i )
{
if ( (number % i) != 0 )
divisible = NO;//not divisible by i
}
Good answers in play, but I think it's good to mention the break operator in this discussion. Any loop, at any time, can be terminated using this operator. This can be helpful if you do not know all of the parameters which might go out-of-bounds, and you want to have a way of breaking the loop for reasons you may not have explicitly anticipated (i.e. perhaps your connection to a resource is no longer available...)
NSError *error = nil;
while(true) {
// run your app
if(error) {
break;
}
}
If a number is divisible by all numbers from 1 to 20 then it is divisible by the LCM of 1 to 20 so divisibility test is if(!(n%232792560)).
Further if m = pq | n then p|n, q|n so to explicitly test you only need to check for divisibility by primes. i.e if the number is not even then there is no need to check for divisibility by 4, 6, 8, 10, 12, 14, 16, 18 or 20. This reduces the test to the number being congruent to the 8th primorial = 9699690
OK, perhaps on second reading not as explicit as I should like: the expanded test looks like (by de Morgan's theorem)
if(!(n%19 || n%17 || n%16 || n%13 || n%11 || n%9 || n%7 || n%5))
// number is divisible by 1..20

Could abs(random()) % someNumberGreaterThanZero return zero?

SELECT foo FROM bar
WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
LIMIT 1;
I saw this in another answer as an alternative to ORDER BY random(). I need to make sure id would always be greater than zero. Do I have to change >= to >?
Since x % y returns 0 when x is a multiple of y, the answer is "Yes, your expression could return 0".
So, if id must be greater than 0, you need to use > rather than >=. Of course, if the modulo operator didn't return 0, you could still use > instead of >= and you'd get the same effect.
Yes. If abs(random()) returned the value of max(id), then the modulo's result would be zero. Since abs(random()) can return any value between 0 & 9223372036854775807, this is definitely possible.
Yes it can return 0 in two ways
Consider that 3 % 3 == 0, 6 % 3 == 0, etc. Then you would get 0 if random() happens to be max(id) or an even divider thereof.
random() can also return 0 and 0 % anything == 0, that is the other possibility.
Yes, it should be > because modulo division can return 0( a mod a ==0, 0 mod a == 0). Also, you might want to check if (SELECT max(id) is not null/0 (a mod 0 is undefined in some systems, or a)

Recognizing when to use the modulus operator

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?
I know I can use the modulus operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the modulus operator is useful, and I would like to learn to take advantage of it.
I just have problems identifying where the modulus operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "Hey! The remainder of division would work here!".
Imagine that you have an elapsed time in seconds and you want to convert this to hours, minutes, and seconds:
h = s / 3600;
m = (s / 60) % 60;
s = s % 60;
0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;
Did you see what it did? At the last step it went back to zero. This could be used in situations like:
To check if N is divisible by M (for example, odd or even)
or
N is a multiple of M.
To put a cap of a particular value. In this case 3.
To get the last M digits of a number -> N % (10^M).
I use it for progress bars and the like that mark progress through a big loop. The progress is only reported every nth time through the loop, or when count%n == 0.
I've used it when restricting a number to a certain multiple:
temp = x - (x % 10); //Restrict x to being a multiple of 10
Wrapping values (like a clock).
Provide finite fields to symmetric key algorithms.
Bitwise operations.
And so on.
One use case I saw recently was when you need to reverse a number. So that 123456 becomes 654321 for example.
int number = 123456;
int reversed = 0;
while ( number > 0 ) {
# The modulus here retrieves the last digit in the specified number
# In the first iteration of this loop it's going to be 6, then 5, ...
# We are multiplying reversed by 10 first, to move the number one decimal place to the left.
# For example, if we are at the second iteration of this loop,
# reversed gonna be 6, so 6 * 10 + 12345 % 10 => 60 + 5
reversed = reversed * 10 + number % 10;
number = number / 10;
}
Example. You have message of X bytes, but in your protocol maximum size is Y and Y < X. Try to write small app that splits message into packets and you will run into mod :)
There are many instances where it is useful.
If you need to restrict a number to be within a certain range you can use mod. For example, to generate a random number between 0 and 99 you might say:
num = MyRandFunction() % 100;
Any time you have division and want to express the remainder other than in decimal, the mod operator is appropriate. Things that come to mind are generally when you want to do something human-readable with the remainder. Listing how many items you could put into buckets and saying "5 left over" is good.
Also, if you're ever in a situation where you may be accruing rounding errors, modulo division is good. If you're dividing by 3 quite often, for example, you don't want to be passing .33333 around as the remainder. Passing the remainder and divisor (i.e. the fraction) is appropriate.
As #jweyrich says, wrapping values. I've found mod very handy when I have a finite list and I want to iterate over it in a loop - like a fixed list of colors for some UI elements, like chart series, where I want all the series to be different, to the extent possible, but when I've run out of colors, just to start over at the beginning. This can also be used with, say, patterns, so that the second time red comes around, it's dashed; the third time, dotted, etc. - but mod is just used to get red, green, blue, red, green, blue, forever.
Calculation of prime numbers
The modulo can be useful to convert and split total minutes to "hours and minutes":
hours = minutes / 60
minutes_left = minutes % 60
In the hours bit we need to strip the decimal portion and that will depend on the language you are using.
We can then rearrange the output accordingly.
Converting linear data structure to matrix structure:
where a is index of linear data, and b is number of items per row:
row = a/b
column = a mod b
Note above is simplified logic: a must be offset -1 before dividing & the result must be normalized +1.
Example: (3 rows of 4)
1 2 3 4
5 6 7 8
9 10 11 12
(7 - 1)/4 + 1 = 2
7 is in row 2
(7 - 1) mod 4 + 1 = 3
7 is in column 3
Another common use of modulus: hashing a number by place. Suppose you wanted to store year & month in a six digit number 195810. month = 195810 mod 100 all digits 3rd from right are divisible by 100 so the remainder is the 2 rightmost digits in this case the month is 10. To extract the year 195810 / 100 yields 1958.
Modulus is also very useful if for some crazy reason you need to do integer division and get a decimal out, and you can't convert the integer into a number that supports decimal division, or if you need to return a fraction instead of a decimal.
I'll be using % as the modulus operator
For example
2/4 = 0
where doing this
2/4 = 0 and 2 % 4 = 2
So you can be really crazy and let's say that you want to allow the user to input a numerator and a divisor, and then show them the result as a whole number, and then a fractional number.
whole Number = numerator/divisor
fractionNumerator = numerator % divisor
fractionDenominator = divisor
Another case where modulus division is useful is if you are increasing or decreasing a number and you want to contain the number to a certain range of number, but when you get to the top or bottom you don't want to just stop. You want to loop up to the bottom or top of the list respectively.
Imagine a function where you are looping through an array.
Function increase Or Decrease(variable As Integer) As Void
n = (n + variable) % (listString.maxIndex + 1)
Print listString[n]
End Function
The reason that it is n = (n + variable) % (listString.maxIndex + 1) is to allow for the max index to be accounted.
Those are just a few of the things that I have had to use modulus for in my programming of not just desktop applications, but in robotics and simulation environments.
Computing the greatest common divisor
Determining if a number is a palindrome
Determining if a number consists of only ...
Determining how many ... a number consists of...
My favorite use is for iteration.
Say you have a counter you are incrementing and want to then grab from a known list a corresponding items, but you only have n items to choose from and you want to repeat a cycle.
var indexFromB = (counter-1)%n+1;
Results (counter=indexFromB) given n=3:
`1=1`
`2=2`
`3=3`
`4=1`
`5=2`
`6=3`
...
Best use of modulus operator I have seen so for is to check if the Array we have is a rotated version of original array.
A = [1,2,3,4,5,6]
B = [5,6,1,2,3,4]
Now how to check if B is rotated version of A ?
Step 1: If A's length is not same as B's length then for sure its not a rotated version.
Step 2: Check the index of first element of A in B. Here first element of A is 1. And its index in B is 2(assuming your programming language has zero based index).
lets store that index in variable "Key"
Step 3: Now how to check that if B is rotated version of A how ??
This is where modulus function rocks :
for (int i = 0; i< A.length; i++)
{
// here modulus function would check the proper order. Key here is 2 which we recieved from Step 2
int j = [Key+i]%A.length;
if (A[i] != B[j])
{
return false;
}
}
return true;
It's an easy way to tell if a number is even or odd. Just do # mod 2, if it is 0 it is even, 1 it is odd.
Often, in a loop, you want to do something every k'th iteration, where k is 0 < k < n, assuming 0 is the start index and n is the length of the loop.
So, you'd do something like:
int k = 5;
int n = 50;
for(int i = 0;i < n;++i)
{
if(i % k == 0) // true at 0, 5, 10, 15..
{
// do something
}
}
Or, you want to keep something whitin a certain bound. Remember, when you take an arbitrary number mod something, it must produce a value between 0 and that number - 1.

Objective C - Random results is either 1 or -1

I am trying randomly generate a positive or negative number and rather then worry about the bigger range I am hoping to randomly generate either 1 or -1 to just multiply by my other random number.
I know this can be done with a longer rule of generating 0 or 1 and then checking return and using that to either multiply by 1 or -1.
Hoping someone knows of an easier way to just randomly set the sign on a number. Trying to keep my code as clean as possible.
I like to use arc4random() because it doesn't require you to seed the random number generator. It also conveniently returns a uint_32_t, so you don't have to worry about the result being between 0 and 1, etc. It'll just give you a random integer.
int myRandom() {
return (arc4random() % 2 ? 1 : -1);
}
If I understand the question correctly, you want a pseudorandom sequence of 1 and -1:
int f(void)
{
return random() & 1 ? 1 : -1;
// or...
// return 2 * (random() & 1) - 1;
// or...
// return ((random() & 1) << 1) - 1;
// or...
// return (random() & 2) - 1; // This one from Chris Lutz
}
Update: Ok, something has been bothering me since I wrote this. One of the frequent weaknesses of common RNGs is that the low order bits can go through short cycles. It's probably best to test a higher-order bit: random() & 0x80000 ? 1 : -1
To generate either 1 or -1 directly, you could do:
int PlusOrMinusOne() {
return (rand() % 2) * 2 - 1
}
But why are you worried about the broader range?
return ( ((arc4random() & 2) * 2) - 1 );
This extra step won't give you any additional "randomness". Just generate your number straight away in the range that you need (e.g. -10..10).
Standard rand() will return a value from this range: 0..1
You can multiply it by a constant to increase the span of the range or you can add a constant to push it left/right on the X-Axis.
E.g. to generate random values from from (-5..10) range you will have:
rand()*15-5
rand will give you a number from 0 to RAND_MAX which will cover every bit in an int except for the sign. By shifting that result left 1 bit you turn the signed MSB into the sign, but have zeroed-out the 0th bit, which you can repopulate with a random bit from another call to rand. The code will look something like:
int my_rand()
{
return (rand() << 1) + (rand() & 1);
}