Thread 1: signal sigabrt error - objective-c

Why do I get the thread error on the NSLog(#"%#", numbers[i]); line?
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSMutableArray *numbers = [NSMutableArray array];
int i;
//Create an arry with the number 0-9
for (i = 0; i < 10; ++i) {
numbers[i] = #(i);
//Sequence through the array and display the values
for (i = 0; i < 10; ++i) {
NSLog(#"%#", numbers[i]);
//Look how NSLog can display it with a singe %# format
NSLog(#"====== Using a single NSLog");
NSLog(#"%#", numbers);
}
}
}
return 0;
}

You're receiving an exception because you have your two for loops nested, and the inner one is trying to iterate through ten values in numbers array, but trying to do that before you've done populating the array in the outer loop.
I presume you do not want those for loops nested:
NSMutableArray *numbers = [NSMutableArray array];
int i;
//Create an array with the number 0-9
for (i = 0; i < 10; ++i)
numbers[i] = #(i);
//Sequence through the array and display the values
for (i = 0; i < 10; ++i)
NSLog(#"%#", numbers[i]);
//Look how NSLog can display it with a single %# format
NSLog(#"====== Using a single NSLog");
NSLog(#"%#", numbers);

Related

Algorithm to find all possible solutions from an array of array

What is the best algorithm to find all possible words from an array of array of character.
Here an example :
From this array : [[A],[B,C,D],[E,F],[G,H]]
I need in return an array of the 12 ordered possibilities [[A,B,E,G],[A,C,E,G], ... , [A,D,F,H]]
Do you know how to implement this algorithm ? If you know it and you provide an example in any language (C,JAVA,Javascript, ...), feel free to share because it's been a day I try to find it ...
Here how I tries to implement it ("array" is an array of array of char):
+ (NSArray*) possibleReading:(NSMutableArray*)array {
int nbPossibilities = 1;
for(int i = 0; i < [array count]; i++) {
nbPossibilities *=[[array objectAtIndex:i] count];
}
NSMutableArray *possArr = [[NSMutableArray alloc] initWithCapacity:nbPossibilities];
for (int i=0; i < nbPossibilities; i++) {
NSMutableArray *innerArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
[possArr addObject:innerArray];
}
for (int i=0; i< [array count]; i++) {
//
for(int nbPoss = 0; nbPoss < nbPossibilities; nbPoss++) {
NSMutableArray * arr = [possArr objectAtIndex:nbPoss];
NSNumber * num = [NSNumber numberWithInt:nbPoss % [[array objectAtIndex:i] count]];
NSString * literal = [[array objectAtIndex:i] objectAtIndex:[num intValue]];
[arr insertObject:literal atIndex:i];
}
}
return possArr;
}
It would be easiest to do this using a recursive method.
Java code
import java.util.Arrays;
public class CartesianProductCalculator {
private char[][] result;
private char[][] sets;
private char[] currentSet;
private int index;
public char[][] calculateProduct(char[][] sets) {
index = 0;
// calculate size of result
int resultSize = 1;
this.sets = sets;
for (char[] set : sets) {
resultSize *= set.length;
}
result = new char[resultSize][];
currentSet = new char[sets.length];
calculateProduct(sets.length-1);
return result;
}
// fills result from right to left
public void calculateProduct(int setIndex) {
if (setIndex >= 0) {
for (char c : sets[setIndex]) {
currentSet[setIndex] = c;
calculateProduct(setIndex-1);
}
} else {
result[index++] = Arrays.copyOf(currentSet, currentSet.length);
}
}
public static void main(String[] args) {
char[][] input = {{'A'},{'B','C','D'},{'E','F'},{'G','H'}};
CartesianProductCalculator productCalculator = new CartesianProductCalculator();
System.out.println(Arrays.deepToString(productCalculator.calculateProduct(input)));
}
}
Objectiv-C
+ (NSArray *) cartesianProductOfArrays(NSArray *arrays) {
int arraysCount = arrays.count;
unsigned long resultSize = 1;
for (NSArray *array in arrays)
resultSize *= array.count;
NSMutableArray *product = [NSMutableArray arrayWithCapacity:resultSize];
for (unsigned long i = 0; i < resultSize; ++i) {
NSMutableArray *cross = [NSMutableArray arrayWithCapacity:arraysCount];
[product addObject:cross];
unsigned long n = i;
for (NSArray *array in arrays) {
[cross addObject:[array objectAtIndex:n % array.count]];
n /= array.count;
}
}
return product;
}
C
#include <stdio.h>
#include <string.h>
void print(int size, char *array[size], int indexs[size]){
char result[size+1];
int i;
for(i = 0; i < size; ++i)
result[i] = array[i][indexs[i]];
result[size] = 0;
puts(result);
}
int countUp(int size, int indexs[size], int lens[size]){
int i = size -1;
while(i >= 0){
indexs[i] += 1;// count up
if(indexs[i] == lens[i])
indexs[i--] = 0;
else
break;
}
return i >= 0;
}
void find_all(int size, char *array[size]){
int lens[size];
int indexs[size];
int i;
for(i = 0; i < size; ++i){//initialize
lens[i] = strlen(array[i]);
indexs[i] = 0;
}
do{
print(size, array, indexs);
}while(countUp(size, indexs, lens));
}
int main(void){
char *array[] = { "A", "BCD", "EF", "GH" };
int size = sizeof(array)/sizeof(*array);
find_all(size, array);
return 0;
}
If you can remove duplicate entries in inner array objects before executing method then you won't get duplicate words in result array.
- (NSArray*) possibleReading:(NSMutableArray*)array {
int nbPossibilities = 1;
for(int i = 0; i < [array count]; i++)
{
NSArray *cleanedArray = [[NSSet setWithArray:[array objectAtIndex:i]] allObjects];
[array replaceObjectAtIndex:i withObject:cleanedArray];
nbPossibilities *=[[array objectAtIndex:i] count];
}
NSMutableArray *possArr = [[NSMutableArray alloc] initWithCapacity:nbPossibilities];
for (int i=0; i < nbPossibilities; i++) {
NSMutableArray *innerArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
[possArr addObject:innerArray];
}
for (int i=0; i< [array count]; i++) {
//
for(int nbPoss = 0; nbPoss < nbPossibilities; nbPoss++) {
NSMutableArray * arr = [possArr objectAtIndex:nbPoss];
NSNumber * num = [NSNumber numberWithInt:nbPoss % [[array objectAtIndex:i] count]];
NSString * literal = [[array objectAtIndex:i] objectAtIndex:[num intValue]];
[arr insertObject:literal atIndex:i];
}
}
return possArr;
}

How to send values to Ivar in method

new to Objective-C and keeping it very very simple I'm looking to understand one thing at a time... I set up a very simple class called student all it does is add two numbers trying to see how things pass into and back from methods) **I rewrote the code ==>> look at end to see the version that works **
If I have a method that has
#property (nonatomic) int firstNum;
#property (nonatomic) int secondNum;
and I have an instance of my class called student I assign a value to firstNum like student.firstNum = 100; student.secondNum = 77; that is easy and the method adds them and sends the sum in a return
But in main I tried assigning it from an array and it did not work I tried
student.firstNum = [myIntegers objectAtIndex:0];
and
student.firstNum = [myIntegers objectAtIndex:i]; //using a for loop with i index
it says incompatible pointer to integer conversion
Here is the snippet from main I tried it's not complete it just is trying to set firstNum eventually I will also set up secondNum and send each pair to the method to get added together but for now I am stuck trying to get the firstNum assigned the value in myIntegers[i] to start
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]]; // this works up to here
student.firstNum = [myIntegers objectAtIndex:i]; // this does not work
}
I also tried [i].
Here is my method:
- (int)addNumbers {
int sum = self.firstNum + self.secondNum;
return sum;
}
HERE IS WHAT WORKS : assuming I have a student object
.m
(long)addNumbers:(NSNumber *)x :(NSNumber *)y {
long sum;
sum = [x integerValue] + [y integerValue];
return sum;
}
main
NSMutableArray *myIntegers1 = [NSMutableArray array];
NSMutableArray *myIntegers2 = [NSMutableArray array];
for (NSInteger i= 0; i <40; i++) {
[myIntegers1 addObject:[NSNumber numberWithInteger:i]];
[myIntegers2 addObject:[NSNumber numberWithInteger:i]];
long sum = [student addNumbers:[myIntegers1 objectAtIndex:i] :[myIntegers2 objectAtIndex:i]];
NSLog(#" The sum is %ld", sum);
}
You are creating a properties of type int, but in your for loop, you are trying to assign them an NSNumber.
NSNumber is a simple container for a c data item and can hold int, float, char, bool, etc.
Change your loop to be like that:
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]];
student.firstNum = [[myIntegers objectAtIndex:i] intValue]; // this 'extracts' the int value from the NSNumber
}

NSMutableArray with random strings

How can I get 5 random strings in array? I tried this:
stringsArray = [[NSMutableArray alloc]init];
int string_lenght = 10;
NSString *symbols = #"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";
NSMutableString *randomString = [NSMutableString stringWithCapacity:string_lenght];
for (int y = 0; y<5; y++) {
for (int i = 0; i<string_lenght; i++) {
[randomString appendFormat:#"%C", [symbols characterAtIndex:random()%[symbols length]]];
}
stringsArray = [NSMutableArray arrayWithObject:randomString];
}
But after I run this, all I have is one long random string!
You almost had it. I think this should work, but I haven't tested it.
stringsArray = [[NSMutableArray alloc] init];
int string_length = 10;
NSString *symbols = #"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";
for (int y = 0; y < 5; y++)
{
//Allocate a new "randomString" object each time, or you'll just add to the old one
NSMutableString *randomString = [NSMutableString stringWithCapacity:string_length];
for (int i = 0; i < string_length; i++)
{
char c = [symbols characterAtIndex:random() % [symbols length]];
[randomString appendFormat:#"%c", c];
}
//Add the object to the array instead of replacing the entire array
[stringsArray addObject:randomString];
}
you are setting the strings array each time, change
stringsArray = [NSMutableArray arrayWithObject:randomString];
to
[stringsArray addObject:randomString];
and you should move the randomString initialisation into the for loop, or you will be appending new random characters to the same string

Converting NSArray to char** and returning the c array

I need to convert an NSarray filled with NSStrings and return this c array to the function.
-(char**) getArray{
int count = [a_array count];
char** array = calloc(count, sizeof(char*));
for(int i = 0; i < count; i++)
{
array[i] = [[a_array objectAtIndex:i] UTF8String];
}
return array;
}
I have this code, but when should i free the memory if I'm returning stuff?
You need to allocate memory for each string in the array as well. strdup() would work for this. You also need to add a NULL to the end of the array, so you know where it ends:
- (char**)getArray
{
unsigned count = [a_array count];
char **array = (char **)malloc((count + 1) * sizeof(char*));
for (unsigned i = 0; i < count; i++)
{
array[i] = strdup([[a_array objectAtIndex:i] UTF8String]);
}
array[count] = NULL;
return array;
}
To free the array, you can use:
- (void)freeArray:(char **)array
{
if (array != NULL)
{
for (unsigned index = 0; array[index] != NULL; index++)
{
free(array[index]);
}
free(array);
}
}
array you return will be caught in some char** identifier in calling environment of getArray() function using that you can free the memory which you have allocated using calloc() inside getArray() function
int main()
{
char **a=getArray();
//use a as your requirement
free(a);
}

Randomly select x amount of items in a "list"

I would like to select x amount of items randomly from a "list" in objective C store them in an other "list" (each item can only be selected one) , I'm talking about lists because I'm coming from Python. What would be the best way to store a list of strings in Objective C ?
cheers,
You should use NSMutableArray class for changeable arrays or NSArray for non-changeable ones.
UPDATE: a piece of code for selecting a number of items from an array randomly:
NSMutableArray *sourceArray = [NSMutableArray array];
NSMutableArray *newArray = [NSMutableArray array];
int sourceCount = 10;
//fill sourceArray with some elements
for(int i = 0; i < sourceCount; i++) {
[sourceArray addObject:[NSString stringWithFormat:#"Element %d", i+1]];
}
//and the magic begins here :)
int newArrayCount = 5;
NSMutableIndexSet *randomIndexes = [NSMutableIndexSet indexSet]; //to trace new random indexes
for (int i = 0; i < newArrayCount; i++) {
int newRandomIndex = arc4random() % sourceCount;
int j = 0; //use j in order to not rich infinite cycle
//tracing that all new indeces are unique
while ([randomIndexes containsIndex:newRandomIndex] || j >= newArrayCount) {
newRandomIndex = arc4random() % sourceCount;
j++;
}
if (j >= newArrayCount) {
break;
}
[randomIndexes addIndex:newRandomIndex];
[newArray addObject:[sourceArray objectAtIndex:newRandomIndex]];
}
NSLog(#"OLD: %#", sourceArray);
NSLog(#"NEW: %#", newArray);