How to create a set of sets (18 sets with 5 separate integers per set, all condensed in a single set)

52 Views Asked by At

How would I write the following in Objective-C? Each integer represents a state of a motor (5 motors, with clockwise (1), off (0), counterclockwise (-1) as the states). There are 18 sequences where each motors is "told" to run in CW or CCW direction, or stay off.

{{1,0,0,0,0},
 {0,0,-1,0,0},
 {0,1,0,1,0},
 // etc. for another 15 sets
}

Couple of questions:

  1. I only want to read these values...should I use NSSet?
  2. Would I write the integers as objects? (etc. @"1") Or can I keep them as integers
  3. If I wanted to add a known time stamp in the set, would that change the identity of the set (meaning, it would no longer be an integer-based set) ? Ex: the first time stamp would be 0.3 seconds.

Let me know if you need anymore information. Thanks

2

There are 2 best solutions below

0
Sagar koyani On

we can direct add integer values in array. and can access value with intvalue.

arrMotorStates=[[NSMutableArray alloc] init];
NSMutableArray *arr1=[[NSMutableArray alloc]initWithObjects:@1,@0,@0,@0,@0, nil];
NSMutableArray *arr2=[[NSMutableArray alloc]initWithObjects:@0,@0,@-1,@0,@0, nil];
[arr1 addObject:@5];
[arrMotorStates addObject:arr1];
[arrMotorStates addObject:arr2];
NSLog(@"%d",[arrMotorStates[1][2] intValue]);
0
James Bucanek On

As pointed out, you can't use sets to organize this for two reasons. First, sets only contain unique values and your sets have duplicate values. Second, sets are unordered; the values in your collection have an order.

Arrays would be the simplest solution. In modern Obj-C immutable (read-only) arrays can be declared and built at run-time. And since an array is an object, you can build arrays of arrays.

Declaration:

NSArray<NSArray<NSNumber*>*>* motorState = @[ @[ @1, @0, @0,  @0, @0 ],
                                              @[ @0, @0, @-1, @0, @0 ],
                                              @[ @0, @1, @0,  @1, @0 ] ];

Access:

// get value of row 1, column 3
NSInteger state = motorState[1][3].integerValue;

The only hitch is that the vanilla foundation arrays can only store object references, so each value is encoded as an NSNumber.