print array of NSString in Objective-C - objective-c

So I have a NSMutableArray of size 100, and I want to print 10 cells at a time (So it looks like a grid). What is the easiest way to print 10 indexes at a time? Thanks.
Here's what I did, it only prints 1 index at a time.
-(void) printBoard{
for(int i =0; i<_board.count; i++){
NSLog(#"%# |", [_board objectAtIndex:i]);
}

If you want to print a contiguous array as a two-dimensional array, you can use something like the following:
- (NSString *) description
{
NSMutableString *result = [NSMutableString string];
for (int y = 0; y < 100; y += 10)
{
NSArray *row = [_board subarrayWithRange:NSMakeRange(y, 10)];
NSString *rowString = [row componentsJoinedByString:#" | "];
[result appendFormat:#"%#\n", rowString];
}
return result;
}
If you put this instance method in your class then you can use NSLog() directly on your instance (that is instead of doing [object printBoard] your would use NSLog(#"%#", object);).

Related

How to add elements in NSArray in Objective-C?

I want to add multiple elements in NSArray with #"title" and value.
for(int i = 0; i < size; i++){
BSDevice *d=[[DeviceManager devices] objectAtIndex:i];
self.dataArray =#[#{#"title":d.Name}];
}
But in this code it only adds one value. When I try with this method it doesn't work:
for(int i = 0; i < size; i++){
BSDevice *d=[[DeviceManager devices] objectAtIndex:i];
[self.dataArray addObject:#[#{#"title":d.buddyName}]];
}
I want to have multiple values with string and its value in NSArray like this #"title":d.Name,#"title":d.Name,#"title":d.Name
Your question isn't very clear and you didn't really explain what problem you are having with the second bit of code, but I think what you want is the following:
for (BSDevice *d in [DeviceManager devices]) {
[self.dataArray addObject:#{ #"title" : d.buddyName }];
}
This assumes that self.dataArray is an NSMutableArray and somewhere before this for loop you initialized self.dataArray as:
self.dataArray = [NSMutableArray array];

Sort characters in NSString into alphabetical order

I'm trying to re-arrange words into alphabetical order. For example, tomato would become amoott, or stack would become ackst.
I've found some methods to do this in C with char arrays, but I'm having issues getting that to work within the confines of the NSString object.
Is there an easier way to do it within the NSString object itself?
You could store each of the string's characters into an NSArray of NSNumber objects and then sort that. Seems a bit expensive, so I would perhaps just use qsort() instead.
Here it's provided as an Objective-C category (untested):
NSString+SortExtension.h:
#import <Foundation/Foundation.h>
#interface NSString (SortExtension)
- (NSString *)sorted;
#end
NSString+SortExtension.m:
#import "NSString+SortExtension.h"
#implementation NSString (SortExtension)
- (NSString *)sorted
{
// init
NSUInteger length = [self length];
unichar *chars = (unichar *)malloc(sizeof(unichar) * length);
// extract
[self getCharacters:chars range:NSMakeRange(0, length)];
// sort (for western alphabets only)
qsort_b(chars, length, sizeof(unichar), ^(const void *l, const void *r) {
unichar left = *(unichar *)l;
unichar right = *(unichar *)r;
return (int)(left - right);
});
// recreate
NSString *sorted = [NSString stringWithCharacters:chars length:length];
// clean-up
free(chars);
return sorted;
}
#end
I think separate the string to an array of string(each string in the array contains only one char from the original string). Then sort the array will be OK. This is not efficient but is enough when the string is not very long. I've tested the code.
NSString *str = #"stack";
NSMutableArray *charArray = [NSMutableArray arrayWithCapacity:str.length];
for (int i=0; i<str.length; ++i) {
NSString *charStr = [str substringWithRange:NSMakeRange(i, 1)];
[charArray addObject:charStr];
}
NSString *sortedStr = [[charArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] componentsJoinedByString:#""];
// --------- Function To Make an Array from String
NSArray *makeArrayFromString(NSString *my_string) {
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < my_string.length; i ++) {
[array addObject:[NSString stringWithFormat:#"%c", [my_string characterAtIndex:i]]];
}
return array;
}
// --------- Function To Sort Array
NSArray *sortArrayAlphabetically(NSArray *my_array) {
my_array= [my_array sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
return my_array;
}
// --------- Function Combine Array To Single String
NSString *combineArrayIntoString(NSArray *my_array) {
NSString * combinedString = [[my_array valueForKey:#"description"] componentsJoinedByString:#""];
return combinedString;
}
// Now you can call the functions as in below where string_to_arrange is your string
NSArray *blowUpArray;
blowUpArray = makeArrayFromString(string_to_arrange);
blowUpArray = sortArrayAlphabetically(blowUpArray);
NSString *arrayToString= combineArrayIntoString(blowUpArray);
NSLog(#"arranged string = %#",arrayToString);
Just another example using NSMutableString and sortUsingComparator:
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:#"tomat"];
[mutableString appendString:#"o"];
NSLog(#"Orignal string: %#", mutableString);
NSMutableArray *charArray = [NSMutableArray array];
for (int i = 0; i < mutableString.length; ++i) {
[charArray addObject:[NSNumber numberWithChar:[mutableString characterAtIndex:i]]];
}
[charArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
if ([obj1 charValue] < [obj2 charValue]) return NSOrderedAscending;
return NSOrderedDescending;
}];
[mutableString setString:#""];
for (int i = 0; i < charArray.count; ++i) {
[mutableString appendFormat:#"%c", [charArray[i] charValue]];
}
NSLog(#"Sorted string: %#", mutableString);
Output:
Orignal string: tomato
Sorted string: amoott

Difficulty with getting random words from NSArray

When I Build & Run my application, it will not generate anything. What I have generating are words and after it erases that word and continues until it exhausts all the words and then repopulates the list again. Here is the code:
#implementation randomnumbersViewController
#synthesize words;
#synthesize randomArray;
#synthesize array;
-(IBAction)generateNumber:(id)sender {
NSInteger randomize(id num1, id num2, void *context);
int rand = arc4random() %2;
if (rand)
return NSOrderedAscending;
else
return NSOrderedDescending;
}
- (void)resetRandomArray;
{
[randomArray setArray: array];
[randomArray sortUsingFunction:random context:NULL];
}
- (NSString*) getRandomWord; {
if ([randomArray count] ==0)
return nil;
NSString* result;
NSInteger randomIndex = [[randomArray lastObject] intValue];
[randomArray removeLastObject];
result = [words objectAtIndex:randomIndex];
return result;
}
- (void)buildRandomWordArray
{
NSInteger index;
NSError *theError;
NSString *path = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"text"];
NSString *text = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &theError];
self.words = [text componentsSeparatedByString: #"\n"];
int arraySize = [words count];
self.array = [NSMutableArray arrayWithCapacity:arraySize];
//This code fills "array' with index values from 0 to the number of elements in the "words" array.
for (index = 0; index<arraySize; index++)
[array addObject: [NSNumber numberWithInt: index]];
[self resetRandomArray];
//for (index = 0; index<=arraySize; index++)
// NSLog(# "Random word: %#", [self getRandomWord]);
}
Also a .txt document must be included in the resources folder in for this to work and I do have it there, but nothing. Does anyone have any suggestions as to how I can actually get it to generate the words, or why it isn't working properly?
I don't get how sorting the array ascending or descending is going to shuffle the array, maybe because it doesn't. :) You should use the Fisher–Yates shuffle implemented here: What's the Best Way to Shuffle an NSMutableArray? Import that category, and just call shuffle on the mutable array.

How do you put an integer array into a setIntValue in objective-c?

I have:
myAnswerArray[i] with four-digit integers stored in them like,
myAnswerArray[0]=1412
myAnswerArray[1]=0518
myAnswerArray[2]=2307
I have an IBOutlet 'answerField'
so I want to [answerField setIntValue:(something)]
and have it send:
1412 0518 2307 to the text field.
For a small array:
[answerField setStringValue:[NSString stringWithFormat:#"%04i %04i %04i", myAnswerArray[0], myAnswerArray[1], myAnswerArray[2]]];
For larger array, build your string using NSMutableString:
NSMutableString *temp = [NSMutableString stringWithCapacity:500];
for (int i = 0; i < 100; i++) {
[temp appendFormat:#"%04i ", myAnswerArray[i]];
}
[answerField setStringValue:temp];
Try:
[answerField setStringValue:[myAnswerArray componentsJoinedByString:#" "]];

How to simplify my code... 2D NSArray in Objective C...?

self.myArray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil], [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil],nil];
for (int k=0; k<[self.myArray count]; k++) {
for(int s = 0; s<[[self.myArray objectAtIndex:k] count]; s++){
[[[self.myArray objectAtIndex:k] objectAtIndex:s] setAttribute:[self generateSecertAttribute]];
}
}
As you can see this is a simple 2*2 array, but it takes me lots of code to assign the NSArray in very first place, because I found that the NSArray can't assign the size at very beginning. Also, I want to set attribute one by one. I can't think of if my array change to 10*10. How long it could be. So, I hope you guys can give me some suggestions on shorten the code, and more readable. thz
(Some Assumptions: myArray will have a fixed size. It won't grown up or become smaller in the run time.)
Generate the array by -addObject:.
NSMutableArray* myArray = [NSMutableArray array];
for (int k = 0; k < 10; ++ k) {
NSMutableArray* subArr = [NSMutableArray array];
for (int s = 0; s < 10; ++ s) {
id item = (s == 0 && k == 0) ? [self d] : [self generateMySecretObject];
[item setAttribute:[self generateSecertAttribute]];
[subArr addObject:item];
}
[myArray addObject:subArr];
// use [myArray addObject:[[subArr copy] autorelease]] for deep immutability.
}
return [[myArray copy] autorelease];
(Don't query self.myArray many times. Each corresponds to an ObjC call and while someone calls an ObjC call is cheap, it's still not free.)
If the array is a fixed size and each row is the same length then you could uses a 1D array and an offset, EG:
int rowLength = 5;
int rowNumber = 0;
int columnNumber = 3;
[myArray objectAtIndex: (rowLength * rowNumber) + columnNumber];