How to add numbers in a mutable array in iPhone? - iphone

I am new to iPhone development. I want a Nsmutable array to hold numbers from 1 to 100. How can I do it? How can I implement in a for loop? Is there any other way to hold numbers in array in iPhone?

You can only add NSObject subclasses in Cocoa containers. In your case, you will have to wrap your integers in NSNumber objects:
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:[NSNumber numberWithInt:i]];
}
To extract the values:
int firstValue = [[array objectAtIndex:0] intValue];

Use an NSNumber object:
[NSNumber numberWithInt:1];

The short hand solution
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:#(i)];
}
int intValue = 10;
NSNumber *numberObj = #(intValue);

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.

Using a for-in loop with NSInteger?

I have an NSMutableArray populated with NSIntegers. I need to loop through the array. I could do:
// given NSMutableArray *array of NSIntegers
NSUInteger n = [array count];
for (NSInteger i = 0; i < n; i++) {
NSInteger x = [array objectAtIndex:i];
// query SQLite WHERE id = x
}
However, it seems that a for (object in array) loop would be cleaner. iOS 5 does not accept NSIntegers or NSNumbers as objects in for-in loops. Should I loop through the array with NSObjects, casting the NSObject to an NSInteger during each iteration? Is there another way? Or is a for loop like the one above the cleanest solution to this problem?
In Objective-C you can use a for-in loop with NSNumber like this:
NSArray *array = /*NSArray with NSNumber*/;
for (NSNumber *n in array) {
NSLog(#"i: %d", [n intValue]);
}
Check this out.
Mostly, you will not be allowed to have an NSMutableArray of NSUInteger (aka unsigned long) as it's not an objective-c object.
You may use the c style.
NSUInteger array[] = {value1,value2,value3};
int size = sizeof(array)/sizeof(array[0]);
for (int i=0; i<size; i++) {
NSInteger value = array[i];
// do whatever you want
}

split NSArray in groups of smaller NSArrays for paging

I have an NSArray of say 100 NSManagedObjects and I need to split that into an NSArray that contains 10 NSArray objects that each hold 10 of theses NSManagedObjects, how would I accomplish that?
I am going to do some paging and this will work well for me.
How are you getting these NSManagedObjects? If you're using an NSFetchRequest, you may want to keep that around and only get 10 results at a time from it.
Here is my code:
[object splitArrayWithArray:arrayWith100Objects rangeNumber:10];
- (NSArray*) splitArrayWithArray:(NSArray*)rawArray rangeNumber:(int)rangeNumber{
int totalCount = rawArray.count;
int currentIndex = 0;
NSMutableArray* splitArray = [NSMutableArray array];
while (currentIndex<totalCount) {
NSRange range = NSMakeRange(currentIndex, MIN(rangeNumber, totalCount-currentIndex));
NSArray* subArray = [rawArray subarrayWithRange:range];
[splitArray addObject:subArray];
currentIndex +=rangeNumber;
}
return splitArray;
}
Something along these lines should work instead of breaking it into separate arrays
//make a new range for each page
NSRange myRange = NSMakeRange(10, 10);
NSArray * myArray = [NSArray array];
//...pass both into a function
for (int i = myRange.location; i < myRange.location + myRange.length; i++) {
//stuff with the array elements
[[myArray objectAtIndex:i] doSomething];
}
It's no one-liner, but this will split an array into pages:
NSArray *arrayToSplit = ...
int pageSize = 50;
NSMutableArray *arrayOfPages = [NSMutableArray new];
NSRange range = NSMakeRange(0, pageSize);
while (range.location < arrayToSplit.count) {
if (range.location + range.length >= arrayToSplit.count)
range.length = arrayToSplit.count - range.location;
[arrayOfPages addObject:[arrayToSplit objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range]]];
range.location += range.length;
}

How to add array values using NSMutableArray in iPHone?

I have the data into the mutable array and the value of array is,
{ "20", "40", "50","60", "70"}.
I have stored the string values into the array.
Now i want to total value of the array. Result is : 240
Thanks!
NSInteger value = 0;
for (String *digit in myArray) {
value += [digit intValue];
}
int total=0;
for(NSString *currentString in myArray){
total +=[currentString intValue];
}
NSLog(#"Sum:%d",total);
This adds all values:
__block NSInteger sum = 0;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
sum += [obj intValue];
}];
You can do as follows:
int totalSum = 0;
NSmutableArray *arrayData = [[NSmutableArray alloc] init];
[arrayData addObject:#"20"];
[arrayData addObject:#"40"];
[arrayData addObject:#"50"];
[arrayData addObject:#"60"];
[arrayData addObject:#"70"];
for(int i=0; i<[arrayData count];i++)
{
totalSum = totalSum + [[arrayData objectAtIndex:i] intValue];
}
NSLog(#"Total:%d",totalSum);
Please let me know if you have any question.
How about the most elegant solution using key-value Collection aggregators:
NSNumber *sum = [myArray valueForKeyPath:#"#sum.self"];

reading an array

I create random numbers using the following code and store them in an array.
NSMutableSet *aSet = [NSMutableSet setWithCapacity:6];
while([aSet count]<=6){
int Randnum = arc4random() % 12;
[aSet addObject:[NSNumber numberWithInt:Randnum]];
}
NSArray *arrayOfUniqueRandomNumbers = [aSet allObjects];
Now, I need to read the array to get the values one-by-one using a forloop like
for (int i = 0; i<6; i++);
Can anyone please help me to finish the code?
You can do:
for (NSNumber *val in arrayOfUniqueRandomNumbers) {
int i = [val intValue];
...
}