File: DCHypergrid.m

package info (click to toggle)
gridlock.app 1.10-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,556 kB
  • sloc: objc: 10,334; ansic: 669; makefile: 12
file content (311 lines) | stat: -rw-r--r-- 10,117 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#import "DCHypergrid.h"
#import "DCHypergridPositionEnumerator.h"
#import "CocoaAdditions.h"

@implementation DCHypergrid

-(id)initWithNumberOfDimensions:(int)numdim sizes:(int *)sizes {
  self = [super init];
  if (self) {
    _cgrid = hypergrid_create(numdim, sizes);
  }
  return self;
}

-(id)initWithCHypergrid:(hypergrid *)gridptr {
  self = [super init];
  if (self) {
    _cgrid = hypergrid_copy(gridptr);
  }
  return self;
}

-(id)copy {
  return [[DCHypergrid alloc] initWithCHypergrid:_cgrid];
}

-(void)copyValuesToGrid:(DCHypergrid *)gridCopy {
  memcpy([gridCopy cHypergrid]->grid_data, [self cHypergrid]->grid_data, [self numberOfCells]*sizeof(gridvalue_t));
}

-(int)numberOfDimensions {
  return _cgrid->num_dimensions;
}

-(int)numberOfCells {
  return _cgrid->num_cells;
}

-(gridvalue_t)valueAtPosition:(DCHypergridPosition *)coords {
  // optimization for 2 dimensions, used in Gridlock to optimize game evaluations
  if (_cgrid->num_dimensions==2) {
    int index = coords->_data[0]*_cgrid->dimension_sizes[1] + coords->_data[1];
    return _cgrid->grid_data[index];
  }
  return hypergrid_get_value(_cgrid, [coords cArray]);
}

-(gridvalue_t)valueAtCoordinateArray:(int *)array {
  // optimization for 2 dimensions, used in Gridlock to optimize game evaluations
  if (_cgrid->num_dimensions==2) {
    int index = array[0]*_cgrid->dimension_sizes[1] + array[1];
    return _cgrid->grid_data[index];
  }
  return hypergrid_get_value(_cgrid, array);
}

-(id)setValue:(gridvalue_t)value atPosition:(DCHypergridPosition *)coords {
  hypergrid_set_value(_cgrid, [coords cArray], value);
  return self;
}

-(id)setValue:(gridvalue_t)value atCoordinateArray:(int *)array {
  hypergrid_set_value(_cgrid, array, value);
  return self;
}

-(void)setValue:(gridvalue_t)value atPositions:(NSArray *)positions {
  int i;
  for(i=[positions count]-1; i>=0; i--) {
    id pos = [positions objectAtIndex:i];
    hypergrid_set_value(_cgrid, [pos cArray], value);
  }
}

-(BOOL)isValidPosition:(DCHypergridPosition *)position {
  return hypergrid_coords_isvalid(_cgrid, [position cArray]);
}

-(BOOL)isValidCoordinateArray:(int *)array {
  return hypergrid_coords_isvalid(_cgrid, array);
}


-(int)sizeOfDimension:(int)dim {
  return hypergrid_dimension_size(_cgrid, dim);
}

-(int)nonzeroNeighborsOfPosition:(DCHypergridPosition *)coords {
  return hypergrid_neighbor_count(_cgrid, [coords cArray], 0, 0, 1);
}

-(int)nonzeroNeighborsOfPosition:(DCHypergridPosition *)coords wrapping:(BOOL)wrap {
  return hypergrid_neighbor_count(_cgrid, [coords cArray], 0, 0, wrap);
}

-(int)numberOfNeighborsOfPosition:(DCHypergridPosition *)pos withValue:(int)value {
  return hypergrid_neighbor_count(_cgrid, [pos cArray], 1, value, 0);
}

-(int)numberOfCellsWithValue:(int)value {
  return hypergrid_value_count(_cgrid, value);
}

-(BOOL)hasCellWithValue:(int)value {
  return (hypergrid_value_exists(_cgrid, value)!=0);
}

-(BOOL)isEqualToHypergrid:(DCHypergrid *)cmp {
  return hypergrid_equal([self cHypergrid], [cmp cHypergrid]);
}

-(NSArray *)neighborsOfPosition:(DCHypergridPosition *)coords distance:(int)dist {
  NSMutableArray *array;
  int dim = [self numberOfDimensions];

  if (dim==2) {
    int dr, dc;
    int r=[coords row], c=[coords column];
    // max neighbors = (2*dist+1)^2 = 4d^2+4d+1 = 4d(d+1)+1
    array = [NSMutableArray arrayWithCapacity:4*dist*(dist+1)+1];
    for(dr=-dist; dr<=dist; dr++) {
      int newr = r+dr;
      for(dc=-dist; dc<=dist; dc++) {
        int newc = c+dc;
        if ([self isValidRow:newr column:newc]) {
          [array addObject:[DCHypergridPosition positionWithRow:newr column:newc]];
        }
      }
    }
  }
  else {
    int **neighborlist;
    int count;
    int i;
    array = [NSMutableArray array];
    neighborlist = hypergrid_neighbors([self cHypergrid], [coords cArray], dist, &count);
    for(i=0; i<count; i++) {
      DCHypergridPosition *neighbor = [DCHypergridPosition positionWithSize:dim data:neighborlist[i]];
      [array addObject:neighbor];
    }
    hypergrid_coords_list_free(neighborlist, count);
  }
  
  return array;
}

-(NSEnumerator *)positionEnumerator {
  return [[[DCHypergridPositionEnumerator alloc] initWithHypergrid:self] autorelease];
}

-(NSEnumerator *)enumeratorForPositionsWithValue:(int)value {
  return [[[DCHypergridPositionEnumeratorForValue alloc] initWithHypergrid:self targetValue:value] autorelease];
}

-(DCHypergridPosition *)positionWithValue:(int)value {
  int * _coords = (int *)calloc(_cgrid->num_dimensions, sizeof(int));
  DCHypergridPosition *position = nil;
  if (hypergrid_get_value(_cgrid, _coords)==value) {
    position = [DCHypergridPosition positionWithSize:_cgrid->num_dimensions data:_coords];
  }
  while (!position && hypergrid_coords_increment(_cgrid, _coords)) {
    if (hypergrid_get_value(_cgrid, _coords)==value) {
      position = [DCHypergridPosition positionWithSize:_cgrid->num_dimensions data:_coords];
    }
  }
  free(_coords);
  return position;
}

-(NSArray *)allPositionsWithValue:(int)value {
  return [[self enumeratorForPositionsWithValue:value] allObjects];
}

-(void)addPositionsToGroup:(NSMutableSet *)group withValue:(int)pnum startingFromPosition:(id)pos onlyOrthoganal:(BOOL)ortho {
  // this only works for 2d grids currently
  static int orthoDeltas[] = {+1,0, -1,0, 0,+1, 0,-1};
  static int diagDeltas[]  = {+1,+1, +1,0, +1,-1, 0,+1, 0,-1, -1,+1, -1,0, -1,-1};

  [group addObject:pos];

  int *deltas = (ortho) ? orthoDeltas : diagDeltas;
  int numd = (ortho) ? 4 : 8;
  int r=[pos row], c=[pos column];
  int i;
  for(i=0; i<numd; i++) {
    int dr = deltas[2*i];
    int dc = deltas[2*i+1];
    id nextpos = [DCHypergridPosition positionWithRow:r+dr column:c+dc];
    if ([self isValidPosition:nextpos] && [self valueAtPosition:nextpos]==pnum && ![group containsObject:nextpos]) {
      [self addPositionsToGroup:group withValue:pnum startingFromPosition:nextpos onlyOrthoganal:ortho];
    }
  }
}

-(NSArray *)connectedGroupsWithValue:(int)value onlyOrthoganal:(BOOL)ortho {
  // returned array is sorted by ascending size of groups
  NSMutableArray *allGroups = [NSMutableArray array];
  NSMutableSet *positionsInGroups = [[[NSMutableSet alloc] init] autorelease];
  NSEnumerator *pe = [self enumeratorForPositionsWithValue:value];
  id pos;
  while(pos=[pe nextObject]) {
    if (![positionsInGroups containsObject:pos]) {
      NSMutableSet *group = [[[NSMutableSet alloc] init] autorelease];
      [self addPositionsToGroup:group withValue:value startingFromPosition:pos onlyOrthoganal:ortho];
      [positionsInGroups addObjectsFromArray:[group allObjects]];
      [allGroups addObject:group];
    }
  }
  [allGroups sortArrayByCount_];
  return allGroups;
}

-(hypergrid *)cHypergrid {
  return _cgrid;
}

-(void)dealloc {
  if (_cgrid) hypergrid_free(_cgrid);
  [super dealloc];
}

-(id)propertyList{
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  NSMutableArray *dimsizes = [NSMutableArray array];
  NSMutableArray *values = [NSMutableArray array];
  NSEnumerator *pe = [self positionEnumerator];
  id pos;
  int i;
  
  for(i=0; i<[self numberOfDimensions]; i++) {
    [dimsizes addObject:[NSNumber numberWithInt:[self sizeOfDimension:i]]];
  }
  [dict setObject:[dimsizes componentsJoinedByString:@" "] forKey:@"dimensions"];

  while(pos=[pe nextObject]) {
    [values addObject:[NSNumber numberWithInt:[self valueAtPosition:pos]]];
  }
  [dict setObject:[values componentsJoinedByString:@" "] forKey:@"values"];
  
  return dict;
}
-(id)initFromPropertyList:(id)plist {
  NSArray *dimArray = [[plist objectForKey:@"dimensions"] componentsSeparatedByString:@" "];
  NSArray *valArray = [[plist objectForKey:@"values"] componentsSeparatedByString:@" "];
  
  int *dims = malloc([dimArray count]*sizeof(int));
  int i;
  for(i=0; i<[dimArray count]; i++) {
    dims[i] = [[dimArray objectAtIndex:i] intValue];
  }
  [self initWithNumberOfDimensions:[dimArray count] sizes:dims];
  free(dims);
  {
    NSEnumerator *pe = [self positionEnumerator];
    NSEnumerator *ve = [valArray objectEnumerator];
    id pos;
    id val;
    while ((pos=[pe nextObject]) && (val=[ve nextObject])) {
      [self setValue:[val intValue] atPosition:pos];
    }
  }
  return self;
}


// convenience methods for 2d grids

-(id)initWithRows:(int)r columns:(int)c {
  int sizes[] = {r,c};
  return [self initWithNumberOfDimensions:2 sizes:sizes];
}

+(id)gridWithRows:(int)r columns:(int)c {
  return [[[self alloc] initWithRows:r columns:c] autorelease];
}

-(int)valueAtRow:(int)r column:(int)c {
  int coords[] = {r,c};
  return [self valueAtCoordinateArray:coords];
}

-(void)setValue:(int)value atRow:(int)r column:(int)c {
  int coords[] = {r,c};
  [self setValue:value atCoordinateArray:coords];
}

-(BOOL)isValidRow:(int)r column:(int)c {
  int coords[] = {r,c};
  return [self isValidCoordinateArray:coords];
}

-(int)numberOfRows {
  return [self sizeOfDimension:0];
}

-(int)numberOfColumns {
  return [self sizeOfDimension:1];
}


@end