Simple array loop question Objective-C - iphone

How can you make this work?
numbers = [[NSMutableArray alloc] initWithObjects: ({int x = 0; while (x <= 60 ) { return x; x++; } })];
Thanks :)

NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = 0; i <= 60; ++i) {
[array addObject:[NSNumber numberWithInt:i]];
}

int myStrangeNumberOfItems = 61;
NSMutableArray * numbers = [[NSMutableArray alloc] initWithCapacity: myStrangeNumberOfItems];
for (int i = 0; i < myStrangeNumberOfItems; i++) {
[numbers addObject:[NSNumber numberWithInt:i]];
}

First, an NSArray can only hold objects, not primitives. You can add the objects within a for loop like so.
NSMutableAray * numbers = [[NSMutableArray alloc] init];
for (int x = 0; x <= 60; x++)
[numbers addObject:[NSNumber numberForInt:x]];

Related

Want to generate non repeating random numbers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating non-repeating random numbers
Here is my code
NSUInteger count = 10;
for (NSUInteger i = 0; i < count; ++i) {
NSLog(#"%d",NeedRandomNumberWithoutRepeat);
}
this output should be like
8
7
9
2
1
4
6
3
5
0
Which is random and not repeating numbers
This should work:
NSUInteger count = 10;
NSMutableArray *array = [[NSMutableArray alloc]init];
for (NSUInteger i = 0; i < count; ++i) {
[array addObject:[NSNumber numberWithInt:i]];
}
NSMutableArray *copy = [array mutableCopy];
array = [[NSMutableArray alloc]init];
while ([copy count] > 0)
{
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];
}
This answer is modified version from one of my answer in SO.
So, you may find something strange here, you can however use this as your requirement is similar.
int TOTAL_NUMBER=10;
NSMutableArray *alreadyGeneratedNumbers;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
alreadyGeneratedNumbers=[NSMutableArray new];
}
-(int)generateRandomNumber{
int low_bound = 0;
int high_bound = TOTAL_NUMBER;
int width = high_bound - low_bound;
int randomNumber = low_bound + arc4random() % width;
return randomNumber;
}
- (IBAction)button:(id)sender {
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:1];
BOOL contains=YES;
while ([shuffle count]<1) {
NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
[shuffle addObject:generatedNumber];
contains=NO;
[alreadyGeneratedNumbers addObject:generatedNumber];
}
}
NSLog(#"shuffle %#",shuffle);
NSLog(#"Next Batch");
if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
NSLog(#"\nGame over, Want to play once again?");//or similar kind of thing.
[alreadyGeneratedNumbers removeAllObjects];
}
}
You put the available numbers in an array, and take the index calculated with arc4random() that goes from 0 to the size of the array -1.When a number comes out you take it away from the array:
NSMutableArray* availableNumbers=[NSMutableArray new];
for(NSUInteger i=0; i<10; i++)
{
[availableNumbers addObject: #(i)];
}
for(NSUInteger i=0; i<10; i++)
{
NSUInteger index= arc4random()%availableNumbers.count;
NSNumber* number= availableNumbers[index];
NSLog(#"%#",number);
[availableNumbers removeObjectAtIndex: index];
}
PS: At the last iteration is useless to sue arc4random(), since there's only one number inside.

Separate array into many in a dynamic way? Obj-C

I currently have this method:
-(void)seperateGuides
{
DLog("GetGuideListCount: %i", [[appDelegate getGuideList] count]);
columnOneArray = [[NSMutableArray alloc] init];
columnTwoArray = [[NSMutableArray alloc] init];
columnThreeArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnOneArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
for (int i = 1; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnTwoArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
for (int i = 2; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnThreeArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
}
And need to do this more dynamic, so I can define how many arrays I want and then get the arrays.
Different possibilities I'm considering is making it a mutli-dimensional array (although I'm not sure how to handle it in Objectvie-C), or making a method that simply loops through as many times as I define, the problem there is that I'm not quite sure how to get the different arrays.
A simple algorithm or another possible solution would be greatly appreciated.
The algorithm you're describing sounds equivalent to what we do when we deal a deck of cards into multiple hands, so I'd do it like this:
- (NSArray *)dealObjects:(NSArray *)objects intoArrays:(NSInteger)numArrays
{
NSMutableArray *arrays = [NSMutableArray arrayWithCapacity:numArrays];
for (a = 0; a < numArrays; a++) {
[arrays addObject:[NSMutableArray arrayWithCapacity:[objects count] / numArrays];
}
for (i = 0; i < [objects count]; i++) {
[[arrays objectAtIndex:i % numArrays] addObject:[objects objectAtIndex:i]];
}
return arrays;
}
You can add multiple array to another arrays as this,
-(void)seperateGuides:(int)columnCount
{
rootArray=[[NSMutableArray alloc] init];
for(int i=0;i<columnCount;i++)
{
column = [[NSMutableArray alloc] init];
for(int j=i;j<[[appDelegate getGuideList] count];j=j+3)
{
[column addObject:[[appDelegate getGuideList]objectAtIndex:j]];
[rootArray addObject:column];
[column release];
}
}
}
Quite simple really. Just add new NSArray objects to a root array as you iterate through your dataset.
- (void)seperateGuides {
DLog("GetGuideListCount: %i", [[AppDelegate getGuideList] count]);
NSArray *root = [[NSArray alloc] init];
int dimensions = anyIntGreaterThanZero;
for (int i = 0; i < dimensions; i += dimensions) {
NSArray *branch = [[NSArray alloc] init];
int k = 0;
for (k += i; k < [[AppDelegate getGuideList] count]; k += dimensions) {
[branch addObject:[[AppDelegate getGuideList] objectAtIndex:k]];
}
[root arrayByAddingObject:branch];
}
}
-(void)seperateGuides
{
NSMutableArray *parentArray = [[NSMutableArray alloc]init];
int count = [[appDelegate getGuideList] count];
int TOTAL_COLUMNS = 3;//Define number of columns here
for (int i = 0; i <count; i++)
{
int columnNo = i % TOTAL_COLUMNS;
if(parentArray.count > columnNo)
{
NSMutableArray *innerArray = [parentArray objectAtIndex:columnNo];
[innerArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
else
{
NSMutableArray *innerArray = [NSMutableArray arrayWithObject:[[appDelegate getGuideList]objectAtIndex:i]];
[parentArray insertObject:innerArray atIndex:columnNo];
}
}
}
Hope this helps...
Here parentArray will have NSMutableArray as its members. Each array represents the objects in a column.

Loading values into an array from two different arrays iphone sdk

Here I am having a situation, I'm using the following code:
int x=0;
for (int i=0; i<=[arrayDeals count]-1; i++) {
x++;
//NSString *deal = [arrayDeals objectAtIndex:i];
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
}
I need to load the values from arrayDeals and the 'x' value into combinedArr. So, I put this in a for loop. But i got only one value from each arrays. What is went wrong here? Please help me. (here CustomObject is a NSObject)
Thank you.
Well there are many things wrong with the code you posted, but I think this is what you want:
int x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
NSInteger count = [arrayDeals count];
for (int i = 0; i < count; i++) {
x++;
CustomObject *customObject = [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x];
[combinedArr addObject:customObject];
}
To give you some idea of what is wrong with the code you posted:
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
Here you create a new NSMutableArray to which you assign an new object to taked the object from the array arrayDeals. But you create this NSMutableArray for every item in the array arrayDeals and you assign them to the same variable.
So each iteration you leak the NSMutableArray.
Also :
for (int i=0; i<=[arrayDeals count]-1; i++) {
is the same as
for (int i=0; i < [arrayDeals count]; i++) {
but the count is called every time you iterate, so as per my example I saved the count in a int to just speed things up.
You could even speed the code up using fast Enumeration:
NSInteger x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
for (id object in arrayDeals) {
id secondObject = [secondArray itemAtIndex:x];
// Arrays start at 0 so only up it after we've got the object.
x++;
CustomObject *customObject = [CustomObject customObjectWithName:object andNumber:x];
[combinedArr addObject:customObject];
}

how to create an C Array

his guys,
i think this is a simple question but i do not know how to do it.
how do i create the line below dynamically from an array?
this is what i need to call.
//data source
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
chartData = [WSData dataWithValues:[WSData arrayWithString:sourceData withLen:7]];
+ (NSArray *)arrayWithString:(NSString *[])strings
withLen:(NSUInteger)len {
NSMutableArray *tmpArr = [NSMutableArray
arrayWithCapacity:len];
NSUInteger i;
for (i=0; i<len; i++) {
[tmpArr addObject:strings[i]];
}
return [NSArray arrayWithArray:tmpArr];
}
thanks for all the help especially Daniel :)
this is the answer to the question
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
dayArray = [NSMutableArray arrayWithCapacity:7];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
sdArray = [NSMutableArray arrayWithCapacity:7];
NSInteger drunked = [appDelegate.drinksOnDayArray count];
if (drunked !=0)
{
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
NSString *sData[7];// = malloc(7 * sizeof(NSString *));
for (int i=0; i<7; i++)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
sData[i] = [NSString stringWithFormat:#"%#",drinksOnDay.standardDrinks];
}
NSString * sourceData[7] = {sData[6],sData[5],sData[4],sData[3],sData[2],sData[1],sData[0] };
}
If you are only using the array as a call parm, and are not storing it somewhere or returning it from your current method:
NSString* sourceData[7];
for (i = 0; i < 7; i++) {
int num = <getTheValueYouWant>;
sourceData[i] = [NSString stringWithFormat:#"%d", num];
}
But note that if you intend to return the array, or store it in some long-lived variable, you need an entirely different setup.
So this is how you would create an NSMutableArray. Mutable because you're creating it at runtime.
NSString * sourceData = [[NSString alloc] initWithFormat:#""];
//assuming the array you have is arr with NSNumber objects
for (NSNumber *num in arr) {
[sourceData stringByAppendingFormat:#"%#", num];
}
You can try below code with the loop as you required.....
NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

Assigning a button tag from an array which stores integers

I am trying to assign a tag to button. The normal command is:
button.tag = 1;
The tag must be an integer.
My problem is that I would like to assign an integer which I stored in an array (tabReference) which is yet again part of a class (currentNoteBook). So I need this:
int k = 0;
button.tag = [currentNoteBook.tabReference objectAtIndex:k]; // This is where I get the warning.
This doesn't seem to work, however, as xCode tells me: Passing argument 1 of setTag: makes integer from pointer without a cast.
My array looks like this (I tried to use integers...):
NSMutableArray *trArray = [[NSMutableArray alloc] init];
NSNumber *anumber = [NSNumber numberWithInteger:1];
[trArray addObject: anumber];
[trArray addObject: anumber];
[trArray addObject: anumber];
[trArray addObject: anumber];
currentNoteBook.tabReference = trArray;
An NSMutableArray stores a modifiable array of objects. You can't directly store an integer in an NSMutableArray. That's why you have to do something like this to store a bunch of integers:
NSMutableArray *the_array = [[NSMutableArray alloc] init];
int max = 100;
for (int i = 0; i < max; i++)
{
NSNumber *temp_number = [NSNumber numberWithInt:arc4random() % max];
[the_array addObject:temp_number];
}
Of course, you could do pretty much the same thing and store something else in there:
NSMutableArray *the_array = [[NSMutableArray alloc] init];
int max = 100;
int max_x = 50;
int max_y = 25;
int max_w = 100;
int max_h = 200;
for (int i = 0; i < max; i++)
{
CGFloat temp_x = arc4random() % max_x;
CGFloat temp_y = arc4random() % max_y;
CGFloat temp_w = arc4random() % max_w;
CGFloat temp_h = arc4random() % max_h;
CGRect temp_rect = CGRectMake(temp_x, temp_y, temp_w, temp_h);
[the_array addObject:[NSValue valueWithCGRect:temp_rect]];
}
When you go to retrieve these values you need to specify what it is you want out of the array because the same array can contain very different objects.
For your integers:
for (int i = 0; i < max; i++)
{
NSLog(#"%i: %i", i, [[the_array objectAtIndex:i] intValue]);
}
For the CGRect example:
for (int i = 0; i < max; i++)
{
CGRect temp_rect = [[the_array objectAtIndex:i] CGRectValue];
NSLog(#"%i: x:%f y:%f w:%f h:%f", i, temp_rect.origin.x, temp_rect.origin.y, temp_rect.size.width, temp_rect.size.height);
}
In a nutshell, you are storing objects not integers in your code. You have to pull them out of there as objects and then extract your integer to get your data back.
Just found the answer in another question I posed:
it must be:
btn.tag = [[currentNoteBook.tabReference objectAtIndex:k] intValue];