Leak of Malloc 16 Bytes in C / Objective-C - objective-c

When I profile my code with Instruments, it shows a leak of Malloc 16 bytes from this function (below), but I never used malloc in this function. Is there a place in this function where I should free some resources?
It may look like a lot of code, but there is really only the variables counts and counts2 as possible offenders I think.
+ (int) trimArray: (NSMutableArray*) source above: (short) max andMin: (short) min
{
int counts[6][7];
int counts2[6][7];
for (int i=0;i<=5;i++)
{
for (int ii=0;ii<7;ii++)
{
counts[i][ii] = 0;
counts2[i][ii] = 0;
}
}
int capacity = (int)[source count]/max;
if (capacity <2)
capacity = 2;
NSMutableArray *itemsToRemove = [[NSMutableArray alloc] initWithCapacity:capacity];
int week,dow,count1,count2;
EntryTimeItem *item;
NSEnumerator *e;
e = [source objectEnumerator];
while (item = [e nextObject])
{
week = item.week_number;
dow = item.day_of_the_week;
if (week >=0 && week <6 && dow >=0 && dow <7)
{
counts[week][dow]++;
}
}
e = [source objectEnumerator];
while (item = [e nextObject])
{
week = item.week_number;
dow = item.day_of_the_week;
if (week >= 0 && week < 6 && dow >= 0 && dow < 7)
{
count2 = counts2[week][dow];
count1 = counts[week][dow];
if (count1 > max)
{
if (!count2)
{
item.time = -1;
item.align = NSCenterTextAlignment;
item.label = [NSString stringWithFormat:#"%d entries",count1];
}
else {
// remove this item if it is after the first item which
// was converted to a placeholder for all the items
[itemsToRemove addObject:item];
}
}
counts2[week][dow]++;
}
}
e = [itemsToRemove objectEnumerator];
while (item = [e nextObject])
{
[source removeObject:item];
}
int count_extra_events = 0;
for (int i=0;i<7;i++)
{
int count_events2 = 0;
for (int ii = 0; ii < 6; ii++)
{
int count3 = counts[ii][i];
if (count3 < max && count3 > min)
count_events2 += count3 - min;
}
// store the greatest value found sofar
if (count_events2 > count_extra_events)
{
count_extra_events = count_events2;
}
}
return count_extra_events;
}

The problem appears to stem from the line:
NSMutableArray *itemsToRemove = [[NSMutableArray alloc] initWithCapacity:capacity];
Please check if there is anyway, the resource itemsToRemove can be freed.

Related

Objective-C equal distribution from 5 different NSMutableArrays

This is my code but its still not correct. Currently i can distribute like this: 0,1,2,0,1,2,0,1,2 but i will distribute it 0,1,2,2,1,0,0,1,2,2 (0,1,2 are the groups)
//Create x Groups
for (int z=0; z<numberOfGroups; z++) {
mutableArrayOfSubarrays[z] = [NSMutableArray arrayWithCapacity:countOfElementsForTheGroups];
}
int nextSubarray = 0;
//Distribute the Objects into the groups
for (int i = 0; i < [AllObjectsToDistribute count]; i++)
{
[mutableArrayOfSubarrays[nextSubarray] addObject:[AllObjectsToDistribute objectAtIndex:i]];
nextSubarray = nextSubarray % customGroups;
nextSubarray++;
nextSubarray = nextSubarray % customGroups;
}
Keep track of which way the group index counts in a BOOL.
Example:
NSUInteger groupIndex = 0;
BOOL groupIndexCountsUp = YES;
for (id object in allObjectsToDistribute) {
[groupsArray[groupIndex] addObject:object];
if (groupIndexCountsUp) {
if (groupIndex < numberOfGroups - 1)
groupIndex++;
else
groupIndexCountsUp = NO;
}
else {
if (groupIndex > 0)
groupIndex--;
else
groupIndexCountsUp = YES;
}
}

myArray count isn't functioning as expected

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.

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])

Objective-C – Transform an array of numbers to arrays with numbers in sequence

Is there an easy way to transform an array of numbers to an arrays with the numbers in sequence?
NSArray *numbers = #[#1,#2,#5,#3];
// Transformed arrays
//NSArray *numbersInSequence = #[#1,#2,#3];
//NSArray *numbersInSequence2 = #[#5];
EDIT:
I modified the code in Richard's answer to get it to work.
NSArray *arraysBySplittingNumbersInOrder(NSArray *input) {
// sort 'input'
input = [input sortedArrayUsingSelector:#selector(compare:)];
NSMutableArray *results = [NSMutableArray array];
if (input.count) {
int start = 0;
int last = INT_MIN;
for (int i = 0; i < input.count; i++) {
BOOL lastItem = i == input.count - 1;
// The first item of the array
if (i == 0) {
if (lastItem) {
[results addObject:input];
break;
}
last = [input[i] intValue];
continue;
}
int cur = [input[i] intValue];
if (cur != last + 1) {
// pull out the next array
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
start = i;
}
// The last item of the array
if (lastItem) {
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start + 1)]];
}
last = cur;
}
}
return results;
}
Here's a rather simple solution:
NSArray *arraysBySplittingNumbersInOrder(NSArray *input)
{
// sort 'input'
input = [input sortedArrayUsingSelector:#selector(compare:)];
NSMutableArray *results = [NSMutableArray array];
if (input.count)
{
int start = 0;
int last = INT_MIN;
for (int i = 0; i <= input.count; i++)
{
if (i == 0)
{
last = [input[i] intValue];
continue;
}
if (i == input.count)
{
if (i != start + 1)
{
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
continue;
}
}
int cur = [input[i] intValue];
if (cur != last + 1)
{
// pull out the next array
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
start = i;
}
last = cur;
}
}
return results;
}
int main()
{
NSArray *input = #[ #1, #3, #4, #7, #8, #12, #13, #14 ];
NSLog(#"%#", input);
NSLog(#"%#", arraysBySplittingNumbersInOrder(input));
}
Output:
2012-11-27 07:55:04.609 TestProj[35890:303] (
1,
3,
4,
7,
8,
12,
13,
14
)
2012-11-27 07:55:04.611 TestProj[35890:303] (
(
1
),
(
3,
4
),
(
7,
8
),
(
12,
13,
14
)
)
I don't think there's an easy way to do this; you'll probably have to do at least part of the work yourself.
My suggestion would be to sort the array an then iterate through it, building the sections as you go. Whenever you hit a "jump", i.e. a non-consecutive number, this concludes your current section and starts a new one.