c style 2d array not retaining value between functions - ios

Ok so I'm creating a map using a c-style 2d array containing position structs:
typedef struct{
int x;
int y;
} posn;
I upload the values fine and print them out to make sure the values are correct. The 2d array is stored as an instance variable in my class.
In my next function I start by printing the array to make sure it's the same but it's not. The values are totally different and the array is even shortened. Can anyone tell me why I'm getting this issue. I'm using structs and c style arrays because I'm designing a game and I figured using them would be faster than NSMutableArray.
this is how I fill the array
mapa_camino = (posn *)malloc(w * h * sizeof(posn));
int i, j = 0;
for (i = 0; i < w; i++){
for (j = 0; j < h; j++){
SKNode *act;
act = [self.main_view nodeAtPoint:CGPointMake(i-algorimo_compensado.x, j-algorimo_compensado.y)];
if([act isKindOfClass:[BasicActor class]] && ![act isKindOfClass:[CMActor class]]){
//crea pt
posn pt = {.x = i,
.y = j,
.ocupado = YES,
.visitado = NO};
//fija posicion actual como pt
*(mapa_camino + i*h + j) = pt;
}else{
posn pt = {.x = i,
.y = j,
.ocupado = NO,
.visitado = NO};
*(mapa_camino + i*h + j) = pt;
}
}
}
this is how I print it:
- (NSMutableArray*) printtwodarray:(posn*)matriz{
int array_w = self.frame.size.width;
int array_h = self.frame.size.height;
NSMutableArray* regresa_matriz = [[NSMutableArray alloc] initWithCapacity:array_w];
for(int i=0;i<array_w;i++){
[regresa_matriz addObject:[[NSMutableArray alloc] initWithCapacity:array_h]];
for(int j=0;j<array_h;j++){
posn *pt = (matriz + i*array_h + j);
[[regresa_matriz objectAtIndex:i] insertObject:[[Posn alloc] initWithX:pt->x Y:pt->y H:pt->h G:pt->g Ocupado:pt->ocupado Goal:pt->is_goal] atIndex:j];
}
}
return regresa_matriz;
}

In order to store a 2D array in an instance variable from one function and use it in another function you need to declare the variable as an array, not as a pointer. Assignment would not work, so you would need to initialize the data with memcpy:
#interface Foo : NSObject {
posn p[20][30];
}
#end
...
-(void)bar {
posn d[20][30] = {{...}, {...},...,{...}};
memcpy(p, d, sizeof(p));
}

Related

Network Delay Problem - Complexity Analysis

Below is a solution Network delay problem of leetcode. I have written a all test case success solution. But not able to analyse the time complexity. I believe its O(V^2 + E) where V is the number of nodes and E edges.
In this solution though I am adding all adjacents of each node every time, but not processing them further if there exists a min distance for that node already.
Leetcode question link https://leetcode.com/problems/network-delay-time
public int networkDelayTime(int[][] times, int n, int k) {
int[] distances = new int[n+1];
Arrays.fill(distances , -1);
if(n > 0){
List<List<int[]>> edges = new ArrayList<List<int[]>>();
for(int i = 0 ; i <= n ; i++){
edges.add(new ArrayList<int[]>());
}
for(int[] time : times){
edges.get(time[0]).add(new int[]{time[1] , time[2]});
}
Queue<Vertex> queue = new LinkedList<>();
queue.add(new Vertex(k , 0));
while(!queue.isEmpty()){
Vertex cx = queue.poll();
int index = cx.index;
int distance = cx.distance;
//process adjacents only if distance is updated
if(distances[index] == -1 || distances[index] > distance){
distances[index] = distance;
List<int[]> adjacents = edges.get(index);
for(int[] adjacent : adjacents){
queue.add(new Vertex(adjacent[0] , adjacent[1]+distance));
}
}
}
}
int sum = 0;
for(int i = 1 ; i <= n; i++){
int distance = distances[i];
if(distance == -1){
return -1;
}
sum = Math.max(sum , distance);
}
return sum;
}
public static class Vertex{
int index;
int distance;
public Vertex(int i , int d){
index = i;
distance = d;
}
}
You should use PriorityQueue instead of LinkedList

In Objective C, How to do Clustering with pagination using CATileLayer

I have one scenario as do cluster for the nearest CGPoint in UIView. So i have set of CGPoint NSArray, I trying to get the nearest value and do cluster but i could not get the logic :
// my code
//total CGpointArray ex: cgPointGroupArray, i try to get each obj closest obj
for (CGPoint firstObjOfCGPoint in cgPointGroupArray) {
for (CGPoint nextPoint in cgPointGroupArray) {
//ex: 30 -distance b/w two point
if (30>[self distanceBetween: firstObjOfCGPoint and:nextPoint]){
[shortestClusterArr addObject:nextPoint];
}
else{
[longestClusterArr addObject:nextPoint];
}
}
//if array hold more than 2 value it will cluster otherwise mark single obj
if(shortestClusterArr.count>2){
//clustered marker obj
[self addClusterMarker:shortestClusterArr];
}
else{
//no cluster marker obj
}
}
Above code, looping time getting duplicate points as well override on the same object so if anyone knows the logic comment here,.. But I want such as clustering concepts like Geo-map clustering with pagination.
xTotalCount=pow( 2, self.mapScrollView.zoomLevel );
for ( int i = 0; i < xTotalCount ; i++) {
// ex : 0 < 2, it will execute 2 times depends on zoom level(pow(2,0),pow(2,1),pow(2,2),.. )
xISet = [[ NSMutableArray alloc ] init];
//set the cordination value to the a and b according to the zoom level
ax=( i*zoomLevelTicketSpacing ) / xTotalCount; // ex : a = 0
bx=((i + 1) *zoomLevelTicketSpacing ) / xTotalCount; // b = 256
for (EDCTicketMarker *ticketMarker in weakSelf.activeTicketMarkers) {
// group with zoom scale
nextPointX = ticketMarker.location.x;
if(nextPointX > ax && nextPointX < bx){
[xISet addObject:ticketMarker];
}
}
[xMatrixSet setValue:xISet forKey:[#(i)stringValue]];
// Y cordination ( 00, 01, 10, 11 )
yTotalCount=pow ( 2, self.mapScrollView.zoomLevel );
for (int j=0; j< yTotalCount ; j++) {
yISet = [[ NSMutableArray alloc ] init];
ay=( j*zoomLevelTicketSpacing ) / yTotalCount; // ex : a = 0
by=(( j+1 ) *zoomLevelTicketSpacing) / yTotalCount; // b = 256
for (EDCTicketMarker *ticketMarker in weakSelf.activeTicketMarkers) {
// group with zoom scale
nextPointY = ticketMarker.location.y;
if( nextPointY > ay && nextPointY < by ){
[yISet addObject:ticketMarker];
}
}
[yMatrixSet setValue:yISet forKey:[#(i)stringValue]];
// Intersect the X and Y matrix array
NSMutableSet *matrixSetX = [ NSMutableSet setWithArray:xISet ];
NSMutableSet *matrixSetY = [ NSMutableSet setWithArray:yISet ];
[matrixSetX intersectSet:matrixSetY];
NSArray *resultMatrix = [matrixSetX allObjects];
NSLog(resultMatrix) // it will print according to the x and y position (00,01,10,11)

EXC_BAD_ACCESS on double array

writing an objective c (with c low level functionality) function to detect pitch. Getting a EXC_BAD_ACCESS code=2 on the line "w[i] = i;" in the first for loop. In our iteration, numberofSamples = 32768. The Error occurs in the first loop after i = 16332. For some reason after filling about half of the array, the pointer is no longer valid. Single threaded app, nothing else should be messing around with stuff while this is running. I was wondering if there were any fundamental errors in this setup that could cause this pointer error. I can provide more detail as requested. Thanks!
NSArray* getMainFrequency(NSMutableArray *input,int numberOfSamples){
const int log2n = log(numberOfSamples)/log(2);
const int n = 1 << log2n;
const int nOver2 = n / 2;
int sFreq=44100;
double fFreq=0,maxMag=0,realFreq=0,t,alpha=0.6;
double mag[n/2+1],dblInput[numberOfSamples],w[numberOfSamples];
FFTSetupD fftSetup = vDSP_create_fftsetupD (log2n, kFFTRadix2);
for(int i=0;i<numberOfSamples;i++){
dblInput[i]=[input[i] doubleValue];
w[i] = i;
}
DSPDoubleSplitComplex fft_data;
fft_data.realp = malloc(nOver2 * sizeof(double));
fft_data.imagp = malloc(nOver2 * sizeof(double));
vDSP_ctozD((DSPDoubleComplex *)dblInput, 2, &fft_data, 1, nOver2);
vDSP_fft_zripD (fftSetup, &fft_data, 1, log2n, kFFTDirection_Forward);
for (int i = 0; i < nOver2; ++i){
fft_data.realp[i] *= 0.5;
fft_data.imagp[i] *= 0.5;
}
for (int i = 48; i < 2974; ++i){
mag[i]=pow((pow(fft_data.realp[i],2)+pow(fft_data.imagp[i],2)),0.5);
}
for(int i=48;i <= 2974;i++){ //to get a max of 4000 hZ hopefully?
if (mag[i]>maxMag){
maxMag = mag[i];
fFreq = i;
}
}
realFreq=fFreq/(numberOfSamples/2+1)*sFreq/2;
return [NSArray arrayWithObjects: #(maxMag),#(realFreq),nil];
}
}

How do I loop through NSString N number of times?

how do I loop the string 9 times ? (z x c v b n z x c)
NSString *fl = #"zxcvbn";
Here's a fast and dirty snippet:
NSString *string = #"abcdef";
NSString *letter = nil;
int n = 9;
for (int index = 0; index < n; index++) {
// start over if it's more than the length
int currentIndex = index % string.length;
letter = [string substringWithRange:NSMakeRange(currentIndex, 1)];
NSLog(#"letter: %#", letter);
}
If you want a low-level example with detailed explanation check this out.
In addition to using substringWithRange (which returns a NSString), you can also use characterAtIndex to get the character value:
NSInteger n = 9;
for (NSInteger index = 0; index < n; index++) {
unichar character = [fl characterAtIndex:index % fl.length];
// do something with `character`, e.g.
//
// if (character == 'z') { ... }
}

Line scanning openCV

below is a very simple code segment, but I am not able to understand why it is cribbing, can you please tell me what the error means:
CvSize iSize;
iSize= cvGetSize(I1);
CvLineIterator *iter ;
CvPoint p1,p2;
long *arrH = new long[iSize.height + 1];
long *arrV = new long [iSize.width + 1];
for( int i=0; i<=iSize.height;i++)
{
p1.y = i; p2.y=i;
p1.x = 0; p2.x=iSize.width;
arrH[i] =0;
int l = cvInitLineIterator(I1,p1,p2,iter,4,0);
for( int j=0;j<l;j++)
{
arrH[i]+=iter.ptr;
CV_NEXT_LINE_POINT(iter);
}
fprintf(f1,"%d \n",arrH[i]);
}
Errors of the form:
left of '.ptr' must have class/struct/union
how do I tackle them ?
I think this:
CvLineIterator *iter ;
Should be:
CvLineIterator iter ;
And this:
cvInitLineIterator(I1,p1,p2,iter,4,0);
Should be:
cvInitLineIterator(I1,p1,p2,&iter,4,0);

Resources