algorithm to add randomly-generated NSStrings to NSMutableArray - objective-c

The goal is to generate an NSString chars in length and assign each string to an array. I'm getting stuck on what I need to do with my algorithm to get the correct result. Here's the sample. The result I get is the same randomly generated string added to my array 26 times instead of 26 DIFFERENT strings added.
I've thought about declaring 26 different NSStrings and assigning each result from the algorithm to each string, but that seems inefficient. Thanks for the help.
NSMutableString *string = #"expert";
NSUInteger strLength = [string length];
NSString *letterToAdd;
NSString *finishedWord;
NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"a", #"b", #"c", #"d",
#"e", #"f", #"g", #"h", #"i", #"j", #"k", #"l", #"m",
#"o", #"p", #"q", #"r", #"s", #"t", #"u", #"v", #"w",
#"x", #"y", #"z", nil];
for (int a = 0; a < 26; a++) {
for (int i = 0; i < strLength; i++) {
letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]];
if([randomString length] < strLength) {
[randomString insertString: letterToAdd atIndex: i];
}
finishedWord = randomString;
}
[randomArray addObject: finishedWord];
}
NSLog(#"Random Array count %i, contents: %#", [randomArray count], randomArray);

Here's how I would do it:
#import "NSString+Shuffle.h"
NSString * string = #"expert";
NSUInteger strLength = [string length];
NSString * alphabet = #"abcdefghijklmnopqrstuvwxyz";
NSMutableSet * randomWords = [NSMutableSet set];
while ([randomWords count] < 26) {
NSString * newWord = [alphabet shuffledString];
newWord = [newWord substringToIndex:strLength];
[randomArray addObject:newWord];
}
NSLog(#"Random set count %d, contents: %#", [randomWords count], randomWords);
You'd then need a category on NSString that defines shuffledString. This method would simply take the characters in the string and rearrange them randomly. Decent shuffle algorithms can be found quite easily with Google.
I hope you get the basic idea of how this works. The only modification I made is using an NSSet instead of an NSArray, and what the conditional on the loop is. The eliminates the (slim) possibility of duplicate random words.
Edit: since I'm feeling generous, here's a basic shuffledString implementation:
//NSString+Shuffle.h
#interface NSString (ShuffleAdditions)
- (NSString *) shuffledString;
#end
//NSString+Shuffle.m
#import "NSString+Shuffle.h"
#implementation NSString (ShuffleAdditions)
- (NSString *) shuffledString {
NSMutableString * shuffled = [self mutableCopy];
NSUInteger length = [shuffled length];
for (int i = 0; i < (4*length); ++i) {
NSString * randomChar = [shuffled subStringWithRange:NSMakeRange(arc4random() % (length-1), 1)];
[shuffled appendString:randomChar];
}
return [shuffled autorelease];
}
#end

You should create a new randomString each time:
NSMutableString *string = #"expert";
NSUInteger strLength = [string length];
NSString *letterToAdd;
NSString *finishedWord;
//NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"a", #"b", #"c", #"d", #"e", #"f",
#"g", #"h", #"i", #"j", #"k", #"l", #"m", #"o", #"p", #"q", #"r", #"s",
#"t", #"u", #"v", #"w", #"x", #"y", #"z", nil];
for (int a = 0; a < 26; a++) {
NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
for (int i = 0; i < strLength; i++) {
letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]];
//if([randomString length] < strLength) {
[randomString insertString: letterToAdd atIndex: i];
//}
//finishedWord = randomString;
}
//[randomArray addObject: finishedWord];
[randomArray addObject: randomString];
}
NSLog(#"Random Array count %i, contents: %#", [randomArray count], randomArray);

You're adding the same object to your array every time through the loop, and overwriting it as you go. You mentioned:
I've thought about declaring 26 different NSStrings and assigning each
result from the algorithm to each string...
And that is indeed exactly what you need to do. Moving the initialization of randomString into the loop will solve your problem (getting a new NSMutableString on every loop iteration, rather than using a single object). Change the definition of randomString to a simple type definition:
NSMutableString *randomString;
and then in your outer loop, add this line:
randomString = [NSMutableString stringWithCapacity:strLength];
You shouldn't need to change any of the rest of your code.

Related

Is there a simple way to split a NSString into an array of characters?

Is there a simple way to split a NSString into an array of characters? It would actually be best if the resulting type were a collection of NSString's themselves, just one character each.
Yes, I know I can do this in a loop, but I'm wondering if there is a faster way to do this with any existing methods or functions the way you can with LINQ in C#.
e.g.
// I have this...
NSString * fooString = #"Hello";
// And want this...
NSArray * fooChars; // <-- Contains the NSStrings, #"H", #"e", #"l", #"l" and #"o"
You could do something like this (if you want to use enumerators)
NSString *fooString = #"Hello";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[fooString length]];
[fooString enumerateSubstringsInRange:NSMakeRange(0, fooString.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characters addObject:substring];
}];
And if you really wanted it in an NSArray finally
NSArray *fooChars = [NSArray arrayWithArray:characters];
Be sure to care about that some characters like emoji and others may span a longer range than just one index.
Here's a category method for NSString
#implementation (SplitString)
- (NSArray *)splitString
{
NSUInteger index = 0;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.length];
while (index < self.length) {
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
NSString *substring = [self substringWithRange:range];
[array addObject:substring];
index = range.location + range.length;
}
return array;
}
#end
convert it to NSData the [data bytes] will have a C string in the encoding that you pick [data length] bytes long.
Try this
NSMutableArray *array = [NSMutableArray array];
NSString *str = #"Hello";
for (int i = 0; i < [str length]; i++) {
NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
[array addObject:ch];
}

How to exclude previously randomly selected NSArrays in loop

I'm new to Objective-C and I'm trying to create a simple dictionary style app for personal use. Right now I'm attempting to make a loop that prints randomly selected NSArrays that have been added to an NSDictionary. I'd like to print each array only once. Here is the code I'm working with:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
...
NSInteger keyCount = [[wordDictionary allKeys] count];
NSInteger randomKeyIndex = arc4random() % keyCount;
int i = keyCount;
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
}
This code prints the same array "i" times. Any pointers on how to exclude previously printed arrays from being printed again?
I'm wondering if removeObjectForKey: could be of any use.
You just need to re-calculate the random key index every time you go through the loop, and then, as you suggest, use removeObjectForKey:.
Something like this:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
//...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
//...
while ([wordDictionary count] > 0) {
NSInteger keyCount = [wordDictionary count];
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
[wordDictionary removeObjectForKey: randomKey];
}
In your code, you generate a random randomKeyIndex, then use it without changing its value i times in the loop. So you get i times the same array.
NSInteger randomKeyIndex = arc4random() % keyCount;
// ...
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
// ...
}
As you say removeObjectForKey is an option for you, you can change your code into something like this:
NSInteger keyCount = [[wordDictionary allKeys] count];
for (i=keyCount; i>0; i--) {
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
[wordDictionary removeObjectForKey:randomKey];
keyCount--;
NSLog(#"%#", randomlySelectedArray);
}

Objective-C: Count the number of times an object occurs in an array?

I need to perform what I feel is a basic function but I can't find any documentation on how to do it. Please help!
I need to count how many times a certain object occurs in an array. See example:
array = NSArray arrayWithObjects:#"Apple", #"Banana", #"Cantaloupe", #"Apple", #"DragonFruit", #"Eggplant", #"Apple", #"Apple", #"Guava",nil]retain];
How can I iterate through the array and count the number of times it finds the string #"Apple"?
Any help is appreciated!
One more solution, using blocks (working example):
NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:#"Apple"];}] count];
NSLog(#"%d",occurrences);
As #bbum said, use an NSCounted set. There is an initializer thet will convert an array directly into a counted set:
NSArray *array = [[NSArray alloc] initWithObjects:#"A", #"B", #"X", #"B", #"C", #"D", #"B", #"E", #"M", #"X", nil];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSLog(#"%#", countedSet);
NSLog output:
(D [1], M [1], E [1], A [1], B [3], X [2], C [1])
Just access items:
count = [countedSet countForObject: anObj]; ...
A Simple and specific answer:
int occurrences = 0;
for(NSString *string in array){
occurrences += ([string isEqualToString:#"Apple"]?1:0); //certain object is #"Apple"
}
NSLog(#"number of occurences %d", occurrences);
PS: Martin Babacaev's answer is quite good too. Iteration is faster with blocks but in this specific case with so few elements I guess there is no apparent gain. I would use that though :)
Use an NSCountedSet; it'll be faster than a dictionary and is designed to solve exactly that problem.
NSCountedSet *cs = [NSCountedSet new];
for(id anObj in someArray)
[cs addObject: anObj];
// then, you can access counts like this:
.... count = [cs countForObject: anObj]; ...
[cs release];
Just came across this pretty old question. I'd recommend using a NSCountedSet:
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSLog(#"Occurrences of Apple: %u", [countedSet countForObject:#"Apple"]);
I would encourage you to put them into a Dictionary (Objective C's version of a map). The key to the dictionary is the object and the value should be the count. It should be a MutableDictionary of course. If the item is not found, add it and set the count to 1.
- (int) numberOfOccurrencesForString:(NSString*)needle inArray:(NSArray*)haystack {
int count = 0;
for(NSString *str in haystack) {
if([str isEqualToString:needle]) {
count++;
}
}
return count;
}
I up-voted Rob's answer, but I wanted to add some code that I hope will be of some assistance.
NSArray *array = [[NSArray alloc] initWithObjects:#"A", #"B", #"B", #"B", #"C", #"D", #"E", #"M", #"X", #"X", nil];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
for(int i=0; i < [array count]; i++) {
NSString *s = [array objectAtIndex:i];
if (![dictionary objectForKey:s]) {
[dictionary setObject:[NSNumber numberWithInt:1] forKey:s];
} else {
[dictionary setObject:[NSNumber numberWithInt:[dictionary objectForKey:s] intValue]+1 forKey:s];
}
}
for(NSString *k in [dictionary keyEnumerator]) {
NSNumber *number = [dictionary objectForKey:k];
NSLog(#"Value of %#:%d", k, [number intValue]);
}
If the array is sorted as in the problem statement then you don't need to use a dictionary.
You can find the number of unique elements more efficiently by just doing 1 linear sweep and incrementing a counter when you see 2 consecutive elements being the same.
The dictionary solution is O(nlog(n)), while the linear solution is O(n).
Here's some pseudo-code for the linear solution:
array = A,B,B,B,B,C,C,D,E,M,X,X #original array
array = array + -1 # array with a dummy sentinel value to avoid testing corner cases.
# Start with the first element. You want to add some error checking here if array is empty.
last = array[0]
count = 1 # you have seen 1 element 'last' so far in the array.
for e in array[1..]: # go through all the elements starting from the 2nd one onwards
if e != last: # if you see a new element then reset the count
print "There are " + count + " " + last elements
count = 1 # unique element count
else:
count += 1
last = e
the complete code with reference to #bbum and #Zaph
NSArray *myArray = [[NSArray alloc] initWithObjects:#"A", #"B", #"X", #"B", #"C", #"D", #"B", #"E", #"M", #"X", nil];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:myArray];
for (NSString *item in countedSet) {
int count = [countedSet countForObject: item];
NSLog(#"the String ' %# ' appears %d times in the array",item,count);
}
Thank you.
If you want it more generic, or you want to count equals/different objects in array, try this:
Sign "!" count DIFFERENT values. If you want SAME values, remove "!"
int count = 0;
NSString *wordToCheck = [NSString string];
for (NSString *str in myArray) {
if( ![str isEqualToString:wordToCheck] ) {
wordToCheck = str;
count++;
}
}
hope this helps the community!
I've used it to add correct number of sections in uitableview!
You can do this way,
NSArray *array = [[NSArray alloc] initWithObjects:#"A", #"B", #"X", #"B", #"C", #"D", #"B", #"E", #"M", #"X", nil];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:array];
NSArray *uniqueStates = [[orderedSet set] allObjects];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
for(int i=0;i<[uniqueStates count];i++){
NSLog(#"%# %d",[uniqueStates objectAtIndex:i], [countedSet countForObject: [uniqueStates objectAtIndex:i]]);
}
The result is like : A 1

finding a number in array

I have an Array {-1,0,1,2,3,4...}
I am trying to find whether an element exist in these number or not, code is not working
NSInteger ind = [favArray indexOfObject:[NSNumber numberWithInt:3]];
in ind i am always getting 2147483647
I am filling my array like this
//Loading favArray from favs.plist
NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:#"favs" ofType:#"plist"];
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath];
NSString *favString = [favPlistDict objectForKey:#"list"];
NSArray *favList = [favString componentsSeparatedByString:#","];
//int n = [[favList objectAtIndex:0] intValue];
favArray = [[NSMutableArray alloc] initWithCapacity:100];
if([favList count]>1)
{
for(int i=1; i<[favList count]; i++)
{
NSNumber *f = [favList objectAtIndex:i];
[favArray insertObject:f atIndex:(i-1)];
}
}
That's the value of NSNotFound, which means that favArray contains no object that isEqual: to [NSNumber numberWithInt:3]. Check your array.
After second edit:
Your favList array is filled with NSString objects. You should convert the string objects to NSNumber objects before inserting them in favArray:
NSNumber *f = [NSNumber numberWithInt:[[favList objectAtIndex:i] intValue]];

how to copy array?

I have four arrays as follows:
toArray = [[NSMutableArray alloc] initWithObjects:#"to 1",#"to 2",#"to 3",#"to 4",#"to 5",#"to 6",#"to 7",nil];
fromArray = [[NSMutableArray alloc] initWithObjects:#"from 1",#"from 2",#"from 3",#"from 4",#"from 5",#"from 6",#"from 7",nil];
messageArray = [[NSMutableArray alloc] initWithObjects:#"message 1",#"message 2",#"message 3",#"message 4",#"message 5",#"message 6",#"message 7",nil];
dayArray = [[NSMutableArray alloc] initWithObjects:#"day 1",#"day 2",#"day 3",#"day 4",#"day 5",#"day 6",#"day 7",nil];
I want to copy or create a single array which should contain all these 4 arrays.
How can i achieve it?
Your question is a little ambiguous; how do you want the result?
NSMutableArray *completeArray = [NSMutableArray array];
[completeArray addObjectsFromArray:toArray];
[completeArray addObjectsFromArray:fromArray];
[completeArray addObjectsFromArray:messageArray];
[completeArray addObjectsFromArray:dayArray];
Or
NSMutableArray *completeArray = [NSMutableArray arrayWithObjects:toArray, fromArray, messageArray, dayArray, nil];
Or if all arrays have the same number of elements:
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSString *fullString = [NSString stringWithFormat:#"%# %# %# %#", [toArray objectAtIndex:i], [fromArray objectAtIndex:i], [messageArray objectAtIndex:i], [dayArray objectAtIndex:i]];
[completeArray addObject:fullString];
}
Or, as an array of dictionaries (also assuming all arrays are same length):
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[toArray objectAtIndex:i], #"to",
[fromArray objectAtIndex:i], #"from",
[messageArray objectAtIndex:i], #"message",
[dayArray objectAtIndex:i], #"day",
nil];
[completeArray addObject:dict];
}
This should work:
NSArray *singleArray = [NSArray arrayWithElements:toArray, fromArray, messsageArray, dayArray, nil];
// mind the nil element at the end
NSMutableArray *result = [NSMutableArray arrayWithCapacity:0];
[result addObjectsFromArray:toArray];
[result addObjectsFromArray:fromArray];
[result addObjectsFromArray:messageArray];
[result addObjectsFromArray:dayArray];