I am trying to create a NSMutableArray so I can populate a map. But immediately after "[row removeAllObjects];" it removes all of the objects in the "layer" array also.
NSMutableArray *row = [[NSMutableArray alloc] init];
NSMutableArray *layer = [[NSMutableArray alloc] init];
NSMutableArray *all = [[NSMutableArray alloc] init];
int blockType = 0;
for (int y = 0; y<10; y++) {
for (int x = 0; x<10; x++) {
for (int z = 0; z<10; z++) {
if (y<5) blockType = 0;
else blockType = arc4random() % 2 + 1;
[row addObject:[NSNumber numberWithInt:blockType]];
}
[layer addObject:row];
[row removeAllObjects];
}
[all addObject:layer];
[layer removeAllObjects];
}
is this because
[layer addObject:row];
[row removeAllObjects];
are being performed at the same time? If so, how do I carry out the actions one after another?
If not, what am I doing wrong?
Try this,
[layer addObject:[row copy]];
You are adding row to layer, but then you're emptying it.
I understand why you are doing this, as you want to re-use both row and layer. However that's not how it works in Objective-C, as variables are just references (C pointers) to objects.
What you need to do is to create all outside the loops, and re-create row and layer inside the inner loops. You can re-use the variables, but the underlying objects need to change.
Try this:
NSMutableArray *all = [[NSMutableArray alloc] init];
NSMutableArray *row;
NSMutableArray *layer;
int blockType = 0;
for (int y = 0; y < 10; y++) {
layer = [[NSMutableArray alloc] init];
for (int x = 0; x < 10; x++) {
row = [[NSMutableArray alloc] init];
for (int z = 0; z < 10; z++) {
if (y < 5)
blockType = 0;
else
blockType = arc4random() % 2 + 1;
[row addObject:[NSNumber numberWithInt:blockType]];
}
[layer addObject: row];
}
[all addObject: layer];
}
Move NSMutableArray *row = [[NSMutableArray alloc] init]; to just after for (int x = 0; x<10; x++) {, and delete [row removeAllObjects]; entirely.
You create a problematic program structure, and it bites you in the behind.
for (int z = 0; z<10; z++) {
if (y<5) blockType = 0;
else blockType = arc4random() % 2 + 1;
[row addObject:[NSNumber numberWithInt:blockType]];
}
[layer addObject:row];
[row removeAllObjects];
This code is supposed to create an array with 10 numbers and add it to the array "layer". But that's not what it does. The array has been created a lot earlier. And add the end, it empties out the array to be ready for the next iteration. That's an awful structure. The correct structure would be:
NSMutableArray* row = [NSMutableArray array];
for (int z = 0; z<10; z++) {
if (y<5) blockType = 0;
else blockType = arc4random() % 2 + 1;
[row addObject:[NSNumber numberWithInt:blockType]];
}
[layer addObject:row];
This does exactly what it is supposed to do: Create an array, fill it with data, add it to layer. No reliance on previous and following code. The complete working code is:
NSMutableArray *all = [[NSMutableArray alloc] init];
for (int y = 0; y<10; y++) {
NSMutableArray *layer = [[NSMutableArray alloc] init];
for (int x = 0; x<10; x++) {
NSMutableArray *row = [[NSMutableArray alloc] init];
for (int z = 0; z<10; z++) {
int blockType = y < 5 ? 0 : arc4random() % 2 + 1;
[row addObject:[NSNumber numberWithInt:blockType]];
}
[layer addObject:row];
}
[all addObject:layer];
}
Well, someone else typed quicker. Which is even better, because you see twice an identical program structure, with almost identical code. That's because the task is clear, and there is exactly one way how any experienced programmer would structure the code.
Related
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;
}
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
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;
}
I’m developing word puzzle game,where one word is given.according to that word the random letters are generated…for that, i applied below logic but some how the random letters not generated as per the given word.
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc]
initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",
nil];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
for(int i =0;i<32;i++)
{
NSUInteger randomIndex = arc4random() %(ArrOfABCD.count);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:[NSString stringWithFormat:#"%#",ArrOfABCD[randomIndex]]
forState:UIControlStateNormal];
[self.view addSubview:btnLetter];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}
can any one suggest me that where i made mistake?
You should generate the unique random number
NSMutableArray* ArrOfWords = [[NSMutableArray alloc] initWithObjects:#"Good",#"Home",#"Beauty",#"Good",nil];
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc] initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
NSMutableArray *arrDuplicate=[[NSMutableArray alloc]init];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
NSInteger rowIndex=4;
NSString *dataString=[ArrOfWords objectAtIndex:0];
NSMutableArray *arrNumber = [[NSMutableArray alloc]init];
for (int i = 0; i < [dataString length]; i++) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
NSNumber *number=[NSNumber numberWithInt:index];
while ([arrDuplicate containsObject:number] ) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
number=[NSNumber numberWithInt:index];
}
[arrNumber addObject:number];
[arrDuplicate addObject:number];
}
[arrDuplicate removeAllObjects];
NSMutableArray *arrayChar = [NSMutableArray array];
for (int i = 0; i < [dataString length]; i++) {
[arrayChar addObject:[NSString stringWithFormat:#"%C", [dataString characterAtIndex:i]]];
}
for(int i =0;i<32;i++)
{
NSString *str=[ArrOfABCD objectAtIndex:arc4random_uniform(ArrOfABCD.count)];
if ([arrNumber containsObject:[NSNumber numberWithInt:i]] ) {
str=[arrayChar objectAtIndex:arrDuplicate.count];
[arrDuplicate addObject:str];
}
NSLog(#"%#",str);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:str forState:UIControlStateNormal];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}
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);