Need to sort 3 arrays by one key array - objective-c

I am trying to get 3 arrays sorted by one key array in objective c for the iphone, here is a example to help out...
Array 1 Array 2 Array 3 Array 4
1 15 21 7
3 12 8 9
6 7 8 0
2 3 4 8
When sorted i want this to look like
Array 1 Array 2 Array 3 Array 4
1 15 21 7
2 3 4 8
3 12 8 9
6 7 8 0
So array 2,3,4 are moving with Array 1 when sorted.
Currently i am using a bubble sort to do this but it lags so bad that it crashes by app.
The code i am using to do this is
int flag = 0;
int i = 0;
int temp = 0;
do
{
flag=1;
for(i = 0; i < distancenumber; i++)
{
if(distance[i] > distance[i+1])
{
temp = distance[i];
distance[i]=distance[i + 1];
distance[i + 1]=temp;
temp = FlowerarrayNumber[i];
FlowerarrayNumber[i] = FlowerarrayNumber[i+1];
FlowerarrayNumber[i + 1] = temp;
temp = BeearrayNumber[i];
BeearrayNumber[i] = BeearrayNumber[i + 1];
BeearrayNumber[i + 1] = temp;
flag=0;
}
}
}while (flag==0);
where distance number is the amount of elements in all of the arrays, distance is array 1 or my key array.
and the other 2 are getting sorted.
If anyone can help me get a merge sort(or something faster, it is running on a iPhone so it needs to be quick and light) to do this that would be great i cannot figure out how the recursion works in this method and so having a hard time to get the code to work.
Any help would be greatly appreciated

Can't you simply structure your array to have A array that each item holds a array ?
Then simply sort your array based on the first item of the array it holds, or have a simple struct that holds an item and also the array.

I'm just thinking out loud here, but if all of your arrays correspond with each other (that is, BeearrayNumber[x] corresponds with FlowerarrayNumber[x], which corresponds with distance[x]), then you could consider using an array of structures rather than independent arrays. For example:
typedef struct
{
int flowerNumber;
int beeNumber;
float distance;
} BeeFlowerData;
#define MAX_BEE_FLOWER_DATA (100)
BeeFlowerData allBeeFlowers[MAX_BEE_FLOWER_DATA];
Then, you can sort using POSIX qsort:
int BeeFlowerComparator(const void *l, const void *r)
{
const BeeFlowerData *left = l;
const BeeFlowerData *right = r;
if (left->distance > right->distance)
return 1;
else if (left->distance < right->distance)
return -1;
else
return 0;
}
// somewhere in your class:
- (void) sort
{
qsort (allBeeFlowers, MAX_BEE_FLOWER_DATA, sizeof(BeeFlowerData), BeeFlowerComparator);
}

I can't believe no one has suggested wrapping them in an object yet. It's fairly trivial:
//MyObject.h
#interface MyObject : NSObject {
int a;
int b;
int c;
int d;
}
#property int a;
#property int b;
#property int c;
#property int d;
#end
//MyObject.m
#implementation MyObject
#synthesize a, b, c, d;
#end
//Elsewhere:
MyObject * m = [[MyObject alloc] init];
[m setA:1];
[m setB:15];
[m setC:21];
[m setD:7];
[myMutableArray addObject:m];
[m release];
//... do that for the rest of the sets of numbers
NSSortDescriptor * sortByA = [NSSortDescriptor sortDescriptorWithKey:#"a" ascending:YES];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByA]];
When you do that, you'll have one array, but the objects in that array will be sorted by their "a" value in ascending order.

This is not a objective c specific question. This is an algorithmic question.
First sort the first array.
Loop through the first array and find the index for each number.
Then retrieve the value in second array corresponding to the index in step 2.
construct a new array that holds the results in step 3.
Repeat step 2,3,4 for the other arrays as well.

Related

Rotate left elements in an array with complexity O(n) and time O(1)

I am trying to solve the problem of rotating elements inside an array to the left. Example: array = [1,2,3,4,5,6,7] if I call the function rotateToLeft(array[],int numberElements,int count) where: array is the array to rotate, numberElements is the number of elements to rotate to the left and count is the size of the array. I am looking for a O(n) complexity and O(1) time consuming algorithm. My first solution is to use a doubly linked list, but I would like to know if there is a better solution.
Class Node of the linkedlist
#interface Node : NSObject
#property (nonatomic,assign) int element;
#property (nonatomic,strong) Node* next;
#property (nonatomic,strong) Node* previous;
#end
Class to manage the linkedlist
#interface LinkedList : NSObject
#property (nonatomic,strong) Node* tail;
#property (nonatomic,strong) Node* root;
-(void)addNode:(int)value;
-(void)printList;
-(void)rotateLeftElementsOnList:(LinkedList*)list elements:(int)numElement;
#end
#implementation LinkedList
-(instancetype)init{
self = [super init];
if (self) {
self.tail = nil;
}
return self;
}
-(void)addNode:(int)value{
Node* newNode = [[Node alloc] init];
newNode.element = value;
newNode.previous = nil;
newNode.next = nil;
if (self.tail == nil) {
newNode.next = nil;
newNode.previous = nil;
self.tail = newNode;
self.root = newNode;
return;
}
self.tail.previous = newNode;
newNode.next = self.tail;
self.tail = newNode;
}
-(void)printList{
Node* header = self.root;
while(header.previous != nil){
NSLog(#"%d",header.element);
header = header.previous;
}
NSLog(#"%d",header.element);
}
/////This is my function to rotate elements an it works but I would like to know if some one knows a better solution,
-(void)rotateLeftElementsOnList:(LinkedList*)list elements:(int)numElement{
Node* header = self.root;
int index = 0;
while(index < numElement){
header = header.previous;
index++;
}
header.next.previous = nil;
header.next = nil;
self.root.next = self.tail;
self.tail.previous = self.root;
self.root = header;
}
A linked list is an O(n) derivative of an array. So that's the floor on this idea. If you're ok transforming to a list, transform to one that's a ring, with the last node's next pointer pointing to the head. Keep track of just a head pointer. With that, a shift can be accomplished simply by advancing the head pointer.
I don't know Objective-C, so unfortunately, I can't provide you the code snippet; but I'll explain you the logic:
Reverse the first count number of elements;
Reverse the remaining elements;
Reverse the entire array now.
Example:
Array is: [1 2 3 4 5 6 7 8] and you want to shift by, say, 3 places:
Step 1: [3 2 1 4 5 6 7 8]
Step 2: [3 2 1 8 7 6 5 4]
Step 3: [4 5 6 7 8 1 2 3]
The time complexity is O(n) since you just traverse the elements once to reverse them and the space complexity is O(1) since you are not using any additional auxiliary storage space. Hope this is helpful!
I don't know objective-c, so I can't offer you a code. But here is an idea. Instead of shifting the array, you can create a class, which will have 2 properties: a of type list/array and shift of type int. After that, you will have method get_element(int i) which will get the i-th element using the shift value. A pseudo code would look something like this:
class ShiftedArray:
int[] a
int shift
void shift_array(int positions):
shift = positions
int get_element(int i):
return a[(n + i - shift % n) % n]

Get sequence of random numbers' pairs (Objective-c)

Good morning, i'm trying to generate a sequence of N pairs of numbers, for example 1-0, 2-4, 4-3. These numbers must range between 0 and 8 and the pair must be different for all the numbers.
I don't want that: 1-3 1-3
I found that if a and b are the numbers, (a+b)+(a-b) has to be different for all couples of numbers.
So I manage to do that, but the loop never ends.
Would you please correct my code or write me another one? I need it as soon as possible.
NSNumber*number1;
int risultato;
int riga;
int colonna;
NSMutableArray*array=[NSMutableArray array];
NSMutableArray*righe=[NSMutableArray array];
NSMutableArray*colonne=[NSMutableArray array];
for(int i=0; i<27; i++)
{
riga=arc4random()%9;
colonna=arc4random()%9;
risultato=(riga+colonna)+(riga-colonna);
number1=[NSNumber numberWithInt:risultato];
while([array containsObject:number1])
{
riga=arc4random()%9;
colonna=arc4random()%9;
risultato=(riga+colonna)+(riga-colonna);
number1=[NSNumber numberWithInt:risultato];
}
NSNumber*row=[NSNumber numberWithBool:riga];
NSNumber*column=[NSNumber numberWithInt:colonna];
[righe addObject:row];
[colonne addObject:column];
[array addObject:number1];
}
for(int i=0; i<27; i++)
{
NSNumber*one=[righe objectAtIndex:i];
NSNumber*two=[colonne objectAtIndex:i];
NSLog(#"VALUE1 %ld VALUE2 %ld", [one integerValue], (long)[two integerValue]);
}
edit:
I have two arrays (righe, colonne) and I want them to have 27 elements [0-8].
I want to obtain a sequence like it:
righe: 1 2 4 6 7 8 2 3 4 8 8 7
colonne: 1 3 4 4 2 1 5 2 7 6 5 6
I don't want to have that:
righe: 1 2 4 6 2
colonne: 1 3 5 2 3
Where you see that 2-3 is repeated once. Then I'd like to store these values in a primitive 2d array (array[2][27])
I found that if a and b are the numbers, (a+b)+(a-b) has to be different for all couples of numbers.
This is just 2 * a and is not a valid test.
What you are looking for are pairs of digits between 0 - 8, giving a total of 81 possible combinations.
Consider: Numbers written in base 9 (as opposed to the common bases of 2, 10 or 16) use the digits 0 - 8, and if you express the decimal numbers 0 -> 80 in base 9 you will get 0 -> 88 going through all the combinations of 0 - 8 for each digit.
Given that you can can restate your problem as requiring to generate 27 numbers in the range 0 - 80 decimal, no duplicates, and expressing the resultant numbers in base 9. You can extract the "digits" of your number using integer division (/ 9) and modulus (% 9)
To perform the duplicate test you can simply use an array of 81 boolean values: false - number not used, true - number used. For collisions you can just seek through the array (wrapping around) till you find an unused number.
Then I'd like to store these values in a primitive 2d array (array[2][27])
If that is the case just store the numbers directly into such an array, using NSMutableArray is pointless.
So after that long explanation, the really short code:
int pairs[2][27];
bool used[81]; // for the collision testing
// set used to all false
memset(used, false, sizeof(used));
for(int ix = 0; ix < 27; ix++)
{
// get a random number
int candidate = arc4random_uniform(81);
// make sure we haven't used this one yet
while(used[candidate]) candidate = (candidate + 1) % 81;
// record
pairs[0][ix] = candidate / 9;
pairs[1][ix] = candidate % 9;
// mark as used
used[candidate] = true;
}
HTH
Your assumption about (a+b)+(a-b) is incorrect: this formula effectively equals 2*a, which is obviously not what you want. I suggest storing the numbers in a CGPoint struct and checking in a do...while loop if you already have the newly generated tuple in your array:
// this array will contain objects of type NSValue,
// since you can not store CGPoint structs in NSMutableArray directly
NSMutableArray* array = [NSMutableArray array];
for(int i=0; i<27; i++) {
// declare a new CGPoint struct
CGPoint newPoint;
do {
// generate values for the CGPoint x and y fields
newPoint = CGPointMake(arc4random_uniform(9), arc4random_uniform(9));
} while([array indexOfObjectPassingTest:^BOOL(NSValue* _Nonnull pointValue, NSUInteger idx, BOOL * _Nonnull stop) {
// here we retrieve CGPoint structs from the array one by one
CGPoint point = [pointValue CGPointValue];
// and check if one of them equals to our new point
return CGPointEqualToPoint(point, newPoint);
}] != NSNotFound);
// previous while loop would regenerate CGPoint structs until
// we have no match in the array, so now we are sure that
// newPoint has unique values, and we can store it in the array
[array addObject:[NSValue valueWithCGPoint:newPoint]];
}
for(int i=0; i<27; i++)
{
NSValue* value = array[i];
// array contains NSValue objects, so we must convert them
// back to CGPoint structs
CGPoint point = [value CGPointValue];
NSInteger one = point.x;
NSInteger two = point.y;
NSLog(#"VALUE1 %ld VALUE2 %ld", one, two);
}

Merge or Combine two different size arrays and filling gaps with 0

I have two arrays and I want to merge or combine, but first compare to see if similar values exist and then fill the gaps with 0, but must conserve first array order. like the example:
Array1: 1 2 3 4 5 6
Array2: 2 5
NewArray: 0 2 0 0 5 0
I read about combining arrays but not sure about how to replace missing rows with 0 and keeping same order of the first Array...
Assuming you want to store result in "result" array.
Objective-C version:
NSArray *arr1 = #[#1,#2,#3,#4,#5,#6];
NSArray *arr2 = #[#2,#5];
NSMutableArray *result = [NSMutableArray array];
for (NSNumber * item in arr1){
[arr2 containsObject: item] ? [result addObject:item] : [result addObject:#0];
}
Swift version:
let arr1 = [1,2,3,4,5,6]
let arr2 = [2,5]
let result = arr1.map { x -> Int in
return arr2.contains(x) ? x : 0
}

How to pick a smaller array from a larger array in objective C?

I need to pick 32 distinctive objects from an NSMutableArray of 75 objects. it can be 1 to 32, 2 to 33 or 10 to 42. What functions should i use to get the new array? Sorry for being noob.
If you want N consecutive objects from a random index, try the following:
NSArray *arrayWithNConsecutiveObjects(NSArray *arr, int n)
{
int subIdx = arc4random_uniform((unsigned) (arr.count - n));
return [arr subarrayWithRange:NSMakeRange(subIdx, n)];
}
If you need 32 random objects, you can extend this method to randomly sort the array:
NSArray *arrayWithNObjects(NSArray *arr, int n)
{
arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// random sort
return arc4random_uniform(3) - 1; // one of -1, 0, and 1
}];
int subIdx = arc4random_uniform((unsigned) (arr.count - n));
return [arr subarrayWithRange:NSMakeRange(subIdx, n)];
}
You can use the appropriate method inherited from NSArray to retrieve a slice of 32 consecutive elements:
int offset = 4;
NSArray *slice = [array subarrayWithRange:NSMakeRange(offset, offset+32)];

Sudoku generation in Objective-c

I am supposed to make an app that generates fully complete Sudoku puzzles. I can get the first row to generate properly with the following code, but, no matter what I do, I cannot get the next rows to work right. They all generate the right way in that I get the numbers 1-9 in a random order, but I cannot get it to make a workable Sudoku puzzle.
Code:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:8];
for (int integerA = 0; integerA < 10; integerA ++) {
[array addObject:[NSNumber numberWithInt:integerA]];
//NSLog(#"%i", (integerA + 1));
}
for (int x = 8; x >= 0; x --) {
[array exchangeObjectAtIndex:(arc4random() % (x + 1)) withObjectAtIndex:x];
section[x][0] = ([[array objectAtIndex:x] intValue] + 1);
for (int y = 8; y >= 0; y --) {
if (0) {
}
}
}
That part works. If I try to make another array and generate the "y" values for each "x" value, it goes all weird. Without numerous conditional statements, is there an efficient way to generate a fully solved Sudoku puzzle?
The "weird results":
2 0 1 | 2 3 3 | 5 2 2
7 0 3 | 2 1 5 | 1 4 4
2 0 1 | 0 3 4 | 6 7 3
- - - - - - - - - -
8 4 0 | 1 3 6 | 5 2 7
5 0 4 | 3 2 1 | 1 1 1
7 0 0 | 3 1 4 | 6 5 1
- - - - - - - - - -
2 7 0 | 5 6 3 | 4 1 8
7 6 1 | 1 3 2 | 5 0 5
0 1 1 | 2 3 5 | 0 1 5
The problem of find a correct Sudoku scheme is a very common homework and it has many different solutions.
I will not provide you the code, but let me give you some suggestions: as you certainly know, the aim is to generate a scheme that has non-repeating numbers in row, column and square.
This is, more basically, the problem of generating random non-repeating numbers.
The web is full of solutions for this problem, just a couple of examples here and here.
Now that we are able to generate non-repeating numbers, the problem is to fill the table.
There are many possible approaches: obviously you cannot avoid to check (in some way) that the current number appears only once per row, column, square.
The first solution that comes in my mind is a recursive procedure (let's call it int fill(int row)):
In a do-while loop (I'll explain later why) do this operations:
generate an array of random (this is to avoid that the algorithm generates always the same scheme) non-repeating numbers (from 1 to 9)
this is a possible candidate to become the row-esim row of your scheme. Of course, most of the case you will not be such lucky to have your row ready, so you have to check some conditions:
for each number in your array check if it's the first time it appears in column and in the square (you do not need to check in the row since you built an array of non-repeating numbers).
I will not explain further how to check since it's almost trivial.
If yes, copy it in your scheme and move it at the end of your array. This way, at the beginning of your array, you will always have non-used numbers.
If no, skip it and try the next one.
Be careful: you must keep the reference of the number of used numbers, otherwise you may use two times the same number in one row.
However, this way it is possible to arrive in a situation in which no number seems to fit your table. In this case, simply return 0
If, instead, you inserted all 9 numbers in the current row, call int chk = fill(row+1). Of course you must not call the recursive step if you reached the final row (row==9). In this case simply return 1.
chk will store the return value of the recursive step.
If chk==0 it means that the algorithm was not able to find a suitable row for the next level. In this case simply restart the initial do-while loop.
Otherwise the recursive step was successful, so you can return 1.
However, this is only a possible solutions. There are many others possible algorithms/variations. It's up to you to increase performance and do some optimization.
For sudoku generates we need to check only three - four step
Get row filled numbers array => rawArray.
Get Column filled numbers array => columnArray.
Get current cell's 3x3 grid array => cellArray.
Create array of 1-9 number (numberArray) and Remove numbers of above three array (rawArray , columnArray , cellArray)
finalArray = (numberArray) - (rawArray , columnArray , cellArray)
get random number from finalArray
and placed it to current cell
if any conflicted repeat step 1-5
bellow is code how to generate random sudoku
#import "ViewController.h"
#interface ViewController (){
NSMutableArray *field;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self genrateSudoku];
}
-(void)genrateSudoku{
[self fillEmptyGrid];
#autoreleasepool {
int n = 3;
BOOL flag=NO;
for (int i = 0; i < n*n; i++) {
for (int j = 0; j < n*n; j++){
if ([field[i][j] isEqualToString:#"_"]) {
if (![self fileValue:i and:j]) {
flag=YES;
break;
}
}else{
continue;
}
}
if (flag) {
break;
}
}
if (flag) {
[self genrateSudoku];
}else{
NSLog(#"field fill =%#",field);
}
}
}
-(void)fillEmptyGrid{
int n = 3;
field=[[NSMutableArray alloc]init];
for (int i = 0; i < n*n; i++) {
NSMutableArray *a=[[NSMutableArray alloc]init];
[field addObject:a];
for (int j = 0; j < n*n; j++){
[field[i] addObject:[NSString stringWithFormat:#"_"]];
}
}
}
-(BOOL)fileValue:(int)i and:(int)j{
NSMutableArray *rawArray=field[i];
NSMutableArray *cellArray=[self boxArray:i and:j];
NSMutableArray *columnArray=[self colArray:i and:j];
NSString *value =[self getRandomCol:columnArray rowA:rawArray box:cellArray];
if (value==nil) {
return NO;
}else{
field[i][j]=value;
return YES;
}
}
-(NSMutableArray *)boxArray:(int)i and:(int)j {
int x= (i<3)?0:((i<6)?3:6);
int y=(j<3)?0:((j<6)?3:6);
NSMutableArray *ar=[[NSMutableArray alloc]init];
for (int a=x; a<x+3; a++) {
for (int b=y; b<y+3; b++) {
[ar addObject:field[a][b]];
}
}
return ar;
}
-(NSMutableArray *)colArray:(int)i and:(int)j{
NSMutableArray *ar=[[NSMutableArray alloc]init];
for (int b=0; b<9; b++) {
[ar addObject:field[b][j]];
}
return ar;
}
-(NSString *)getRandomCol:(NSMutableArray *)col rowA:(NSMutableArray *)row box:(NSMutableArray *)box{
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9", nil];
[array removeObjectsInArray:row];
[array removeObjectsInArray:box];
[array removeObjectsInArray:col];
if (array.count>0) {
int x=arc4random()%array.count;
return array[x];
}
else{
return nil;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end