Checking if a number fits between two numbers in objective c? [duplicate] - ios

This question already has answers here:
How to test to see if number is in range using Objective-C?
(6 answers)
Closed 7 years ago.
I was wondering if it's possible to check if a number fits between two numbers in Objective C. For example:
if (variable == 1-100) {
//Do Something
}
I don't mean if the variable is equal to 1 minus 100. I want to know if the variable fits between 1 and 100. I understand this may not be possible but I'm interested to know so if it is possible.

Try below code..
if(variable >= MINVALUE && variable <= MAXVALUE){
** Do your stuff here**
}

In Objective-C you can use this simple check:
if (variable >=1 && variable <= 100)
In Swift it's even easier:
if 1 ... 100 ~= variable

If, by "the variable fits between 1 and 100" you mean "variable should be between 1 and 100, including 1 and 100" then it is pretty trivial:
if (variable >= 1 && variable <= 100) {
//Do Someting
}
NB: The "&&" is the logical test operator AND commonly used in C, C++, Objective-C, Java...

You can do this:
if ( var >= 1 && var <= 100 ){ ... }

Related

Computing remainder without using modulus operator F#

I have implemented my code which is basically to compute remainder in two numbers without using modulus operator however, I am stuck in a situation which is just hectic. I know the logic however I am newbie in f# and dont know how to implement it.
let rec modulus a b =
if b = 0 Console.WriteLine("Sorry Wrong Divisor")
let bool neg = a < 0
a = abs a
b = abs b
modulus(val-divisor,divisor)
All I know is I am getting a pretty basic mistake here, Any help,
The first step towards getting this to work is to fix your indentation and turn your sketch into valid F# code that actually compiles and runs - that should help you get to the next step, which is to fix the logic of the implementation.
A minimal code that is similar to yours and actually runs looks like this:
let rec modulus value divisor : int =
printfn "value=%d, divisor=%d" value divisor
if divisor = 0 then Console.WriteLine("Sorry Wrong Divisor")
let neg = value < 0
let value = abs value
let divisor = abs divisor
modulus (value-divisor) divisor
modulus 10 5
I fixed the indentation - F# is indentation sensitive, so this matters.
I replaced your a = abs a with let - the let keyword defines a new variable, hiding the existing one (as you cannot mutate existing variables - they are immutable in F#)
I renamed your variables to consistently use divisor and value names
I added printfn so that you can see how the function runs (it will get into an infinite loop, because it currently never checks for the termination condition!)
I had to add type annotation : int to say that the result will be int - as your function never returns, this is required (but you can remove it once you fix this)
You can calculate modulus in simpler way
let modulus a b=
if b = 0.0 then failwith "Cannot divide by zero"
a - b * truncate(a / b);

Generation random (positive and negative) numbers for a quiz

I am writing a Math Quiz app for my daughter in xcode/swift.Specifically, I want to produce a question that will contain at least one negative number to be added or subtracted against a second randomly generated number.Cannot be two positive numbers.
i.e.
What is (-45) subtract 12?
What is 23 Minus (-34)?
I am struggling to get the syntax right to generate the numbers, then decide if the said number will be a negative or positive.
Then the second issue is randomizing if the problem is to be addition or subtraction.
It's possible to solve this without repeated number drawing. The idea is to:
Draw a random number, positive or negative
If the number is negative: Draw another number from the same range and return the pair.
If the number is positive: Draw the second number from a range constrained to negative numbers.
Here's the implementation:
extension CountableClosedRange where Bound : SignedInteger {
/// A property that returns a random element from the range.
var random: Bound {
return Bound(arc4random_uniform(UInt32(count.toIntMax())).toIntMax()) + lowerBound
}
/// A pair of random elements where always one element is negative.
var randomPair: (Bound, Bound) {
let first = random
if first >= 0 {
return (first, (self.lowerBound ... -1).random)
}
return (first, random)
}
}
Now you can just write...
let pair = (-10 ... 100).randomPair
... and get a random tuple where one element is guaranteed to be negative.
Here's my attempt. Try running this in a playground, it should hopefully get you the result you want. I hope I've made something clean enough...
//: Playground - noun: a place where people can play
import Cocoa
let range = Range(uncheckedBounds: (-50, 50))
func generateRandomCouple() -> (a: Int, b: Int) {
// This function will generate a pair of random integers
// (a, b) such that at least a or b is negative.
var first, second: Int
repeat {
first = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound
second = Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound))) - range.upperBound
}
while (first > 0 && second > 0);
// Essentially this loops until at least one of the two is less than zero.
return (first, second)
}
let couple = generateRandomCouple();
print("What is \(couple.a) + (\(couple.b))")
// at this point, either of the variables is negative
// I don't think you can do it in the playground, but here you would read
// her input and the expected answer would, naturally, be:
print(couple.a + couple.b)
In any case, feel free to ask for clarifications. Good luck !

How to use Greater than and less. Like a range from 5-10

My application uses animation to push items over the screen. If there are more than 3 items it changes the animation, and adding ten more it changes it even more.
I've created iF and else if statements for my app. The first is: if items = 0. Then no animations
Second is else if items < 3. Then I reduce the force
The third is else items = 0. Then there is no animation
What I want to do is create an if statement for a range of numbers: i.e..
else if items >= 7, but <= 3. Then if there were anywhere from 3-7 items the force would be:...
Here is my code I'm working on as an example:
else if
([self.reorderedButtons count] <= 4) {
pushBehavior.pushDirection = CGVectorMake(0, self.force * .5);
[self.animator addBehavior:pushBehavior];
Is there a reason an AND statement won't work?
You can always combine conditionals with the && (AND) operator or the || (Or operator)
if([self.reorderedButtons count] <= 7 && [self.reorderedButtons count] >= 3)
//Do Function
As a general rule:
Any if-clause will unfold top to bottom. That is
if (i < 3) {
// Code for i < 3
} else if (i <= 7) {
// Code for 3 <= i <= 7
} else {
// Code for i > 7
}
This applies to all major languages.

Average of textfields depending on how many textfield are "used"

Little explication: I have an app with 5 textfields, i already got the code to make the avaerage of them. Using floates and giving a variable to each textfield.so, the adding of the value of all the textfield /5 (divided per 5)
My problem is that when a textfield is leaved emptty, its not goona be /5, if user fill in only 4 cells it will be/4 and so on.
Question: how to divide the adding of cells depending in how many cells have content?
I was tryng with textfield.text.length > 0 in an if. But i dont get it
Thanks, hope i was clear.
You could check each textfield and see if the text is NULL or blank (#"")
Use an int to keep track of the number of textfields that have a value.
For example:
int counter = 0;
float total = 0.0;
if([textfield1.text length] > 0)
{
counter++;
float thisValue = [textfield1.text floatValue];
total = total + thisValue;
}
repeat this for all 5 textfields and then divide your total by the counter variable.
You could include the if statement in a loop if you are going to vary the number of text fields or to reduce the amount of coding you do.
EDIT I have changed my answer based on the good suggestions of other to use text.length
try to count the number of used textfields by increasing a number every time you read out a textfield that has valid text in it and divide the result by that number. (logically the "number" should be initialized as 0)

Randomizing pre-defined numbers

In my app I would like to randomize set values which I set in #define's. I am looking to use arc4random also. I usually would know how to do this but I have only seen tutorials with very basic things like numbers 0-10!
Any tips/help would be appreciated!
put all of your numbers to an array after that calculate an random number in range of 0 and sizeof your array. After you can get your randomized value from random place of predefined array and remove this value. Do it again for range 0 sizoef array - 1 and so on.
From the Wikipedia objective C article it looks like you can define macros using #define. From their example:
#define Add(x,y) ( x + y )
int a = 1;
int b = 2;
int c = Add(a,b);
NSLog(#"Add result: %i", c);
// this will output
// Add result: 3
I'm not sure how complex you can get with those, but I would think you'd be able to do something like #define MY_VAL() (arc4random()%100) to get a range of values, or maybe even use AlexTeho's idea within the macro.

Resources