Issue with calculation - objective-c

Can anyone see if there's problem with the way i handle the calculation below? I seemed to be getting "You scored 0" at runtime even when the answer is actually correct.
- (void)countGain{
int gain = 0;
int percentage;
if ([answer objectForKey:#"1"] == [usrAnswer objectForKey:#"1"]) {
gain += 1;
}
percentage = (gain / 10) * 100;
NSString *scored = [[NSString alloc] initWithFormat:#"You scored %d",percentage];
score.text = scored;
rangenans.text = [answer objectForKey:#"1"];
[scored release];
}

What is the point doing:
percentage = (gain / 10) * 100;
Use
percentage = gain * 10;
Rest looks good. You shouldn't divide integers. What if you get 3/10 and this is int value?
In condition change
if([answer objectForKey:#"1"] == [usrAnswer objectForKey:#"1"])
To:
if([[answer objectForKey:#"1"] isEqualToString:[usrAnswer objectForKey:#"1"]])

This is integer arithmetic. Try:
percentage = gain * 10;
or
percentage = (gain * 10 ) / 100;
or
percentage = ((float)gain / 10) * 100;
Note that in any of the above, you only have 10 options for the "percentage", so percentage = gain * 10; is the simpler.

The problem is that you are trying to compare NSStrings and == compares the assresses of strings. You want to compare their values
e.g.
NSString *correct = #"Yes";
NSString *answer = ..... from some entry;
Then these two NSStrings will point to different bits of memory.
to compre with the user replied you need to compare values using the isEqualToString: method
e.g.
gain += [correct isEqualToString:answer] ? 1 : 0;
In your code == failed each time so gain was always 0. So the int division problem never occureed - but it would have when gain became 1 etc.

Related

Creating a Balancing Class to Balance Weights

First of all I must admit that it is my assignment. But I am not asking anyone to solve it but I am working hard to solve it and need help with my algorithm.
I have an array of weights that is assigned to leftSide and rightSide of a scale. I need to balance the weights in right side and left side using the weights in the array.
I have the following code but it does not cover all the situations:
-(BOOL) isBalanced
{
_weights = [NSMutableArray arrayWithArray:#[#3,#4,#2,#1,#5,#6,#4]];
self.leftSide = [[_weights objectAtIndex:arc4random() % 7] integerValue]; // random weight
self.rightSide = [[_weights objectAtIndex:arc4random() % 7] integerValue]; // random weight
if(self.leftSide == self.rightSide) return YES; // already balanced
if(self.leftSide > self.rightSide)
{
// add weights on right side
int difference = self.leftSide - self.rightSide;
int index = [_weights indexOfObject:[NSNumber numberWithInt:difference]];
self.rightSide += [[_weights objectAtIndex:index] integerValue];
NSLog(#"%d",index);
}
else
{
int difference = self.rightSide - self.leftSide;
int index = [_weights indexOfObject:[NSNumber numberWithInt:difference]];
self.leftSide += [[_weights objectAtIndex:index] integerValue];
NSLog(#"%d",index);
}
return self.leftSide == self.rightSide;
}
UPDATE:
To simplify! I have a number 6 and now I need to search inside an array of ints if any of the numbers can be added together to get 6. Example:
1,2,3,5,4
In the above array I can take 1+2+3 which makes 6. I can also take 4+2 which is 6. The question is how do I find those individual numbers that can sum up to the number 6.

2 text fields to always equal 100 percent xcode

I have two text fields that are for percentages to be entered in. If i put 20 in the first field I would like the second text field to be updated to 60. And later on if I changed the second one to say 30, I would like the first updated to 70.
For ease of showing what I mean, say I have two text fields _firstPercent and _secondPercent with associated labels _firstTotal and _secondTotal:
float firstPercent = [_firstPercent.text floatValue];
float firstAmount = (firstSalePercent / 100) * firstOrigonalAmount;
_firstTotal.text = [NSString stringWithFormat:#"%1.0f",firstAmount];
float secondPercent = [_secondPercent.text floatValue];
float secondAmount = (secondSalePercent / 100) * secondOrigonalAmount;
_secondTotal.text = [NSString stringWithFormat:#"%1.0f",secondAmount];
I really don't know how to handle this so I tried adding this below its respective code. It works for the first one, but not the second.
float percentToSecond = 100 - firstPercent;
_secondPercent.text = [NSString stringWithFormat:#"%1.0f", percentToSecond];
float percentToFirst = 100 - secondPercent;
_firstPercent.text = [NSString stringWithFormat:#"%1.0f", percentToFirst];
I have tried other solutions but don't know what to do.
I would just like someone to lead me in the right direction.
Thanks
How about using the delegate method controlTextDidEndEditing: to see what value was entered, and then set the value for the other text field. In the following code tf1 and tf2 are the IBOutlets for the two text fields.
-(void)controlTextDidEndEditing:(NSNotification *)obj {
float value = [[[obj.userInfo valueForKey:#"NSFieldEditor"] string] floatValue];
if (obj.object == self.tf1) {
self.tf2.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}else if (obj.object == self.tf2) {
self.tf1.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}
}
You'd have to do some more checking to make sure the user didn't enter a number greater than 100 or something not a number.

NSNumber and decimal value

I have an NSNumber like this for example = 1978, i would like to convert this for : 1K9, seconde example : 35700 convert to : 35K7 ( where "k" is kilometers and "M" is meters, how i can do this
thanks
int temp;
NSNumber *yourNumber;//the number you enter from some where
NSString *newValue;
if([yourNumber intValue]>1000){
temp = [yourNumber intValue] % 1000 ;//your number module 1000
newValue= [[temp stringValue]stringByAppendingString:#"K"];
}
Note: I haven't my mac with me, if the [temp stringValue] gives any worning&error please inform me.
Here's how:
NSNumber *initialNumber = [NSNumber numberWithInt:35700];
NSString *resultString = [NSString stringWithFormat:#"%iK%i", floor(initialNumber / 1000), floor((initialNumber % 1000) / 100)];
Basically you can work with the internal number data.
Assuming you are working on a meter-based value, you might want something like this:
NSNumber *sourceValue = ... // your NSNumber value from any source
int meters = sourceValue.intValue;
int km = floor(meters / 1000); // only your kilometers
int sub_km = meters % 1000; // only the part behind the kilometers
int first_sub_km = floor(sum_km / 100); // the first digit of the subrange
NSString *readable = [NSString stringWithFormat:#"%iK%i", km, first_sub_km];
First, you split the meters into <= 1000 and > 1000.
Then you'll just have to put that out formatted, with a K in between.
Write your own subclass of NSNumberFormatter. In this subclass you can implement the calculation logic.
The logic might look like this.
Devide the value by thousend and add your "k"
if you want to have the first digit of hundreds get the thired last digit of your value
return the new string

Trying to make my objective-c program more efficient; Beginner

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, right_digit;
NSLog(#"Enter your number.");
scanf("%i", &number);
while (number != 0) {
right_digit = number % 10;
if (right_digit <0 && number <10 && number>-10) {
right_digit = -right_digit;
NSLog(#"%i- ", right_digit);
}
else if (right_digit<0) {
right_digit = -right_digit;
NSLog(#"%i", right_digit);
}
else {
NSLog(#"%i", right_digit);
}
number /=10;
}
[pool drain];
return 0;
}
The aforementioned code works insofar as finding the reverse of a number, both negative and positive. If negative, say for example, -1234, the answer is supposed to read 4321-. I have no problems there. I am just learning Objective-C so I understand if this is a basic question and my code is very basic. The problem is I have some repeating code and I'm sure there is a better way to write this. I just wanted to know if someone could give me any insight.
I'd do it this way:
NSInteger number = -12;
NSUInteger inverse = 0;
NSInteger sign = (number >= 0) ? 1 : -1;
number = number * sign;
while (number > 0)
{
inverse = inverse * 10 + (number % 10);
number = number / 10;
}
NSLog(#"%i%#", inverse, (sign == -1) ? #"-" : #"");
Without critiquing the details of the algorithm (I might have done it differently, and I haven't evaluated it for correctness/robustness) I can't see anything that would be regarded as "inefficient".
Necessarily you're going to have to iterate through each digit, and you don't appear to iterate more than necessary. The logic is all (save for the actual output) "scalar" (not-object) integer values, so no unnecessary object creation. At most you might be able to eliminate one or two of the tests in your if statements, but there's little efficiency gain there. And I can't see how using any Cocoa classes might have made it simpler.

Odd behavior with NSUInteger - can't convert to float properly

Here is my situation. Its driving me nuts:
I have an NSMutableArray with a count value of 517. I have a double value that is my multiplier.
double multiplier = 0.1223;
double result = [myArray count] * multiplier; // 63 even (wrong!)
In fact it should be 63.2291. If I go:
double result = [myArray count] * 0.1223; // 63.2291 (right!)
or..
double result = 517 * multiplier; // 63.2291 (right!)
Does this make any sense to anyone?
Addendum:
here is my actual function:
- (double) getValueForPercentage:(double)percVal
{
int adjustedCount = [originalData count] - 1;
double final = percVal * (double)adjustedCount;
return final;
}
I never get any digits beyond the decimal point when I do this. It does however work if I get rid of the "-1", a-la:
- (double) getValueForPercentage:(double)percVal
{
int adjustedCount = [originalData count];
double final = percVal * (double)adjustedCount;
return final;
}
Of course, I need to have the -1.
Second addendum:
Another interesting thing I noted was, if I pass a hard-coded number to this function it works fine, but if I pass the double value that I need to use, it fails:
int pointCount = [srcData getDayCount];
for (int i = 0; i < pointCount; i++) {
double progress = (double)i/(double)(pointCount - 1);
double satv = [srcData getValueForPercentage:progress];
// satv is always a number without any digits beyond the decimal
}
Well, when I started to have these issues i looked around a bit and found no reason or explanation.
What I do now is make everything become an NSNumber and then call doubleValue on it. This should yield the results you're looking for:
NSNumber * pointCount = [NSNumber numberWithUnsignedInt: [srcData getDayCount]];
for (NSInteger i = 0; i < [pointCount intValue]; i++) {
NSNumber * count = [ NSNumber numberWithInt: i ];
double progress = [count doubleValue]/[pointCount doubleValue] - 1.0;
double satv = [srcData getValueForPercentage:progress];
// satv is always a number without any digits beyond the decimal
}
Hope it helps.