I have been learning Objective-C with the Kochan book and I can't figure out how to do this exercise program. Only odd numbered exercises are listed online and this one is even. The exercise is to convert numbers into words. So, if "932" was entered, the program should return: "nine three two"
I used a do, while loop but the words came out backwards, as in "two three nine". Can anyone suggest a technique that works for this?
int number, digit;
NSLog(#"Type in your integer.");
scanf("%i", &number);
do
{
digit = number % 10;
if (digit == 0)
NSLog(#"zero");
if (digit == 1)
NSLog(#"one");
if (digit == 2)
NSLog(#"two");
if (digit == 3)
NSLog(#"three");
if (digit == 4)
NSLog(#"four");
if (digit == 5)
NSLog(#"five");
if (digit == 6)
NSLog(#"six");
if (digit == 7)
NSLog(#"seven");
if (digit == 8)
NSLog(#"eight");
if (digit == 9)
NSLog(#"nine");
number /= 10;
}
while (number != 0);
This isn't exactly what you want, but for your consideration:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterSpellOutStyle];
NSString *s = [f stringFromNumber:[NSNumber numberWithInt:932]];
NSLog(#"%#", s);
[f release];
This will log:
nine hundred and thirty-two
Again, it's not the "nine three two" you want, but it's also nice and short. :)
Since you're adding the numbers to a string, and you want to calculate them right to left, prepend the string with each new number. Something like:
numberString = [NSString stringWithFormat:#"%# %#", theNewNumber, numberString];
Where theNewNumber is a string (like #"six") and numberString is the string that you want to output once you're done...
(oh, and don't forget to initialize numberString before you start looping...something like:
NSString *numberString = #"";
=====
Based on the code you just posted, you could either do it mathematically, or just pre-pend a string like this:
Put this variable in your .h file:
NSString *numberString;
Then put this in your .m:
- (void) prependNumber:(NSString *)num {
numberString = [NSString stringWithFormat:#"%# %#", num, numberString];
}
NSLog(#"Type in your integer.");
scanf("%i", &number);
numberString = #"";
do
{
digit = number % 10;
if (digit == 0)
[self prependNumber:#"zero"];
if (digit == 1)
[self prependNumber:#"one"];
if (digit == 2)
[self prependNumber:#"two"];
if (digit == 3)
[self prependNumber:#"three"];
if (digit == 4)
[self prependNumber:#"four"];
if (digit == 5)
[self prependNumber:#"five"];
if (digit == 6)
[self prependNumber:#"six"];
if (digit == 7)
[self prependNumber:#"seven"];
if (digit == 8)
[self prependNumber:#"eight"];
if (digit == 9)
[self prependNumber:#"nine"];
number /= 10;
}
while (number != 0);
NSLog (#"%#", numberString);
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int a, b, number, logNum, nThNum;
NSLog(#"Please enter a valid integer: ");
scanf("%d", &number); // read input as a decimal integer
if (!number) // if zero or something other than a number is entered output zero
NSLog(#"Zero");
else if (number < 0) { // convert negatives to something that can be used
number = -number;
NSLog(#"(negative)"); // but output negative first then continue as usual
}
logNum = (log10(number) + 1); // find how many digits there are in the number
for (int j=0; j < logNum; j++) {// loop based on number of digits
a = pow(10,logNum-j);
b = pow(10,logNum-1-j);
nThNum = (number % a) / b;// find the nth digit in a number, in our case 1st
switch (nThNum) {// output current digit that was found
case 0:
NSLog(#"Zero");
break;
case 1:
NSLog(#"One");
break;
case 2:
NSLog(#"Two");
break;
case 3:
NSLog(#"Three");
break;
case 4:
NSLog(#"Four");
break;
case 5:
NSLog(#"Five");
break;
case 6:
NSLog(#"Six");
break;
case 7:
NSLog(#"Seven");
break;
case 8:
NSLog(#"Eight");
break;
case 9:
NSLog(#"Nine");
break;
default:
break;
}
}
[pool drain];
return 0;
}
Well, now that you've posted your code, your method will work great if you first reverse the number. So, you can just write a short routine to do that, then use your own code.
Well it sounds like you're halfway there if you were able to get the numbers to convert to words already, even if output backwards.
Assuming you're looping through your data, incrementing the index, just start at the character length of the number, decrementing your index backwards, reversing your output.
We can't help you much more without seeing your actual code. ;)
As a learning exercise, I modified Dave's code:
+(NSString*)doIt:(NSString*)inString delimiter:(NSString*)delimiter{
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterSpellOutStyle];
NSMutableString* outString= [[NSMutableString alloc]init];
for (int i=0; i< [inString length]; i++) {
unsigned char oneChar= [inString characterAtIndex:i];
if (oneChar>47 && oneChar<58) {
NSString* temp=[f stringFromNumber:[NSNumber numberWithUnsignedChar:oneChar-48]];
[outString appendFormat:#"%#",temp];
[outString appendString:delimiter];
}
}
[f release];
[outString autorelease];
return outString;
}
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
// insert code here...
int number; //store the value the user enter
int lastDigit; //pick of the last digit of the integer
int tempNum; //a temporary storage of the integer the user enter
int count = 0; //used to count how many digits were entered
int count2; //going to be use as a duplicate of count
NSLog(#"Enter an integer");
scanf("%i", &number);
tempNum = number;
//Loop to find out how many digits were entered
for (; number != 0; number /= 10) {
count +=1;
}
//Loop to convert the numbers into words
for (; count != 0; count -= 1) {
count2 = count; //set count2 to count so the for and while loop use them independently
number = tempNum; //restore the value entered by by the user to the number variable
//Loop to reverse the order of the last digit
while (count2 != 0) { //loops to the same number of counts to get the first digit
lastDigit = number % 10; //picks off the last value in the integer
number /= 10; //enables the loop to set the last value of the integer to zero
count2 -=1; //loops one less time to get the numbers from front to back
}
//switch statements
switch (lastDigit) {
case 9:
NSLog(#"nine");
break;
case 8:
NSLog(#"eight");
break;
case 7:
NSLog(#"seven");
break;
case 6:
NSLog(#"six");
break;
case 5:
NSLog(#"five");
break;
case 4:
NSLog(#"four");
break;
case 3:
NSLog(#"three");
break;
case 2:
NSLog(#"two");
break;
case 1:
NSLog(#"one");
break;
case 0:
NSLog(#"zero");
break;
default:
break;
}
}
}
return 0;
}
I use nested under nested loop but believe that this works
int i, j, number, reversenumber = 0;
NSLog(#" Input Number:");
scanf( "%i", &number);
if (number != 0)
// chekcing for zero entry
{
for (;number!= 0; number = number/10)
//for reversing the number entered so that the words doesn't come reversed when printed
{
i = number%10;
reversenumber = reversenumber * 10 + i;
}
NSLog(#"Reverser Number for the input number is %i", reversenumber);
// mid routine check to print the reversed number
while(reversenumber != 0)
{
j = reversenumber % 10;
switch (j)
{
case 9:
NSLog(#"nine");
break;
case 8:
NSLog(#"eight");
break;
case 7:
NSLog(#"seven");
break;
case 6:
NSLog(#"six");
break;
case 5:
NSLog(#"five");
break;
case 4:
NSLog(#"four");
break;
case 3:
NSLog(#"three");
break;
case 2:
NSLog(#"two");
break;
case 1:
NSLog(#"one");
break;
default:
NSLog(#"zero");
}
reversenumber /= 10;
}
}
else
NSLog(#"Zero");
}
return 0;
}
very easy, there are number of approaches but i normally try this :
do
{
digit = number % 10;
switch (digit) {
case 0:
[self prependNumber:#"zero"];
break;
case 1:
[self prependNumber:#"one"];
break;
case 2:
[self prependNumber:#"two"];
break;
case 3:
[self prependNumber:#"three"];
break;
case 4:
[self prependNumber:#"four"];
break;
case 5:
[self prependNumber:#"five"];
break;
case 6:
[self prependNumber:#"six"];
break;
case 7:
[self prependNumber:#"seven"];
break;
case 8:
[self prependNumber:#"eight"];
break;
case 9:
[self prependNumber:#"nine"];
break;
default:
break;
}
number /= 10;
}
while (number != 0);
/************/
-(void) prependNumber:(NSString*)str{
NSLog(str);
}
Related
I have the following code working correctly in my game project where a ball is randomly shown to the player.
int random = arc4random_uniform(5);
switch (random)
{
case 0:
{
NSLog(#"Case 0 Ball");
}
break;
case 1:
{
NSLog(#"Case 1 Big Ball");
break;
}
case 2:
{
NSLog(#"Case 2 Center Ball");
break;
}
case 3:
{
NSLog(#"Case 3 Red Ball");
break;
}
case 4:
{
NSLog(#"Case 4 Blue Ball");
break;
}
}
What I would like to do is limit the number of potential balls shown to the player until the player achieves a certain level. I think the simplest way to do this is with just changing the number of random cases. So for instance...
int random = arc4random_uniform(1);
int random = arc4random_uniform(2);
int random = arc4random_uniform(3);
int random = arc4random_uniform(4);
int random = arc4random_uniform(5);
Of course the problem is when I try to wrap those options in the if statement below, it separates it from the Switch, which won't work.
int unlockBallLevel = [_levels getCurrentLevel];
if (unlockBallLevel > 5) {
int random = arc4random_uniform(5);
}
I'm wondering what would be the most logical and efficient way to limit the number of balls until a certain level is reached?
Perhaps:
switch (arc4random_uniform([_levels getCurrentLevel] < 5 ?: 5))
{
...
}
I solved the problem. I still don't know if there is a more efficient way to doing this, but the following code works and unlocks more balls as the player levels up through level 75. After level 75, all five balls are unlocked.
int unlockAtLevel = [_levels getCurrentLevel];
if (unlockAtLevel >= 1)
{
ballsForRandom = 1;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
if (unlockAtLevel >= 10)
{
ballsForRandom = 2;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
if (unlockAtLevel >= 30)
{
ballsForRandom = 3;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
if (unlockAtLevel >= 50)
{
ballsForRandom = 4;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
if (unlockAtLevel >= 75)
{
ballsForRandom = 5;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
int random = arc4random_uniform(ballsForRandom);
switch (random)
{
case 0:
{
NSLog(#"Case 0 Ball");
}
break;
case 1:
{
NSLog(#"Case 1 Big Ball");
break;
}
case 2:
{
NSLog(#"Case 2 Center Ball");
break;
}
case 3:
{
NSLog(#"Case 3 Red Ball");
break;
}
case 4:
{
NSLog(#"Case 4 Blue Ball");
break;
}
}
Based on #CRD's comments, I made the following changes to the code. The code below seems like a much more efficient and smarter implementation over the last answer posted.
int unlockAtLevel = [_levels getCurrentLevel];
if (unlockAtLevel >= 25)
{
ballsForRandom = 6;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
} else if (unlockAtLevel >= 20)
{
ballsForRandom = 5;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
} else if (unlockAtLevel >= 15)
{
ballsForRandom = 4;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
} else if (unlockAtLevel >= 10)
{
ballsForRandom = 3;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
} else if (unlockAtLevel >= 3)
{
ballsForRandom = 2;
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
} else if (unlockAtLevel >= 1)
{
ballsForRandom = 1;
[[GCHelper defaultHelper]reportAchievementIdentifier:achievementID1 percentComplete:100];
NSLog(#"\n\nLevel %i reached! There are now %i main balls unlocked!\n\n",unlockAtLevel,ballsForRandom);
}
NSLog(#"\n\n###############################################################\n\nCurrently the player is on level %i so there should be %i main balls unlocked!\n\n###############################################################\n\n",unlockAtLevel,ballsForRandom);
int random = arc4random_uniform(ballsForRandom);
switch (random)
I am new beginner in iOS, i want to remove if else condition and use proper code for this following code ..
can anyone help me for this ?
I have to Many condition
if (B == 99)
{
B = 11;
[Search_color addObject:Z];
}else if(B == 4)
{
B = 1;
[Search_color addObject:D];
}else if (B == 5)
{
B = 2;
[Search_color addObject:E];
}else if (A == 14)
{
B = 11; A = 10;
[Search_color addObject:N];
[Search_color addObject:Z];
}
else if (B == 26)
{
B = 11;
[Search_color addObject:Z];
}
can use switch with same result :
switch (B) {
case 99:
B = 11;
//[Search_color addObject:Z];
break;
case 4:
B = 1;
//[Search_color addObject:D];
break;
case 5:
B = 2;
//[Search_color addObject:E];
break;
case 26:
if (A != 14) {
B = 11;
//[Search_color addObject:Z];
break;
}
default:
if (A == 14) {
B = 11; A = 10;
//[Search_color addObject:N];
//[Search_color addObject:Z];
}
break;
}
Code use switch in function
- (void)yourFunction
{
NSInteger B, A;
B = 99;
switch (B) {
case 99:
B = 11;
//[Search_color addObject:Z];
break;
case 4:
B = 1;
//[Search_color addObject:D];
break;
case 5:
B = 2;
//[Search_color addObject:E];
break;
case 26:
if (A != 14) {
B = 11;
//[Search_color addObject:Z];
break;
}
default:
if (A == 14) {
B = 11; A = 10;
//[Search_color addObject:N];
//[Search_color addObject:Z];
}
break;
}
NSLog(#"B = %ld", B);
}
output: B = 11.
I'm trying to do a camera calibration using cvCalibrateCamera2() but run into a strage problem: the returned intrinsic_matrix and distortion_coeffs contain invalid floats (=NaN).
That's what I'm doing (the break's are responsible for leaving this completely):
image_points =cvCreateMat(board_total,2,CV_32FC1); if (!image_points) break;
object_points =cvCreateMat(board_total,3,CV_32FC1); if (!object_points) break;
point_counts =cvCreateMat(1,1,CV_32SC1); if (!point_counts) break;
intrinsic_matrix =cvCreateMat(3,3,CV_32FC1); if (!intrinsic_matrix) break;
corners =new CvPoint2D32f[board_total]; if (!corners) break;
distortion_coeffs=cvCreateMat(4,1,CV_32FC1); if (!distortion_coeffs) break;
int found = cvFindChessboardCorners(gray_image, board_sz, corners,corner_count,CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS );
if (found==0) break;
It woks fine until here, "gray_image" is my input image and "corners" contains the correct chessboard corner coordinates
cvFindCornerSubPix(gray_image, corners,*corner_count, cvSize(11,11),cvSize(-1,-1), cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 ));
for (j=0; j<board_total; j++)
{
CV_MAT_ELEM(*image_points, float,0,0) = corners[j].x;
CV_MAT_ELEM(*image_points, float,0,1) = corners[j].y;
CV_MAT_ELEM(*object_points,float,0,0) = (float) j/board_w;
CV_MAT_ELEM(*object_points,float,0,1) = (float) (j%board_w);
CV_MAT_ELEM(*object_points,float,0,2) = 0.0f;
}
CV_MAT_ELEM(*point_counts, int,0,0) = board_total;
CV_MAT_ELEM( *intrinsic_matrix, float, 0, 0 ) = 1.0f;
CV_MAT_ELEM( *intrinsic_matrix, float, 1, 1 ) = 1.0f;
cvCalibrateCamera2(object_points,image_points,point_counts,cvGetSize( gray_image ),intrinsic_matrix,distortion_coeffs,NULL,NULL,0);
Here cvCalibrateCamera2() seems to work and causes no exception but when I try to get the results out of it, all floats "d" are invalid:
float d;
for (i=0; i<3; i++)
for (j=0; j<3; j++)
{
d=CV_MAT_ELEM(*intrinsic_matrix,float,i,j);
calib_data->intrinsic[i][j]=(int)OAPC_ROUND(d*1000000,0);
}
for (i=0; i<4; i++)
{
d=CV_MAT_ELEM(*distortion_coeffs,float,i,0);
calib_data->distortion[i]=(int)OAPC_ROUND(d*100000000,0);
}
So what is wrong here?
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.
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);
}