get an integer -unit digit in a simple way - objective-c

i am not sure about my english, but i need to get the unit digit of an integer.
WITHOUT complex algorithm but with some API or another trick.
for example :
int a= 53;
int b=76;
this i add because i almost always dont "meet the quality standards" to post! its drive me crazy! please , fix it ! it took me 10 shoots to post this,and other issue also.
i need to get a=3 and b=6 in a simple smart way.
same about the other digit.
thanks a lot .

here is how to split the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5

You're looking for % operator.
a=a%10;//divides 'a' by 10, assigns remainder to 'a'

WARNING
here is how to divine the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5
this answer is totally incorrect. It may work only in a number of cases. For example try to get the first digit of 503 via this way
It seems the simplest answer (but not very good in performance):
int a = ...;
int digit = [[[NSString stringWithFormat:#"%d", a] substringToIndex:1] intValue]; //or use substringWithRange to get ANY digit

Modulo operator will help you (as units digit is a reminder when number is divided by 10):
int unitDigit = a % 10;

The following code "gets" the digits of a given number and counts how many of them divide the number exactly.
int findDigits(long long N){
int count = 0;
long long newN = N;
while(newN) // kinda like a right shift
{
int div = newN % 10;
if (div != 0)
if (N % div == 0) count++;
newN = newN / 10;
}
return count;
}

Related

Using Greatest Common Divisor for a ratio in Objective-C?

I would like to write a method in Objective-C that will result in a text string 'a:b:c:d'. I have four UISteppers (their values are displayed in a label each). I would like the ratio of those four numbers to display in their lowest integer form, including if some are 0.
Eg. a=6, b=4, c=0, d=0
Textstring = 3:2:0:0
I have found various ways of finding the greatest common divisor including http://macscripter.net/viewtopic.php?id=35759. However, I'm really new to iOS, this is my first app after Hello World, and the maths functions and even declaring a method, defining it and calling it are still a mystery.
Can you help out?
I settled for a method that takes the label values and alters the ratio label:
- (void)CalculateRatio {
int temp;
int PRBCs = [self.labelPRBCs.text integerValue];
int FFP = [self.labelFFP.text integerValue];
int u = PRBCs;
int v = FFP;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
int PRBCratio = PRBCs / u;
int FFPratio = FFP / u;
double Plateletratio = [self.labelPlatelets.text doubleValue] / u;
double Cryoratio = [self.labelCryo.text doubleValue] / u;
NSString *returnValue = [NSString stringWithFormat:#"%d : %d : %.1lf : %.1lf", PRBCratio, FFPratio, Plateletratio, Cryoratio];
self.calculatedRatio.text = returnValue;
}
If you can see some syntactical errors, ways to improve this, I'd be happy to hear them.
Cheers.

Getting a values most significant digit in Objective C

I currently have code in objective C that can pull out an integer's most significant digit value. My only question is if there is a better way to do it than with how I have provided below. It gets the job done, but it just feels like a cheap hack.
What the code does is that it takes a number passed in and loops through until that number has been successfully divided to a certain value. The reason I am doing this is for an educational app that splits a number up by it's value and shows the values added all together to produce the final output (1234 = 1000 + 200 + 30 + 4).
int test = 1;
int result = 0;
int value = 0;
do {
value = input / test;
result = test;
test = [[NSString stringWithFormat:#"%d0",test] intValue];
} while (value >= 10);
Any advice is always greatly appreciated.
Will this do the trick?
int sigDigit(int input)
{
int digits = (int) log10(input);
return input / pow(10, digits);
}
Basically it does the following:
Finds out the number of digits in input (log10(input)) and storing it in 'digits'.
divides input by 10 ^ digits.
You should now have the most significant number in digits.
EDIT: in case you need a function that get the integer value at a specific index, check this function out:
int digitAtIndex(int input, int index)
{
int trimmedLower = input / (pow(10, index)); // trim the lower half of the input
int trimmedUpper = trimmedLower % 10; // trim the upper half of the input
return trimmedUpper;
}

Objective-C Random int

Example, I have 2 ints and 1 output.
int IntNumberOne = 100;
int IntNumberTwo = 30;
NSLog(#"");
I would like the output to display just ONE of the two ints, and randomize every time this program is started.
How would that be done?
Use arc4random() function to pick number randomly:
NSLog(#"%d", arc4random()%2 ? IntNumberOne : IntNumberTwo);

Generate Random Numbers Between Two Numbers in Objective-C

I have two text boxes and user can input 2 positive integers (Using Objective-C). The goal is to return a random value between the two numbers.
I've used "man arc4random" and still can't quite wrap my head around it. I've came up with some code but it's buggy.
float lowerBound = lowerBoundNumber.text.floatValue;
float upperBound = upperBoundNumber.text.floatValue;
float rndValue;
//if lower bound is lowerbound < higherbound else switch the two around before randomizing.
if(lowerBound < upperBound)
{
rndValue = (((float)arc4random()/0x100000000)*((upperBound-lowerBound)+lowerBound));
}
else
{
rndValue = (((float)arc4random()/0x100000000)*((lowerBound-upperBound)+upperBound));
}
Right now if I put in the values 0 and 3 it seems to work just fine. However if I use the numbers 10 and 15 I can still get values as low as 1.0000000 or 2.000000 for "rndValue".
Do I need to elaborate my algorithm or do I need to change the way I use arc4random?
You could simply use integer values like this:
int lowerBound = ...
int upperBound = ...
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
Or if you mean you want to include float number between lowerBound and upperBound? If so please refer to this question: https://stackoverflow.com/a/4579457/1265516
The following code include the minimum AND MAXIMUM value as the random output number:
- (NSInteger)randomNumberBetween:(NSInteger)min maxNumber:(NSInteger)max
{
return min + arc4random_uniform((uint32_t)(max - min + 1));
}
Update:
I edited the answer by replacing arc4random() % upper_bound with arc4random_uniform(upper_bound) as #rmaddy suggested.
And here is the reference of arc4random_uniform for the details.
Update2:
I updated the answer by inserting a cast to uint32_t in arc4random_uniform() as #bicycle indicated.
-(int) generateRandomNumberWithlowerBound:(int)lowerBound
upperBound:(int)upperBound
{
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
return rndValue;
}
You should avoid clamping values with mod (%) if you can, because even if the pseudo-random number generator you're using (like arc4random) is good at providing uniformly distributed numbers in its full range, it may not provide uniformly distributed numbers within the restricted modulo range.
You also don't need to use a literal like 0x100000000 because there is a convenient constant available in stdint.h:
(float)arc4random() / UINT32_MAX
That will give you a random float in the interval [0,1]. Note that arc4random returns an integer in the interval [0, 2**32 - 1].
To move this into the interval you want, you just add your minimum value and multiply the random float by the size of your range:
lowerBound + ((float)arc4random() / UINT32_MAX) * (upperBound - lowerBound);
In the code you posted you're multiplying the random float by the whole mess (lowerBound + (upperBound - lowerBound)), which is actually just equal to upperBound. And that's why you're still getting results less than your intended lower bound.
Objective-C Function:
-(int)getRandomNumberBetween:(int)from to:(int)to
{
return (int)from + arc4random() % (to-from+1);
}
Swift:
func getRandomNumberBetween(_ from: Int, to: Int) -> Int
{
return Int(from) + arc4random() % (to - from + 1)
}
Call it anywhere by:
int OTP = [self getRandomNumberBetween:10 to:99];
NSLog(#"OTP IS %ld",(long)OTP);
NSLog(#"OTP IS %#",[NSString stringWithFormat #"%ld",(long)OTP]);
For Swift:
var OTP: Int = getRandomNumberBetween(10, to: 99)
In Swift:
let otp = Int(arc4random_uniform(6))
Try this.

Randomly pick between 2 defined ints

Is there a method in objective-c that allows you to pseudorandomly decide between two ints? Or is there a quick way to implement this?
Use the following:
int number = arc4random() % 2;
if(number==0){
//pick one number
}else{
//pick other number
}
randomSelection = arc4random() % 2 ? choice1 : choice2;
in C++ that would be result = rand() < 0.5 ? int1 : int2
why can't you build the same command in ObjC?