iOS : round off to nearest number - ios

Lets say I've following NSInteger's :
111
246
99
82
92
85
Is there a function which converts (round off) like these numbers like :
110
250
100
80
90
85

Looking at your requested result, numbers less than 100 are rounded to the nearest 5, and those over rounded to the nearest 10. By doing this, you can get the desired result
- (NSInteger)roundToNearest:(NSInteger)inputNum
{
if (inputNum < 100){
return roundf(inputNum / 5.0f) * 5;
}
else {
return roundf(inputNum / 10.0f) * 10;
}
}

// This Generic function can solve the purpose you can modify it according to your requirement.
- (NSInteger)roundOffNumberToNearestCompleteNo:(NSInteger)number
{
if(number <= 0)
return 0;
NSString *strNumber = [NSString stringWithFormat:#"%ld",number];
NSInteger digitCount = [strNumber length];
if(digitCount == 1)
{
if(number <= 5)
{
return 1;
}
else
{
return 10;
}
}
NSString *strNumberUnit = #"1";
for(int i = 1; i < digitCount; i++)
{
strNumberUnit = [strNumberUnit stringByAppendingString:#"0"];
}
NSInteger numberUnit = [strNumberUnit integerValue];
NSInteger reminder = number%numberUnit;
if(reminder <= (numberUnit/2))
{
number = number - reminder;
}
else
{
number = number + (numberUnit - reminder);
}
return number;
}

You should use
- (NSInteger)roundFive:(NSInteger)number
{
return roundf(number/5.)*5;
}

Why not use a more generic and thus reusable method? This seems to work for all valid NSIntegers including negative numbers and checks for div0 but someone let me know if they spot a flaw:
- (NSInteger)roundInteger:(NSInteger)num toNearestInteger:(NSInteger)roundTo
{
if (!roundTo) { return 0; }
return (roundTo * round((float)num / roundTo));
}

Probably easier to implement it yourself:
- (NSInteger)roundOff:(NSInteger)number
{
NSInteger remainder = number % 5;
NSInteger quotient = number / 5;
if (remainder > 0) {
return (quotient + 1) * 5;
}
else {
return quotient * 5;
}
}

Related

How to create random numbers for multiple images to show randomly in Grid without repetition in iOS?

I create GridView in SpriteKit.my requirement is to shuffle images randomly in Grid View.
Here is my code to show images randomly without repetition.but this code is working for only two images.for multiple images this code is not working.
int RandomRowMainImage = arc4random_uniform(3);
int RandomColumnMainImage = arc4random_uniform(3);
//
int RandomRowOtherImage = arc4random_uniform(3);
int RandomColumnOtherImage = arc4random_uniform(3);
NSLog(#"RandomRowMain:%d \n Random Column :%d \n RandomRow1:%d \n randomColumn1 :%d",RandomRowMainImage,RandomColumnMainImage,RandomRowOtherImage,RandomColumnOtherImage);
//
BOOL checkStatus = [self checkRandomNumberColumRowLogic:RandomRowMainImage withMainRow:RandomColumnMainImage withOtherColumn:RandomColumnOtherImage withOtherRow:RandomRowOtherImage];
if (checkStatus) {
imgIcons.position = [self GridPosition:MainRowCount Column:MainColumnCount];
imgOtherImage.position = [self GridPosition:otherRowCount Column:otherColumnCount];
}
than Code for Position of Images
//Grid Position
-(CGPoint)GridPosition:(int)Row Column:(int)Column
{
CGFloat offset = SizeOfGrid / 2.0 + 0.5;
CGFloat x = Column * SizeOfGrid - (SizeOfGrid*TotalCol)/2.0 + offset;
CGFloat y = (TotalRows-Row-1) * SizeOfGrid -(SizeOfGrid*TotalRows)/2.0 + offset;
return CGPointMake(x, y);}
//Code to check prevent duplication of repeat random number for Two Images.
- (BOOL)checkRandomNumberColumRowLogic:(int)MainColumn withMainRow:(int)mainRow withOtherColumn:(int)otherColumn withOtherRow:(int)otherRow {
BOOL CompareRow = false;
BOOL CompareColumn = false;
if (mainRow == otherRow) {
int otherRow = 0;
for (int i = 0; i < TotalCol; i++ ) {
otherRow = [self checkRandomNumberCompare:otherRow];
if (MainColumn == otherRow) {
CompareRow = true;
break;
}
}
MainColumnCount = mainRow;
otherColumnCount = otherRow;
}
else {
CompareRow = true;
MainRowCount = mainRow;
otherRowCount = otherRow;
}
if (MainColumn == otherColumn) {
int otherCol = 0;
for (int i = 0; i < TotalCol; i++ ) {
otherCol = [self checkRandomNumberCompare:otherColumn];
if (MainColumn == otherCol) {
CompareColumn = true;
break;
}
}
MainColumnCount = MainColumn;
otherColumnCount = otherCol;
}
else {
CompareColumn = true;
MainColumnCount = MainColumn;
otherColumnCount = otherColumn;
}
if(CompareRow == CompareColumn) {
return true;
} else {
return false;
}
}
-(int)checkRandomNumberCompare:(int)compareRow {
int compareDiff = arc4random_uniform(TotalRows);
return compareDiff;
}
can you please help to display multiple images without repeat? like one time one image in Node
Sorry, but the logic of your checkRandomNumberColumRowLogic: method baffles me. Given two coordinates (x1, y1) and (x2, y2) then they represent the same point if and only if x1 == x2 and y1 == y2, and if this is not fall then they represent different points.
Here is the outline of a possible algorithm to solve your problem. First consider that given a rectangular grid of cells where the rows and columns are numbered starting from 0 then each cell can be assigned a unique number by multiplying its row index by the number of columns and adding in its column index. A diagram is worth a thousand words, given a 3 x 3 grid you get the numbering:
0 1 2
3 4 5
6 7 8
Note that given a cell number the row & column it represents can be calculated using integer division and remainder.
Doing the above reduces your problem to producing the numbers from 0 to rowCount x colCount - 1 in some random order.
There are a number of ways in which you can do this, here is one:
Set upperLimit to rowCount x colCount - 1
Generate a random number r between 0 and upperLimit
Check if cell r is occupied, if it is add 1 to r and repeat this step
Place next image into cell r
Subtract 1 from upperLimit and goto step 2 if the result is greater than 0 (of course "goto" here translates to a "while" in code)
They key to avoiding duplicates is step 3, and the algorithm guarantees that step 3 will always find an unoccupied cell – proving that is left as an exercise.
HTH
I'd agree with the answer above that your logic is overly complicated. If you give an index to each image as suggested, e.g. for a 3x4 grid:
0 1 2
3 4 5
6 7 8
9 10 11
You could then randomise the grid and exchange those images. The following code would achieve this:
-(void)createRandomGridArrays
{
NSInteger columnLength = 3;
NSInteger rowLength = 4;
// Create an array of NSNumbers up to the max then randomise
NSMutableArray *indexes = [NSMutableArray new];
for (NSInteger i=0; i<columnLength*rowLength; i++) {
[indexes addObject:#(i)];
}
NSArray *randomIndexes = [self shuffleArray:indexes];
NSLog(#"%# -> %#", indexes, randomIndexes);
// (0,1,2,3,4,5,6,7,8,9,10,11) -> (1,0,6,10,4,2,7,11,9,5,8,3)
// Convert indexes back to row/columns
for (NSNumber *randomIndex in randomIndexes) {
NSInteger index = [randomIndex integerValue];
NSInteger row = index % rowLength;
NSInteger column = index % columnLength;
NSLog(#"%ld row:%ld, column:%ld", index, row, column);
}
}
-(NSArray*)shuffleArray:(NSArray*)array
{
NSMutableArray *shuffledArray = [array mutableCopy];
for (NSInteger i=shuffledArray.count-1; i>0; i--) {
[shuffledArray exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
return shuffledArray;
}
If you had an NSMutableArray of images you would then just exchange the image at index with the image at [randomIndexes[index] integerValue].

Program wrongly states whether numbers are prime

I wrote this code to determine which numbers between two numbers someone types are prime and which are composite. The user types two numbers, e.g. 5 & 10, and in that case the program should output:
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
But it is not doing this correctly. For example, if the user enters 13 and 33, the output is that 13, 14, and 15 are prime, but all the other numbers are not. What's even more strange is that the results contradict each other. For example, if the user enters 10 and 20, the program outputs that all the numbers are not prime.
package more.basic.applications;
import java.util.Scanner;
public class MoreBasicApplications {
public static void main(String[] args)
{
//program to determine how many numbers between 2 numbers inclusive are prime, and how many are composite, as well as display them
int j = 2;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter number 1, between 0 and 100: ");
int number = reader.nextInt();
boolean composite = false;
System.out.println("Please enter number 2, between 0 and 200: ");
int number2 = reader.nextInt();
int difference = number2 - number;
int[] array = new int[difference+1];
for (int i = 0; i < array.length; i++)
{
array[i] = number + i;
while (j <= Math.sqrt(array[i]))
{
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.");
}
else
{
System.out.println (array[i] + " is prime.");
}
}
}
It looks like you don't "reset" j back to 2 at the beginning of your for loop, so j keeps getting bigger and bigger.
for (int i = 0; i < array.length; i++) {
j = 2; // reset j back to 2.
array[i] = number + i;
while (j <= Math.sqrt(array[i])) {
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.")
} else {
System.out.println (array[i] + " is prime.");
}
}

Calculate factorial of a decimal (i.e. Gamma function) on iOS

I need to calculate the factorial of a decimal number, say 6.4, on iOS. I tried
double myFactorial = gamma(6.4);
But get the error "'gamma is unavailable': not avaiable on iOS". Is there a way to add the gamma function into iOS?
Have you tried:
tgamma(6.4)
I see it working in my code.
There's also:
double tgamma (double x)
float tgammaf (float x)
long double tgammal (long double x)
you can try like this logic may be this will well you.
- (int)factorial:(int)operand
{
if`enter code here`(operand < 0)
return -1;
else if (operand > 1)
return operand * [self factorial:operand - 1];
else
return 1;
}
and then
- (double)factorial:(double)operand
{
double output = operand;
if (output == 0) output = 1; // factorial of 0 is 1
else if (output < 0) output = NAN;
else if (output > 0)
{
if (fmod(output, floor(output)) == 0) // integer
output = round(exp(lgamma(output + 1)));
else // natural number
output = exp(lgamma(output + 1));
}
return output;
}
- (double)n:(double)n chooseR:(double)r
{
return round(exp((lgamma(n+1)) - (lgamma(r+1) + lgamma(n-r+1))));
}
- (double)n:(double)n pickR:(double)r
{
return round(exp(lgamma(n+1) - lgamma(n-r+1)));
}

How do I randomize the questions pulled from my dictionary-plist

Hey Guys any ideas for randomising the questions that I pull from my -plist file?
-(NSUInteger)nextQuestionID:(NSUInteger)question_number{
return (question_number>=[self.questions count]-1) ? 0 : (question_number+1);
return 0;
}
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
return [self.questions objectAtIndex:question_number];
return NULL;
}
To get a random integer, I would suggest using arc4random function, here is some code to do this:
int randomInt = arc4random() % questionNumber;
return [self.questions objectAtIndex: randomInt];
You can use the arc4random_uniform(upper_bound) function. The parameter is the upper bound of your random number.
An example:
int index = arc4random_uniform([self.question count]);
question_number = arc4random() % self.questions.count;
set question number as random number
replace the function
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
question_number = arc4random()%[self.questions count];// changes made here
return [self.questions objectAtIndex:question_number];
return NULL;
}
the random integers:
srand(time(nil));
for (int i = 0; i < 100; i++) {
NSLog(#"random number between 72 and 96 : %d", rand() % (96 - 72) + 72);
}
UPDATE
and for your specific case:
- (NSUInteger)nextQuestionID {
srand(time(nil));
return rand() % [self.questions count];
}
- (NSDictionary*)getQuestion {
return [self.questions objectAtIndex:[self nextQuestionID]];
}
UPDATE#2
test the following loop two, three or more times and compare the outputs:
srand(time(nil));
for (int i = 0; i < 10; i++) {
NSLog(#"random number : %d", rand() % 89 + 10);
}
you should get 10 random numbers between 10 and 99, I've tested it on a real device, not on the simulator but it should work on the simulator as well.
if you get the same result always, let me know.

Generating 3 unique random numbers in Objective-C?

I'm trying to generate 3 random numbers between 0 to 25. I used arc4random_uniform(25) for this and it generate 3 random numbers.but problem is that some time I get two or even all three numbers are same, but I require 3 unique numbers.
As #Thilo said you have to check they are random and repeat if they are not:
// This assumes you don't want 0 picked
u_int32_t numbers[3] = { 0, 0, 0 };
for (unsigned i = 0; i < 3; i++)
{
BOOL found = NO;
u_int32_t number;
do
{
number = arc4random_uniform(25);
if (i > 0)
for (unsigned j = 0; j < i - 1 && !found; j++)
found = numbers[j] == number;
}
while (!found);
numbers[i] = number;
}
int checker[3];
for(int i = 0 ; i < 3 ; i++){
checker[i] = 0;
}
for(int i = 0 ; i < 3 ; i++){
random = arc4random() % 3;
while(checker[random] == 1){
random = arc4random() % 20;
}
checker[random] = 1;
NSLog(#"random number %d", random);
}
I am generating an Array of unique Random Number in the following way:
-(void)generateRandomUniqueNumberThree{
NSMutableArray *unqArray=[[NSMutableArray alloc] init];
int randNum = arc4random() % (25);
int counter=0;
while (counter<3) {
if (![unqArray containsObject:[NSNumber numberWithInt:randNum]]) {
[unqArray addObject:[NSNumber numberWithInt:randNum]];
counter++;
}else{
randNum = arc4random() % (25);
}
}
NSLog(#"UNIQUE ARRAY %#",unqArray);
}

Resources