Convert id type to int [duplicate] - ios

This question already has an answer here:
Get int value from NSMutableOrderedSet
(1 answer)
Closed 8 years ago.
I guess it's really simple, but I can't find the way to work this out...
#property (strong, nonatomic) NSMutableArray *randomQuestionNumberArray;
I have a method beginning like this
- (int)showQuestionMethod:(int)number;
In this method I have a loop where I fill NSMutableArray with numbers and then shuffle it.
//Creating random questions array
_randomQuestionNumberArray = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfQuestions; i++) {
[_randomQuestionNumberArray addObject:[NSNumber numberWithInt:i]];
}
//Shuffling the array
NSUInteger count = [_randomQuestionNumberArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[_randomQuestionNumberArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
And this works pretty well. Let's say it shuffles the numbers like 4, 5, 1, 3, 6, 0, 2.
Now in viewDidLoad I try to call the the method showQuestionMethod with the first value of _randomQuestionNumberArray which should be 4 in this case.
[self showQuestionMethod:[_randomQuestionNumberArray[0] intValue]];
The problem is that the method gets passed the value of 0 all the time when it should be 4, but NSLog(#"first value is %#", _randomQuestionNumberArray[0]) returns the correct value of 4.
How do I get around this and convert id type to int?

You can try this:
[self showQuestionMethod:[(NSNumber)_randomQuestionNumberArray[0] intValue]];

Are you sure, that the wrong value is passed? Maybe you have a problem with your NSLog statement in your showQuestionMethod.
I've tried this code and it works fine:
- (IBAction)start:(id)sender {
NSMutableArray *_randomQuestionNumberArray;
int numberOfQuestions=5;
_randomQuestionNumberArray = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfQuestions; i++) {
[_randomQuestionNumberArray addObject:[NSNumber numberWithInt:i]];
}
//shuffling the array
NSUInteger count = [_randomQuestionNumberArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[_randomQuestionNumberArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSLog(#"first value is %#", _randomQuestionNumberArray[0]);
[self showQuestionMethod:[_randomQuestionNumberArray[0] intValue]];
}
- (void)showQuestionMethod:(int)number {
NSLog(#"number is %d", number);
}

Related

Displaying Array in NSLog

I have made a basic card shuffling algorithm.
I want to check if its working through the nslog.
It crashes the app and puts in a break point at the nslog
Can someone help with doing so?
-(IBAction)suffle:(id)sender
{
NSMutableArray *arrayExample = [[NSMutableArray alloc] init];
[arrayExample addObject:[NSNumber numberWithInt:1]];
[arrayExample addObject:[NSNumber numberWithInt:2]];
[arrayExample addObject:[NSNumber numberWithInt:3]];
[arrayExample addObject:[NSNumber numberWithInt:4]];
for (int i = 0; i < [arrayExample count]; ++i) {
int r = (random() % [arrayExample count]);
[arrayExample exchangeObjectAtIndex:i withObjectAtIndex:r];
NSLog(#"%#", [arrayExample description]);
}
}
Here is my code
Maybe this routine help you.
- (NSMutableArray *)generateRandomNumbers:(NSNumber *)numberOfElements {
NSMutableArray *arrayRandomPositions = [[NSMutableArray alloc] init];
// First create sequential numbers array
for (int i=0; i<[numberOfElements integerValue]; i = i +1) {
[arrayRandomPositions addObject:[NSNumber numberWithInt:i]];
}
// Make the shuffle
for (int i = 0; i < [numberOfElements integerValue]; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = (int)[numberOfElements integerValue] - i;
int n = arc4random_uniform(nElements) + i;
[arrayRandomPositions exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return arrayRandomPositions;
}

instantiate an NSArray with integers value

I have a PickerView and I want to initialize it with integer values. For example PickerView with all integers lower than 10.
Thank you
NSArray *array =[NSArray arrayWithObjects:#1,#2,#3,#4,#5,#6,#7,#8,#9,nil];
NSMutableArray *yourArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[yourArray addObject:[NSNumber numberWithInt:i]];
}
NSInteger min = 1;
NSInteger max = 10;
NSInteger step = 1;
NSMutableArray<NSNumber *> *options = [NSMutableArray new];
for (NSInteger index = 0; index < ceilf(((float)max)/step); index++)
{
options[index] = #((index + min) * step);
}
NSLog(#"%#",options);
An alternate approach:
NSInteger from = 1;
NSInteger size = 10;
NSInteger step = 1;
NSMutableArray<NSNumber *> *options = [NSMutableArray new];
for (NSInteger index = 0; index < size; index++)
{
options[index] = #((index + from) * step);
}
NSLog(#"%#",options);
Both of the above print the following:
(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
)
int yourInt = 5;
[myMutableArray addObject:[NSNumber numberWithInt:yourInt]]; have look on this
It will just sample code to add the int value to the array nothing else

How to randomize a multidimensional NSMutableArray?

So, I was tasked with randomizing a multidimensional array in Objective-C.
I needed to make this:
[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
Look something like this:
[[4,8,6],[1,7,9],[2,11,10],[3,5,12]]
I did that by hand, so please excuse me for the poor randomization.
This is what I came up with, please feel free to critique or improve it. I borrowed certain parts from existing SO contributions.
-(NSMutableArray *)shuffleArray:(NSMutableArray *)array
{
NSMutableArray *flatArray = [array valueForKeyPath:#"#unionOfArrays.self"];
NSUInteger count = flatArray.count;
for (NSUInteger i = 0; i < count; i++) {
NSInteger remainingCount = count - i;
NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t)remainingCount);
[flatArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}
NSMutableArray *set = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int i = 0; i < flatArray.count; i++) {
[tempArray addObject:flatArray[i]];
if ((i + 1) % 3 == 0) {
[set addObject:[tempArray copy]];
[tempArray removeAllObjects];
}
}
return set;
}

How to delete the number from non repeating number array?

I am trying this code for generating a random number and saving the list of numbers in an array, then i am trying to delete those numbers from the list one by one which appeared once, e.g
1, 5, 9 , 4, 3, 7 ,6 ,10, 11, 8, 2 are the list of integers now 9 is appeared once and now i do not need 9 again.. this is my code of random non repeating numbers array.
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
{
x = arc4random() % 10;//generating random number
if(i==0)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
Try this,
NSArray *arrRandoms = [[NSArray alloc]initWithObjects:1,5,8,7,36,17,96,32,5,7,8,13,36,nil] ; // This contains your random numbers
NSMutableArray *arrFresh = [[NSMutableArray alloc]init];
// Now removing the duplicate numbers
BOOL checkRepeat = NO;
int _Current;
for (int i=0; i<[arrRandoms count]; i++)
{
_Current = [arrRandoms objectAtIndex:i];
if (i == 0)
[arrFresh addObjects:_Current];
else
{
checkRepeat = NO;
for(int j=0; j< [arrFresh count]; j++)
{
if ( _Current == [arrFresh objectAtIndex:j])
checkRepeat = YES;
}
if (checkRepeat == NO)
[arrFresh addObjects:_Current];
}
}
I think this code will work. Check It.
try it
//**************remove repeat objects from array***************************//
NSArray *noDuplicates = [[NSSet setWithArray: yourArray] allObjects];
you add
.h file
BOOL isSame;
NSMutableArray *countArray;
NSInteger randomNumber;
.m file
countArray=[[NSMutableArray alloc]init];
//get randon no
-(NSInteger)getRandomNo:(NSInteger)range
{
isSame=TRUE;
while (isSame){
isSame = FALSE;
randomNumber = arc4random() % range;
for (NSNumber *number in countArray){
if([number intValue] ==randomNumber){
isSame = TRUE;
break;
}
}
}
[countArray addObject:[NSNumber numberWithInt:randomNumber]];
return randomNumber;
}
Tested Please try this,
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
NSMutableSet * setUnique = [[NSMutableSet alloc] init];
for (int i=0; [setUnique count] < 10; i++) //Loop for generate different random values
{
[setUnique addObject:[NSNumber numberWithInt:arc4random() % 10]];
}
storeArray = [[setUnique allObjects] mutableCopy];
// check this how to get random number in array (i.e.. this array(below arr_numbers) contain non repeated number)
// for general purpose i am posting this.. so people cannot check for another answer
int num_count = 10;
int RandomNumber;
NSMutableArray *arr_numbers = [[NSMutableArray alloc] init];
for (int j =0; j < num_count; j++)
{
RandomNumber = 0 + arc4random() % num_count;
NSLog(#"%d",RandomNumber);
if ([arr_numbers count]>0)
{
if (![arr_numbers containsObject:[NSNumber numberWithInt:RandomNumber]])//
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
if (j == num_count-1)
{
if ([arr_numbers count] != num_count)
{
j = 0;
}
}
}
else
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
}
NSLog(#"%#",arr_numbers);

Efficient storage of two dimensional data that enables "rotation" of the data by row or column

I'd like to store a two dimensional array of data that makes it possible to easily "rotate" the data either by row or column.
For example, considering the following initial state
A B C D
E F G H
I J K L
M N O P
If I wanted to "rotate" the 3rd ('C') column of data by +2, the result would be:
A B K D
E F O H
I J C L
M N H P
If I then wanted to "rotate" the 2nd ('E') row by -1, the result would be:
A B K D
F O H E
I J C L
M N H P
I can envisage how you'd enable an efficient means of rotating either by row or column by storing the underlying data as either an array of rows or an array of columns, but being able to do both would presumably result in having one means of rotation being a lot less efficient, as you'd have to carry out operations across each of the arrays in turn.
Then again, I've never tried to solve this type of problem before, so perhaps I'm missing something obvious.
Unless you have huge arrays, I would not sweat it and use either row or column storage with plain NSArrays as you have mentioned. An alternative implementation would be to use just one array and compute indexes yourself. Finally, there is also the possibility of using a c-array internally. I've implemented all three using 4x4 matrices and the c-arrays are by far the fastest yet the simple nested arrays remain more than fast enough:
#import <mach/mach_time.h>
typedef void(^execution_block_t)(void);
double time_execution(execution_block_t aBlock);
double time_execution(execution_block_t aBlock)
{
uint64_t time0 = mach_absolute_time();
aBlock();
uint64_t time1 = mach_absolute_time();
return (double)(time1 - time0)/NSEC_PER_SEC;
}
// -----------------------------------------------------------------------------
#pragma mark - Using Nested Arrays
// -----------------------------------------------------------------------------
#interface Simple2DRotMatrix : NSObject {
NSMutableArray *_rows;
}
- (void) rotateRowRightAtIndex:(NSUInteger)index;
- (void) rotateColumnRightAtIndex:(NSUInteger)index;
#end
#implementation Simple2DRotMatrix
- (id) init
{
if ((self = [super init])) {
_rows = [NSMutableArray array];
for (int i=0; i<4; i++) {
NSMutableArray *aRow = [NSMutableArray array];
for (int j=0; j<4; j++)
[aRow addObject:#(i*4+j+1)];
[_rows addObject:aRow];
}
}
return self;
}
- (void) rotateArrayRight:(NSMutableArray*)array
{
id value = array.lastObject;
[array removeObjectAtIndex:array.count-1];
[array insertObject:value atIndex:0];
}
- (void) rotateRowRightAtIndex:(NSUInteger)index
{
[self rotateArrayRight:_rows[index]];
}
- (void) rotateColumnRightAtIndex:(NSUInteger)index
{
NSMutableArray *col = [NSMutableArray arrayWithCapacity:_rows.count];
for (NSArray *row in _rows)
[col addObject:row[index]];
[self rotateArrayRight:col];
NSEnumerator *values = col.objectEnumerator;
for (NSMutableArray *row in _rows)
[row replaceObjectAtIndex:index withObject:values.nextObject];
}
- (NSString*) description
{
NSMutableString *descr = [NSMutableString string];
for (NSArray *row in _rows) {
[descr appendString:[row componentsJoinedByString:#","]];
[descr appendString:#"\n"];
}
return descr;
}
#end
// -----------------------------------------------------------------------------
#pragma mark - Using 1-D Arrays
// -----------------------------------------------------------------------------
#interface Simple1DRotMatrix : NSObject {
NSMutableArray *_values;
NSMutableIndexSet *_indexes0;
}
- (void) rotateRowRightAtIndex:(NSUInteger)index;
- (void) rotateColumnRightAtIndex:(NSUInteger)index;
#end
#implementation Simple1DRotMatrix
- (id) init
{
if ((self = [super init])) {
_values = [NSMutableArray array];
for (int i=0; i<16; i++)
[_values addObject:#(i)];
_indexes0 = [NSMutableIndexSet indexSetWithIndex:0];
[_indexes0 addIndex:4];
[_indexes0 addIndex:8];
[_indexes0 addIndex:12];
}
return self;
}
- (void) rotateArrayRight:(NSMutableArray*)array
{
id value = array.lastObject;
[array removeObjectAtIndex:array.count-1];
[array insertObject:value atIndex:0];
}
- (void) rotateRowRightAtIndex:(NSUInteger)index
{
NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index*4, 4)];
NSMutableArray *row = [[_values objectsAtIndexes:indexes] mutableCopy];
[self rotateArrayRight:row];
[_values replaceObjectsAtIndexes:indexes withObjects:row];
}
- (void) rotateColumnRightAtIndex:(NSUInteger)index
{
NSMutableIndexSet *indexes = [_indexes0 mutableCopy];
[indexes shiftIndexesStartingAtIndex:0 by:index];
NSMutableArray *col = [[_values objectsAtIndexes:indexes] mutableCopy];
[self rotateArrayRight:col];
[_values replaceObjectsAtIndexes:indexes withObjects:col];
}
- (NSString*) description
{
NSMutableString *descr = [NSMutableString stringWithString:#"\n"];
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
[descr appendFormat:#"%#,",_values[i*4+j]];
}
[descr appendString:#"\n"];
}
return descr;
}
#end
// -----------------------------------------------------------------------------
#pragma mark - Using C Arrays
// -----------------------------------------------------------------------------
#interface Simple2DCArrayRotMatrix : NSObject {
id _values[4][4];
}
- (void) rotateRowRightAtIndex:(NSUInteger)index;
- (void) rotateColumnRightAtIndex:(NSUInteger)index;
#end
#implementation Simple2DCArrayRotMatrix
- (id) init
{
if ((self = [super init])) {
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++)
_values[i][j] = #(i);
}
}
return self;
}
- (void) rotateRowRightAtIndex:(NSUInteger)index
{
id temp = _values[index][0];
_values[index][0] = _values[index][3];
_values[index][1] = _values[index][0];
_values[index][2] = _values[index][1];
_values[index][3] = temp;
}
- (void) rotateColumnRightAtIndex:(NSUInteger)index
{
id temp = _values[0][index];
_values[0][index] = _values[3][index];
_values[1][index] = _values[0][index];
_values[2][index] = _values[1][index];
_values[3][index] = temp;
}
- (NSString*) description
{
NSMutableString *descr = [NSMutableString stringWithString:#"\n"];
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
[descr appendFormat:#"%#,",_values[i][j]];
}
[descr appendString:#"\n"];
}
return descr;
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
static int kLoopSize = 50000;
Simple2DRotMatrix *mat2d = [[Simple2DRotMatrix alloc] init];
double t0 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat2d rotateRowRightAtIndex:i%4];
});
double t1 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat2d rotateColumnRightAtIndex:i%4];
});
NSLog(#"2D: Time for %d row rotations: %f",kLoopSize, t0);
NSLog(#"2D: Time for %d column rotations: %f",kLoopSize, t1);
Simple1DRotMatrix *mat1d = [[Simple1DRotMatrix alloc] init];
t0 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat1d rotateRowRightAtIndex:i%4];
});
t1 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat1d rotateColumnRightAtIndex:i%4];
});
NSLog(#"1D: Time for %d row rotations: %f",kLoopSize, t0);
NSLog(#"1D: Time for %d column rotations: %f",kLoopSize, t1);
Simple2DCArrayRotMatrix *mat2dC = [[Simple2DCArrayRotMatrix alloc] init];
t0 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat2dC rotateRowRightAtIndex:i%4];
});
t1 = time_execution(^(void) {
for (int i=0; i<kLoopSize; i++)
[mat2dC rotateColumnRightAtIndex:i%4];
});
NSLog(#"C-Array: Time for %d row rotations: %f",kLoopSize, t0);
NSLog(#"C-Array: Time for %d column rotations: %f",kLoopSize, t1);
}
return 0;
}
I get the following output:
2D: Time for 50000 row rotations: 0.009645
2D: Time for 50000 column rotations: 0.099982
1D: Time for 50000 row rotations: 0.118850
1D: Time for 50000 column rotations: 0.133798
C-Array: Time for 50000 row rotations: 0.001620
C-Array: Time for 50000 column rotations: 0.002277

Resources