myArray count isn't functioning as expected - objective-c

The arrayTwelveLEngth variable isn't working as expected. When I placed a breakpoint on the amount = 1; line above, I hovered over arrayTwelve, and found that it was empty with 0 elements. Immediately after, I then hovered about arrayTwelveLength, expecting to see 0, but instead it seems that the arrayTwelveLength had a value of 1876662112. I don't know how it got that value, and I need to solve that problem. What am I doing wrong?
NSMutableArray *redValues = [NSMutableArray array];
NSMutableArray *arrayTwelve = [NSMutableArray array];
__block int counter = 0;
__block NSInteger u;
NSUInteger redValuesLength = [redValues count];
__block int arrayTwelveLength = 0;
__block float diffForAverage, fps, averageTime, bloodSpeed;
float average;
__block int amount = 1;
__block float totalTwelve, totalThirteen;
__block NSUInteger totalNumberOfFramesInSmallArrays = 0;
__block NSUInteger totalNumberOfFramesNotInSmallArrays;
for (u = (counter + 24); u < (redValuesLength - 24); u++)
{
diffForAverage = average - [redValues[u + 1] floatValue];
float test = [redValues[u] floatValue];
arrayTwelveLength = [arrayTwelve count];
if (diffForAverage > -1 && diffForAverage < 1)
{
totalTwelve += [redValues[u + 1] floatValue];
amount++;
[arrayTwelve addObject:#(test)];
counter++;
}
else
{
if (arrayTwelveLength >= 8)
{
counter++;
break;
}
else
{
[arrayTwelve removeAllObjects];
totalTwelve = [redValues[u + 1] floatValue];
counter++;
amount = 1;
}
}
}
amount = 1; // I added a breakpoint here
totalThirteen = [redValues[u + 1] floatValue];
average = totalThirteen / amount;
if (counter == redValuesLength)
{
totalNumberOfFramesNotInSmallArrays = redValuesLength - totalNumberOfFramesInSmallArrays - 25 - (redValuesLength - counter);
fps = redValuesLength / 30;
averageTime = totalNumberOfFramesNotInSmallArrays / fps;
bloodSpeed = 3 / averageTime;
[_BloodSpeedValue setText:[NSString stringWithFormat:#"%f", bloodSpeed]];
}
if (arrayTwelveLength == NULL)
{
arrayTwelveLength = 0;
}
totalNumberOfFramesInSmallArrays += arrayTwelveLength;

You have problems with unsigned/signed types and with your data set the first for loop should not even enter, because your for loop index variable u (== 24) < (redValuesLength (== 0) - 24) but, because redValuesLength being Unsigned type it wraps around and you get:
(unsigned long)0 - (unsigned long)24 = -24 modulo ULONG_MAX + 1= 18446744073709551592
Also, you are not initialising average before usage.

Related

Assigning to 'float' from incompatible type 'id'

The following error occurs on the two lines that are commented below:
Assigning to 'float' from incompatible type 'id'
NSMutableArray *redValues = [NSMutableArray array];
NSUInteger *redValuesLength = [redValues count];
NSMutableArray *arrayOne = [NSMutableArray array];
NSUInteger arrayOneLength = [arrayOne count];
__block int counter = 0;
int amount = 1;
float totalOne, diffForAverage;
NSInteger j;
totalOne = redValues[25]; // ERROR OCCURS HERE
float average = totalOne / amount;
for (j = (counter + 25); j < (redValuesLength - 25); j++)
{
diffForAverage = average - [redValues[j + 1] floatValue];
if (diffForAverage > -1 && diffForAverage < 1)
{
totalOne += [redValues[j + 1] floatValue];
amount++;
[arrayOne addObject:[NSNumber numberWithInt:(j - 25)]];
counter++;
}
else
{
if (arrayOneLength >= 15)
{
break;
counter++;
}
else
{
[arrayOne removeAllObjects];
totalOne = redValues[j + 1]; // ERROR OCCURS HERE
counter++;
}
}
}
Why is this error caused, and how can I fix it?
totalOne is float. And your array hold NSInteger. Change to that:
totalOne = [redValues[25] floatValue];

Code will never be executed warning

In my previous question, I asked why my application was terminating early. It turns out I'm getting this warning on one of the lines below and that may help me solve my problem.
Here's the code:
NSMutableArray *redValues = [NSMutableArray array];
NSUInteger redValuesLength = [redValues count];
float totalOne, diffForAverage;
int amount = 1;
__block int counter = 0;
NSInteger j;
GPUImageVideoCamera *videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
GPUImageAverageColor *averageColor = [[GPUImageAverageColor alloc] init];
[averageColor setColorAverageProcessingFinishedBlock:^(CGFloat redComponent, CGFloat greenComponent, CGFloat blueComponent, CGFloat alphaComponent, CMTime frameTime)
{
NSLog(#"%f", redComponent);
[redValues addObject:#(redComponent * 255)];
}];
[videoCamera addTarget:averageColor];
[videoCamera startCameraCapture];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 27 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[videoCamera stopCameraCapture];
});
totalOne = [redValues[25] floatValue];
float average = totalOne / amount;
for (j = (counter + 25); j < (redValuesLength - 25); j++)
{
diffForAverage = average - [redValues[j + 1] floatValue];
if (diffForAverage > -1 && diffForAverage < 1)
{
totalOne += [redValues[j + 1] floatValue];
amount++;
[arrayOne addObject:[NSNumber numberWithInt:(j - 25)]];
counter++;
}
else
{
if (arrayOneLength >= 15)
{
break;
counter++; // WARNING OCCURS HERE
}
else
{
[arrayOne removeAllObjects];
totalOne = [redValues[j + 1] floatValue];
counter++;
}
}
}
Why would the commented line above never be run? Is it a problem with my for loop, or my if statement, or something else entirely?
Because you have a break command just before it. The break command will immediately take you out of the for loop, so the next line won't be executed.

Find Max Difference in Array - Need Algorithm Solution Optimization [duplicate]

This question already has answers here:
optimal way to find sum(S) of all contiguous sub-array's max difference
(2 answers)
Closed 6 years ago.
I practised solving an algo on HackerRank - Max Difference.
Here's the problem given:
You are given an array with n elements: d[ 0 ], d[ 1 ], ..., d[n-1]. Calculate the sum(S) of all contiguous sub-array's max difference.
Formally:
S = sum{max{d[l,...,r]} - min{d[l, ..., r}},∀ 0 <= l <= r < n
Input format:
n
d[0] d[1] ... d[n-1]
Output format:
S
Sample Input:
4
1 3 2 4
Sample Output:
12
Explanation:
l = 0; r = 0;
array: [1]
sum = max([1]) - min([1]) = 0
l = 0; r = 1;
array: [1,3]
sum = max([1,3]) - min([1,3]) = 3 - 1 = 2
l = 0; r = 2;
array: [1,3,2]
sum = max([1,3,2]) - min([1,3,2]) = 3 - 1 = 2
l = 0;r = 3;
array: [1,3,2,4]
sum = max([1,3,2,4]) - min([1,3,2,4]) = 4 - 1 = 3
l = 1; r = 1 will result in zero
l = 1; r = 2;
array: [3,2]
sum = max([3,2]) - min([3,2]) = 3 - 2 = 1;
l = 1; r = 3;
array: [3,2,4]
sum = max ([3,2,4]) - min([3,2,4]) = 4 - 2 = 2;
l = 2; r = 2; will result in zero
l = 2; r = 3;
array:[2,4]
sum = max([2,4]) - min([2,4]) = 4 -2 = 2;
l = 3; r = 3 will result in zero;
Total sum = 12
Here's my solution:
-(NSNumber*)sum:(NSArray*) arr {
int diff = 0;
int curr_sum = diff;
int max_sum = curr_sum;
for(int i=0; i<arr.count; i++)
{
for(int j=i; j<=arr.count; j++) {
// Calculate current diff
if (!(j-i > 1)) {
continue;
}
NSArray *array = [arr subarrayWithRange:NSMakeRange(i, j-i)];
if (!array.count || array.count == 1) {
continue;
}
int xmax = -32000;
int xmin = 32000;
for (NSNumber *num in array) {
int x = num.intValue;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
}
diff = xmax-xmin;
// Calculate current sum
if (curr_sum > 0)
curr_sum += diff;
else
curr_sum = diff;
// Update max sum, if needed
if (curr_sum > max_sum)
max_sum = curr_sum;
}
}
return #(max_sum);
}
There were totally 10 test cases.
The above solution passed first 5 test cases, but didn't get passed through the other 5, which were failed due to time out (>=2s).
"Here's the Status: Terminated due to timeout".
Please help me on how this code can be further optimised.
Thanks!
Already there was an answer in Python. Here's the Objective C version from me:
#interface Stack : NSObject {
NSMutableArray* m_array;
int count;
}
- (void)push:(id)anObject;
- (id)pop;
- (id)prev_prev;
- (void)clear;
#property (nonatomic, readonly) NSMutableArray* m_array;
#property (nonatomic, readonly) int count;
#end
#implementation Stack
#synthesize m_array, count;
- (id)init
{
if( self=[super init] )
{
m_array = [[NSMutableArray alloc] init];
count = 0;
}
return self;
}
- (void)push:(id)anObject
{
[m_array addObject:anObject];
count = m_array.count;
}
- (id)pop
{
id obj = nil;
if(m_array.count > 0)
{
obj = [m_array lastObject];
[m_array removeLastObject];
count = m_array.count;
}
return obj;
}
- (id)prev_prev
{
id obj = nil;
if(m_array.count > 0)
{
obj = [m_array lastObject];
}
return obj;
}
- (void)clear
{
[m_array removeAllObjects];
count = 0;
}
#end
#interface SolutionClass:NSObject
/* method declaration */
-(NSNumber*)findDiff:(NSArray*) arr;
#end
#implementation SolutionClass
-(NSNumber*)findDiff:(NSArray*) arr {
NSNumber *maxims = [self sum:arr negative:NO];
NSNumber *minims = [self sum:arr negative:YES];
NSNumber *diff = #(maxims.longLongValue+minims.longLongValue);
NSLog(#"diff: %#", diff);
return diff;
}
-(NSNumber*)sum:(NSArray*) arr negative:(BOOL)negate {
Stack *stack = [Stack new];
[stack push:#{#(-1): [NSNull null]}];
long long sum = 0;
for(int i=0; i<arr.count; i++) {
NSNumber *num = arr[i];
if (negate) {
num = #(-num.longLongValue);
}
NSDictionary *prev = stack.m_array.lastObject;
NSNumber *prev_i = (NSNumber*)prev.allKeys[0];
NSNumber *prev_x = (NSNumber*)prev.allValues[0];
if ([self isNumber:prev_x]) {
while (num.longLongValue > prev_x.longLongValue) {
prev_i = (NSNumber*)prev.allKeys[0];
prev_x = (NSNumber*)prev.allValues[0];
prev = [stack pop];
NSDictionary *prev_prev_Dict = [stack prev_prev];
NSNumber *prev_prev_i = (NSNumber*)prev_prev_Dict.allKeys[0];
sum += prev_x.longLongValue * (i-prev_i.longLongValue) * (prev_i.longLongValue - prev_prev_i.longLongValue);
prev = stack.m_array.lastObject;
prev_x = (NSNumber*)prev.allValues[0];
if (![self isNumber:prev_x]) {
break;
}
}
}
[stack push:#{#(i): num}];
}
NSLog(#"Middle: sum: %lld", sum);
while (stack.count > 1) {
NSDictionary *prev = [stack pop];
NSDictionary *prev_prev_Dict = [stack prev_prev];
NSNumber *prev_i = (NSNumber*)prev.allKeys[0];
NSNumber *prev_x = (NSNumber*)prev.allValues[0];
NSNumber *prev_prev_i = (NSNumber*)prev_prev_Dict.allKeys[0];
sum += prev_x.longLongValue * (arr.count-prev_i.longLongValue) * (prev_i.longLongValue - prev_prev_i.longLongValue);
prev = stack.m_array.lastObject;
prev_x = (NSNumber*)prev.allValues[0];
if (![self isNumber:prev_x]) {
break;
}
}
NSLog(#"End: sum: %lld", sum);
return #(sum);
}
-(BOOL)isNumber:(id)obj {
if ([obj isKindOfClass:[NSNumber class]]) {
return 1;
}
return 0;
}
#end
The above solution works well for 7 test cases, but fails for the other 3 saying this: "Status: Wrong Answer". Hoping to find a fix for that too.
EDIT:
Have updated the WORKING code that passed all the test cases. Wrong data types were used before.

if statement comparring keep saying 4 is bigger than 5

I have an array that would has 0-49. When I compare acc_x[i] > acc_x[i-1], it would work for some value until it is comparing 5 and 4, then it say that 4 is bigger than 5 and go into the else statement. Please help.
int main(int argc, const char * argv[])
{
#autoreleasepool {
// insert code here...
//NSLog(#"Hello, World!");
//use velocity not acceleration. sorry for the naming. so run the velocity function for the array first that I wrote a already
NSMutableArray * acc_x = [NSMutableArray array];
NSNumber * temp = 0;
//the highest point or lowest point
NSNumber *highest =0;
NSNumber *lowest = 0;
int flag = 0;
//array for the highest and lowest point
NSMutableArray * array_lowest = [NSMutableArray array];
NSMutableArray * array_highest = [NSMutableArray array];
//array for the time when the highest and the lowest point
NSMutableArray * time_lowest = [NSMutableArray array];
NSMutableArray * time_highest = [NSMutableArray array];
double temp1 = 0;
NSNumber *temp2 = 0;
// the time variable is is just for temp variable. the real variable will be how long it take to have one measurement. i think it was like .001 or something like that but i don't remember. the time have to be in second if it is not in second the conver it.
double time = 0.1;
//trying to find the highest point or the lowest points in the graph from the acceleration
for (int i=0; i<50; i++)
{
//putting 0-49 into the array for testing
temp = [NSDecimalNumber numberWithDouble:i];
[acc_x addObject:temp];
if(i == 2) {
if (acc_x[i] > acc_x[i-1]) {
flag = 0;
}
if(acc_x[i] < acc_x[i-1]){
flag = 1;
}
NSLog(#"flag = %d",flag);
}
if(i>1) {
if(acc_x[i] > acc_x[i-1]) {
NSLog(#"x now is bigger then x past");
}
}
if(i >1) {
if(acc_x[i] > acc_x[i-1]) {
NSLog(#"x now is bigger then x pass");
}
NSLog(#"i = %d , i-1 = %d",i, i-1);
if (flag == 0) {
NSLog(#"flag is 0");
if(acc_x[i] > acc_x[i-1]) {
highest = acc_x[i];
}
else {
NSLog(#"flag going to turn into 1");
[array_highest addObject:highest];
flag = 1;
// calculate the time when the highest point is
temp1 = time * i;
temp2 = [NSNumber numberWithDouble:temp1];
[time_highest addObject:temp2];
}
}
if (flag ==1) {
NSLog(#"flag is 1");
}
}
}
// the size of the array
/* long size = [acc_x count];
for (int i =1; i<size-1; i++) {
NSLog(#"i = %d, flag = %d, array = %#, array[i-1] = %#",i,flag,acc_x[i],acc_x[i-1]);
if (flag == 1) {
if (acc_x[i] < acc_x[i-1]) {
lowest = acc_x[i];
}
if (acc_x[i] > acc_x[i-1]) {
flag = 0;
[array_lowest addObject:lowest];
// the temp1 is storing the time when this point got recorded
temp1 = time * i;
temp2 = [NSNumber numberWithDouble:temp1];
[time_lowest addObject:temp2];
}
}
if (flag == 0) {
if (acc_x[i] > acc_x[i-1]) {
highest = acc_x[i];
NSLog(#"x now is bigger than x-1");
//NSLog("highest = %d", highest);
}
if (acc_x[i] < acc_x[i-1]) {
NSLog(#"x now is less than x-1");
flag = 1;
[array_highest addObject:highest];
// the temp1 is storing the time when this point got recorded
temp1 = time * i;
temp2 = [NSNumber numberWithDouble:temp1];
[time_highest addObject:temp2];
}
}
}*/
//finding the period: time for 1 oscillation in second (remember that it is in second VERY IMPORTANT)
}
return 0;
}
You are comparing objects (NSNumber) instead of their numerical value.
do: if ([acc_x[i] intValue] > [acc_x[i-1] intValue])
instead of if (acc_x[i] > acc_x[i-1])

Why does my sorted array occasionally return random 0s at the end?

I wrote a program to sort a randomly generated array of 50 integers from greatest to least. So far it works, but it will occasionally return random zeros at the end of the sorted array. These zeros are not present in the unsorted array, and they do not always appear. Here's my program:
#import <Foundation/Foundation.h>
#interface Number: NSObject
- (void) start;
- (int) getValue;
- (void) counted;
- (void) placeValue: (int) a;
#end
#implementation Number
{
int x;
}
- (void) start
{
x = arc4random_uniform(1000);
if (x == 1)
{
x = x+1;
}
}
- (int) getValue
{
return x;
}
- (void) counted
{
x = 0;
}
- (void) placeValue: (int) a
{
x = a;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool
{
NSMutableArray *unsortedArray = [[NSMutableArray alloc] initWithCapacity: 50];
for (int n = 0; n < 50; n++)
{
Number *num = [[Number alloc] init];
[num start];
[unsortedArray addObject: num];
}
for (int n = 0; n < 50; n++)
{
printf("%i, ", [unsortedArray[n] getValue]);
}
printf ("unsorted array.\n\n");
int x = 0;
int y = 1001;
for (int n = 0; n < 50; n++)
{
for (int m = 0; m < 50; m++)
{
if (([unsortedArray[m] getValue] > x) && ([unsortedArray[m] getValue] < y))
{
x = [unsortedArray[m] getValue];
}
}
printf("%i, ", x);
y = x;
x = 0;
}
printf("sorted array.\n");
} return 0;
}
Try this:
- (void)start
{
x = (arc4random_uniform(1000) + 1);
}
You don't want to only be increasing x when you hit 0 or 1, since that will skew the results. arc4random_uniform will return a random number less than 1000 in this case, so 0 -> 999, adding 1 to all values, gives you 1 -> 1000. Adjust your numbers to suit what you need.
There are other issues in your code though. Why create your own Number class? Why create your own sort method? Use NSNumber and NSArray's sort methods.
Here is a much cleaner version:
int main(int argc, const char * argv[])
{
#autoreleasepool
{
NSMutableArray* unsortedArray = [[NSMutableArray alloc] initWithCapacity:50];
for (NSUInteger n = 0; n < 50; ++n) {
[unsortedArray addObject:#(arc4random_uniform(999) + 1)];
}
for (NSUInteger n = 0; n < 50; ++n) {
printf("%li, ", (long)[unsortedArray[n] integerValue]);
}
printf ("unsorted array.\n\n");
NSArray* sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
for (NSUInteger n = 0; n < 50; ++n) {
printf("%li, ", (long)[sortedArray[n] integerValue]);
}
printf("sorted array.\n");
}
return 0;
}
- (void) start
{
x = arc4random_uniform(1000);
if (x == 0)
x = x + 1;
}
Everyone is focusing on the fact that arc4random_uniform can generate zero as an acceptable value (which is true), but there is another problem: Your sort algorithm is incorrect, as it will only work if the values in the array are unique. But, if you have any duplicate values (and there's no assurances that arc4random_uniform won't generate some duplicates), your algorithm will show only one of those values, and thus, by the time you get to the end, you'll see a bunch of extra zeros.
There are tons of different sorting algorithms, but it's probably easier to just avail yourself of one of the native NSMutableArray sort methods, which gets you out of the weeds of writing your own.