I've declared a static array of integer from 1 to 5 and now want to call randomly each number with each press of a button. I don't want the same number to be called twice.
int randomNumber;
static int size = 5;
int position = arc4random() % size - 1;
randomNumber = usedNumbers[position];
int switcher = usedNumbers[size]; // wrong
usedNumbers[position] = usedNumbers[size];
size--;
usedNumbers[position] = switcher;
Here's what I've done so far. There's a hole in my logic somewhere and I could do with some help. I think it's something to do with the switcher which is trying to hold a number whilst another is being deleted.
If all you want to do is to show a random number every time the button is clicked, here is some code that can help.
But first, the line you use to create the position is wrong. Do this instead:
int position = (arc4random() % 5) + 1; // Creates a random number between 1 and 5.
int position = (arc4random() % 5) - 1; // Creates a random number between -1 and 3.
Second, I'd suggest to use an NSArray or NSMutableArray to hold your data.
I assume that you have a method that is called when you press a button. Inside that method you can simply put something like this:
int size = 5; // You might want to get the size of your array dynamically, with something like [usedNumbers count];
int position = (arc4random() % size) + 1; // Generates a number between 1-5.
NSNumber *randomNumber = [usedNumbers objectAtIndex:position]; // Here is your random number from the array.
So.. If you add the array as an instance variable to your class, your header file would look something like this:
#interface MyViewController : UIViewController
#property (nonatomic, retain) NSMutableArray *usedNumbers;
- (IBAction)buttonWasClicked:(id)sender; // Remember to connect it to your button in Interface Builder.
#end
And your implementation file:
#implementation MyViewController
#synthesize usedNumbers;
- (void)viewDidLoad {
// Initialize your array and add the numbers.
usedNumbers = [[NSMutableArray alloc] init];
[usedNumbers addObject:[NSNumber numberWithInt:4]];
[usedNumbers addObject:[NSNumber numberWithInt:13]];
// Add as many numbers as you'd like.
}
- (IBAction)buttonWasClicked:(id)sender {
int size = [usedNumbers count];
int position = (arc4random() % size); // Generates a number between 0 and 4, instead of 1-5.
// This is because the indexes in the array starts at 0. So when you have 5 elements, the highest index is 4.
NSNumber *randomNumber = [usedNumbers objectAtIndex:position]; // The number chosen by the random index (position).
NSLog(#"Random position: %d", position);
NSLog(#"Number at that position: %#", randomNumber);
}
#end
If you do it like this, a random number will be chosen from the array every time the button is clicked.
Also, remember to release all your objects if you don't have ARC enabled.
PS: There are several other questions here on SO covering this subject. Remember to search before asking.
Update:
To make sure every number is used only once, you can remove it from your array when it is chosen. So the buttonWasClicked: method will be something like this:
- (IBAction)buttonWasClicked:(id)sender {
int size = [usedNumbers count];
if (size > 0) {
int position = (arc4random() % size);
NSNumber *randomNumber = [usedNumbers objectAtIndex:position];
// Do something with your number.
// Finally, remove it from the array:
[usedNumbers removeObjectAtIndex:position];
} else {
// The array is empty.
}
}
Related
I have the following code which works fine...
int testarr[3][3] = {
{1,1,1},
{1,0,1},
{1,1,1}
};
[self testCall: testarr];
Which calls this function:
- (void)testCall: (int[3][3]) arr {
NSLog(#"cell value is %u",arr[1][1]);
}
I need the array to be of variable length - What is the best way to declare the function?
Using blanks doesn't work:
- (void)testCall: (int[][]) arr {
Thanks for your help.
I would write this as:
- (void) testCall: (int *) aMatrice;
Doing so allows you to avoid multiple mallocs and the math to calculate a single offset in a linear array based on x, y coordinates in a 2D array is trivial. It also avoids the multiple mallocs implied by int** and the limitations of 2D array syntax perpetuated by the language.
So, if you wanted a 4x5 array, you might do:
#define WIDTH 4
#define HEIGHT 5
#define INDEXOF(x,y) ((y*WIDTH) + x)
int *myArray = malloc(sizeof(int) * 5 * ELEMS_PER_ROW);
You could then initialize the array linearly or with a nested for loop:
for(int x=0; x<width; x++)
for(int y=0; y<height; y++)
myArray[INDEXOF(x,y)] = ... some value ...;
And you would pass it to the method like:
[foo testCall: myArray];
Though you might want to also carry along the width and the height or, better yet, create a IntMatrix subclass of NSObject that wraps all of the pointer arithmetic and storage beyond a nice clean API.
(all code typed into SO)
C arrays can't be variable in more than one dimension.
You can't have this:
int testarr[][] = {
{1,1,1},
{1,0,1,2},
{1,1}
};
But you can have this:
int testarr[][3] = {
{1,1,1},
{1,0,1},
{1,1,1},
{4,5,6},
{7,8,9}
}
foo(testarr);
void foo(int param[][3])
{
printf("%d", param[3][1]); // prints 5
}
You can't use int[][] because the size of the second dimension affects how the array is laid out in memory. If you know the second dimension you can use int[][x], otherwise you'll have to use int** which can be accessed just like an array.
Why don't you just use NSArray or NSMutableArray with NSIntegers? Those array classes are of variable length, and much easier to use.
This would result in
- (void)testCall: (NSArray *) arr {
NSLog(#"cell value is %u", [[arr objectAtIndex:1] objectAtIndex:1]);
}
(Of course, you would also have to define testarr using NSArray.)
If you really want to use C arrays, making the method argument a pointer to an int with
- (void)testCall: (int*) arr {
will probably work (with the rest of the code staying the same).
call
int testarr[3][3] = {
{1,1,1},
{1,0,1},
{1,1,1}
};
[self testCall: (int *)testarr];
function
- (void)testCall: (int *) arr
{
int (*V_arr)[3] = (int(*)[3])arr;
NSLog(#"cell value is %u",V_arr[1][1]);
}
Does anyone know any efficient ways to check if any set of integers contains an integer that has changed by a certain amount.
For example I have:
int1 = 10;
int2 = 20;
int3 = 30;
And I want to know if any of these 3 integers change by 30
Now if int1 becomes 40 than the call should be triggered. At first I thought of just doing something like this.
if (abs((int1+int2+int3)-(newInt1+newInt2+newInt3)) >= 30) {
But many problems can arise from this...
False triggers (e.g. each new int value increases by 10, making the NET change greater than 30 but not necessarily any individual int greater than 30)
Untriggered reactions (e.g. one of the new integer values has increased by 50 so it should be called but then another new integer value is decreased by 50 (again, it should be called) but the net change is now zero because -50+50=0)
Does anyone have any efficient way of doing this? (Yes, I know obviously I could just check each value individually with OR statements...)
So far this is my best stab at it
if ((((abs(int1-newInt1))>=30)+((abs(int2-newInt2))>=30)+((abs(int3-newInt3))>=30))>0) {
But that's basically the same as using an OR statement (probably even takes a little longer than an OR statment.
I don't think that you can get any faster than that, and unless you're dealing with hundreds of millions of integers, this should not introduce a significant performance penalty.
However, you might want to be "clever". What if you somehow "checksum" the two sums? For example, multiply all the old and new numbers with the nth prime, then check if the difference of the new and old sum divided by the indexth prime is the amount you want.
int sum(int arr[], size_t n)
{
int n = 0;
for (int i = 0; i < n; i++)
n += primes[i] * arr[i];
return n;
}
int primes[3] = { 2, 3, 5 }; // or more
int olds[3] = { 10, 20, 30 };
int news[3] = { 40, 20, 30 };
int nth = 0; // check first
int change_expected = 30;
int oldsum = sum(olds, 3);
int newsum = sum(news, 3);
if ((newsum - oldsum) / primes[nth] == change_expected) {
// 1st value changed as expected
}
Note that this will take way more time and CPU cycles that your naive approach.
Since you are using objective-c, you can always create an object that does exactly what you want (see class below the example). The main benefit of doing it this way is that you don't have to check every integer every time one is set. You simply check each number as it is changed to see if it has changed too much.
Usage Example:
// myNumbers.confined will be true until you create a number, and THEN change it by 30 or more.
ARConfinedNumbers *myNumbers = [ARConfinedNumbers new];
[myNumbers addNumber:10];
[myNumbers addNumber:20];
[myNumbers addNumber:30];
[myNumbers replaceNumberAtIndex:0 withObject:40];
// No longer confined because we have changed 10 to 40
if (!myNumbers.confined)
NSLog(#"Not confined.");
// Reset
[myNumbers setConfined:YES];
Here is the class that I wrote to do this. Note that I used an NSArray, assuming that you were programming for iOS/MacOS but you can replace the NSArray with something else if you aren't using those classes. This should give you a great starting point though.
ARConfinedNumbers.h:
#import <Foundation/Foundation.h>
#interface ARConfinedNumbers : NSObject
// confined is true if the numbers have not been changed by more than 30.
// This can be reset by setting it to YES.
#property (nonatomic, assign) BOOL confined;
// Methods to manipulate the set of numbers
// Add more array-type-methods as needed
- (void)addNumber:(int)number;
- (void)replaceNumberAtIndex:(NSUInteger)index withObject:(int)number;
- (int)numberAtIndex:(NSUInteger)index;
- (NSUInteger)count;
#end
ARConfinedNumbers.m
#import "ARConfinedNumbers.h"
/* Private Methods */
#interface ARConfinedNumbers()
#property (nonatomic, strong) NSMutableArray *numbers;
#end
#implementation ARConfinedNumbers
- (id)init
{
self = [super init];
if (self)
{
_confined = YES;
_numbers = [NSMutableArray new];
}
return self;
}
- (void)addNumber:(int)number
{
[self.numbers addObject:#(number)];
}
- (void)replaceNumberAtIndex:(NSUInteger)index withObject:(int)number
{
if (index < self.numbers.count)
{
if (number)
{
int existingNumber = [self.numbers[index] intValue];
if (abs(existingNumber - number) >= 30)
self.confined = NO;
[self.numbers replaceObjectAtIndex:index withObject:#(number)];
}
}
}
- (int)numberAtIndex:(NSUInteger)index
{
if (index < self.numbers.count)
return [self.numbers[index] intValue];
return 0;
}
- (NSUInteger)count
{
return self.numbers.count;
}
#end
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;
}
Im haveing a problem suming two NSInteger, I have tried with simple int but cant find the answer. I Have this on my header file:
#interface ViewController : UIViewController {
NSMutableArray *welcomePhotos;
NSInteger *photoCount; // <- this is the number with the problem
//static int photoCount = 1;
}
The on my implementation fiel I have:
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
photoCount = 0;
welcomePhotos = [NSMutableArray array];
int sum = photoCount + 1;
NSLog(#"0 + 1 = %i", sum);
}
The las NSLog always prints 0 + 1 = 4
Also if if do:
if (photoCount < [welcomePhotos count]){
photoCount++;
NSLog(#"%i", photoCount);
}else{
photoCount = 0;
}
Several times i get: 4, 8, 12.
So it is skiping by four, but I can't get to understand why.
You are declaring your photoCount instance var as pointer to NSInteger. But NSInteger is a scalar type.
Remove the asterisk in your .h file and try again.
Replace
NSInteger *photoCount;
with
NSInteger photoCount;
You're printing out a pointer object I believe as you've declared it as
NSInteger* photocount;
Try changing it to
int photocount;
doing a variable++ on an integer adds the size of a pointer which is 4 bytes on iOS.
You used pointer to NSInteger...
Change it to NSInteger photoCount;
NSInteger is just an int, and you are treating it as an wrapper object. Pointer in not required.
I wanted to create 2 global arrays which can be updated during the run of the programme.In each update i add one element to zeroth position and deleted the last number
I created the arrays as....
In the .h file..........
//////////////
#interface Shared : NSObject{
NSMutableArray *x;
NSMutableArray *y;
}
#property (nonatomic,retain) NSMutableArray *x;
#property (nonatomic,retain) NSMutableArray *y;
+(Shared*)sharedInstance;
#end
In .m file
staticShared* sharedInstance;
#implementation Shared
#synthesize x;
#synthesize y;
+(Shared*)sharedInstance
{
if (!sharedInstance) {
sharedInstance=[[Sharedalloc]init];
}
returnsharedInstance;
}
-(Shared*)init
{
self = [superinit];
if(self)
{
x=[[NSMutableArrayalloc] init];
x=[NSMutableArrayarrayWithObjects:#"0",#"0",#"0",#"0",#"0",#"0",#"0",nil];
y=[[NSMutableArrayalloc] init];
y=[NSMutableArrayarrayWithObjects:#"0",#"0",#"0",#"0",#"0",#"0",nil];
}
returnself;
}
#end
Then i used to call them and re,ove and added elements using the following code....
[[shared sharedInstance].y removeLastObject];
[[shared sharedInstance].y insertObject:new_element atIndex:0];
[[shared sharedInstance].x removeLastObject];
[[shared sharedInstance].x insertObject:new_element atIndex:0];
In the mean time i call these values and calculate an arithmetic value using an expression.
This seems to work well. But it seems to be an inefficient way to handle floating point numbers which i store in it. As these arrays creates objects. Is there any easy method that i can create a global array containing specified amount of floating point numbers and update it during the run of the programm(array size is fixed) by deleting the last object, and call them back to do calculation?
Please help me!
EDIT 1
To sir deanWombourne
.................................
I implement as you instructed! Can you please go through this and help me to correct 2 errors i get.
IN the .h file
#interface Shared : NSObject{
#private
float input[7];
float output[6];
}
+(Shared*)sharedInstance;
-(void)addNewInput:(float)input1;
-(float *)input;
-(void)addNewOutput:(float)output1;
-(float *)output;
#end
in .m file............
#implementation Shared
-(id)init{
if((self =[superinit])){
for(int n=0; n<7 ;++n)
input[n]=0.00f;
for(int n=0; n<6 ;++n)
output[n]=0.00f;
}
returnself;
}
-(void)addNewInput:(float)input1{
input[0]=input[1];
input[1]=input[2];
input[2]=input[3];
input[3]=input[4];
input[4]=input[5];
input[5]=input[6];
input[6]=input1;
}
-(float *)input {
returninput;
}
-(void)addNewOutput:(float)output1{
output[0]=output[1];
output[1]=output[2];
output[2]=output[3];
output[3]=output[4];
output[4]=output[5];
input[5]=output1;
}
-(float *)output {
returnoutput;
}
#end
When calling it
float reading= (accel_reading)/(1.165969038*1e5f);
[[SharedsharedInstance] addNewInput:reading];
Problems i get
1. In the implementation, it says incomplete implementation (it's a warning not an error)
2. How can i used a for loop to fill array values or is this way ok?
Major problem i get,
When i call it as shown above, program stops running telling
Terminating application due to uncaught exception 'NSInvalidArgumentException', reason '+[SharedsharedInstance]: unrecognized selector sent to class 0x5780'
Please help me through this...............
Your code Smells (and I mean that in the nicest possible way!)
Using two parallel arrays and keeping in sync is a bad design pattern (and a performance hit in quite a few ways!). Especially as there is already a struct that handles storing an x and y at the same time - CGPoint).
You're solving the 'only objects go in arrays' problem by converting your float' primitives toNSString` objects, which is horrendously inefficient - take a look instead at the NSValue class, it's designed to put native C primitives into an object without expensive parsing operations :)
You might also want to look into malloc (and free etc) and deal with the whole problem at the C level - this will mean no objects at all and would be blindingly fast (at the cost of more complicated code).
Hope this helps, if you have any questions just add a comment to this answer :)
EDIT
If all you want to do is store 4 x and y values, then this is probably the easiest way to do it :
#interface Shared : NSObject {
#private
CGPoint points[4];
}
+(Shared *)sharedInstance;
- (void)addNewPoint:(CGPoint)point;
- (CGPoint *)points;
#end
#implementation
- (id)init {
if ((self = [super init])) {
// Start with 0,0 for all your points
for (int n = 0; n < 4; ++n)
points[n] = CGPointZero;
}
return self;
}
- (void)addNewPoint:(CGPoint)point {
// Just move all the points along one and add the new one to the end
// (yes, this could be done in a loop but there's not that much point for 4 points!)
points[0] = points[1];
points[1] = points[2];
points[2] = points[3];
points[3] = point;
}
- (CGPoint *)points {
return points;
}
#end
This gives you a method addNewPoint that removes the first point and adds the new point to the end of your array.
You also get the method points that returns the 4 points. Use it something like :
// To add a point
CGPoint newPoint = CGPointMake(100, 100);
[[Shared sharedInstance] addNewPoint:newPoint];
// To do something with the points (in this case, NSLog them)
CGPoint *points = [[Shared sharedInstance] points];
for (int n = 0; n < 4; ++n)
NSLog(#" Point %i : %#", n, NSStringFromCGPoint(points[n]));
EDIT #2
From your comments, you need two arrays, one with input data and one with output data. Try something like this :
#interface Shared : NSObject {
float inputs[4];
float outputs[5];
}
...
This will give you two arrays to read/write to - one called inputs and the other called outputs. Access them in pretty much the same way you did the ones in my first edit :
float *inputs = [[Shared sharedInstance] inputs];
for (int n = 0; n < 4; ++n)
NSLog(#" Input %i : %f", n, inputs[n]);
float *outputs = [[Shared sharedInstance] outputs];
for (int n = 0; n < 5; ++n)
NSLog(#" Output %i : %f", n, output[n]);
Would a linked list be overkill for what you're trying to achieve? It's not quite as simple as a static array of floats, but makes the removal of the last object and insertion of the zeroth object reasonably simple and fast.
If you want an array containing a specific number of Objects, you can use NSArray, which is static, opposed to NSMutableArray.
As for the array being Global, just implement a singleton class that contains the 2 arrays and provides the associated methods.
in Globals.h:
#interface Globals : NSObject
+ (Globals *) sharedGlobals;
#end
in Globals.m:
#implementation Globals
static Globals *sharedGlobals = nil;
+ (Globals *) sharedGlobals{
#synchronized(self){
if (sharedGlobals == nil){
sharedGlobals = [[self alloc] init];
}
}
return sharedGlobals;
}
you then can access the arrays (after you implemented them) with the following line:
[[Globals sharedGlobals] getArrayX];
Here is a sketch to get you going.
Your array size is fixed and only contains floating point numbers, start with a C array:
double x[] = {0, 0, 0, 0, 0, 0, 0};
double y[] = {0, 0, 0, 0, 0, 0};
The number of elements in these arrays can be calculated rather than hard-coded:
int xCount = sizeof(x)/sizeof(double);
int yCount = sizeof(y)/sizeof(double);
Now use these arrays as a circular buffer, declare a cursor and initialise:
int xCursor = 0;
The item at the front of the queue is at the cursor:
valueAtFrontOfQueue = x[xCursor]; // get the current front item
To remove the value at front and add a new one to the rear replace the value at the cursor with the new value and increment the cursor:
x[xCursor] = newValueForBackOfQueue; // replace it with new item for back of queue
xCursor = (xCursor + 1) % xCount; // and advance cursor using mod arithmetic to it cycles around
No wrapping doubles as objects, no dynamic allocation at all.
Wrap the above up as you see fit, maybe as a class, and you're done.