Get sequence of random numbers' pairs (Objective-c) - 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);
}

Related

Random Generator slightly less random

NSPredicate *predicate = [NSPredicate predicateWithFormat:#"category == %#", selectedCategory];
NSArray *filteredArray = [self.Quotes filteredArrayUsingPredicate:predicate];
// Get total number in filtered array
int array_tot = (int)[filteredArray count];
// As a safeguard only get quote when the array has rows in it
if (array_tot > 0) {
// Get random index
int index = (arc4random() % array_tot);
// Get the quote string for the index
NSString *quote = [[filteredArray objectAtIndex:index] valueForKey:#"quote"];
// Display quote
self.quote_text.text = quote;
// Update row to indicate that it has been displayed
int quote_array_tot = (int)[self.Quotes count];
NSString *quote1 = [[filteredArray objectAtIndex:index] valueForKey:#"quote"];
for (int x=0; x < quote_array_tot; x++) {
NSString *quote2 = [[Quotes objectAtIndex:x] valueForKey:#"quote"];
if ([quote1 isEqualToString:quote2]) {
NSMutableDictionary *itemAtIndex = (NSMutableDictionary *)[Quotes objectAtIndex:x];
[itemAtIndex setValue:#"DONE" forKey:#"source"];
}
}
Above is the code I use in my app for generating a random quote from one of two categories stored in a plist (in arrays, where the first line is category, and second is quote). However, it seems to have a preference of repeating ones it's already shown. I'd prefer it have a preference (but not exclusively) show ones it hasn't shown before.
Your question is an algorithm question. What you want is a sequence of numbers that seems random but is more uniform.
What you are looking for is called a low-discrepancy sequence. A simple form of this is a "shuffle bag", often used in game development, as described here or here.
With a shuffle bag, you basically generate all the indices (e.g. 0 1 2 3 4 5), shuffle them (e.g. 2 3 5 1 0 4) and then display the elements in this order. At the end, you generate another sequence (e.g. 4 1 0 2 3 5). Note that it is possible that the same element appears twice in the sequence, although it is rare. E.g. in this case, the "4" is a duplicate, because the full sequence is 2 3 5 1 0 4 4 1 0 2 3 5.
arc4random() is a good PRNG on Apple platforms, so it doesn't give you a "low discrepancy sequence". But: you can use it as a primitive to generate "low discrepancy sequences", you can also use it as a primitive to create a shuffle bag implementation.

UIButton with random text/value or tag [duplicate]

This question already has answers here:
iOS: How do I generate 8 unique random integers?
(6 answers)
Closed 9 years ago.
I have 10 UIButtons created in historyboard, OK?
I want to add random numbers that do not repeat these numbers, ie, numbers from 0 to 9 that interspersed whenever the View is loaded.
I tried to find on Google and here a way to use my existing buttons ( 10 UIButton ), and just apply them to random values​​. Most ways found ( arc4random() % 10 ), repeat the numbers.
Here's one
here's another
here's another
All results found that creating buttons dynamically. Anyone been through this?
Create an array of the numbers. Then perform a set of random swapping of elements in the array. You now have your unique numbers in random order.
- (NSArray *)generateRandomNumbers:(NSUInteger)count {
NSMutableArray *res = [NSMutableArray arrayWithCapacity:count];
// Populate with the numbers 1 .. count (never use a tag of 0)
for (NSUInteger i = 1; i <= count; i++) {
[res addObject:#(i)];
}
// Shuffle the values - the greater the number of shuffles, the more randomized
for (NSUInteger i = 0; i < count * 20; i++) {
NSUInteger x = arc4random_uniform(count);
NSUInteger y = arc4random_uniform(count);
[res exchangeObjectAtIndex:x withObjectAtIndex:y];
}
return res;
}
// Apply the tags to the buttons. This assumes you have 10 separate ivars for the 10 buttons
NSArray *randomNumbers = [self generateRandomNumbers:10];
button1.tag = [randomNumbers[0] integerValue];
button2.tag = [randomNumbers[1] integerValue];
...
button10.tag = [randomNumbers[9] integerValue];
#meth has the right idea. If you wanna make sure the numbers aren't repeating, try something like this: (note: top would the highest number to generate. Make sure this => amount or else this will loop forever and ever and ever ;)
- (NSArray*) makeNumbers: (NSInteger) amount withTopBound: (int) top
{
NSMutableArray* temp = [[NSMutableArray alloc] initWithCapacity: amount];
for (int i = 0; i < amount; i++)
{
// make random number
NSNumber* randomNum;
// flag to check duplicates
BOOL duplicate;
// check if randomNum is already in your array
do
{
duplicate = NO;
randomNum = [NSNumber numberWithInt: arc4random() % top];
for (NSNumber* currentNum in temp)
{
if ([randomNum isEqualToNumber: currentNum])
{
// now we'll try to make a new number on the next pass
duplicate = YES;
}
}
} while (duplicate)
[temp addObject: randomNum];
}
return temp;
}

Objective C - comparing values in an array to an arbritary

How would you sort through an array, which also contains 0 values i.e.
-54
0
-12
0
-10
and comparing it to a constant (say -5), which would return the index of the corresponding closest value (smallest difference) ? (i.e. closest value = -10, so returned value = 4)
The challenge here being 0 values should always be overlooked, and the array cannot be sorted before hand
Heres a Similar problem, answers for which doesn't quite work in my case
How do I find the closest array element to an arbitrary (non-member) number?
That is relatively straightforward:
NSArray *data = #[#-54, #0, #-12, #0, #-10];
NSUInteger best = 0;
int target = -5;
for (NSUInteger i = 1 ; i < data.count ; i++) {
int a = [[data objectAtIndex:best] intValue];
int b = [[data objectAtIndex:i] intValue];
if (b && abs(a-target) > abs(b-target)) { // Ignore zeros, check diff
best = i;
}
}
// At this point, "best" contains the index of the best match
NSLog(#"%lu",best); // Prints 4

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

Need to sort 3 arrays by one key array

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.