Reversing a string using array in xcode - objective-c

this is my first question in stackoverflow!
im trying to reverse a string using two arrays in xcode, ive set up the interface,i got a button,a text field and a label.
whatever goes into the text field is reversed when the button is touched!
i got the code and it seems correct to me on paper,the problem is that when i test the application with for example "HELLO", the content of myArray is "H E" and reverseArray is" O L L".
id be grateful if anyone cud help im pretty fed up with tracing this code :(((
here is the code:
#interface ViewController ()
#end
#implementation ViewController
#synthesize textField,string1,string2,reverseArray,myArray;
#synthesize Label1;
- (IBAction)Reverse:(UIButton *)sender {
reverseArray=[[NSMutableArray alloc]init];
string1=[[NSString alloc]init];
string2=[[NSString alloc]init];
string1=textField.text;
myArray=[[NSMutableArray alloc]init];
for (int i=0; i<=string1.length-1; i++) {
[myArray insertObject:[[NSString alloc] initWithFormat:#"%c",[string1 characterAtIndex:i]] atIndex:i];
}
for (int j=0; j<=myArray.count-1; j++) {
[reverseArray insertObject:[myArray objectAtIndex:myArray.count-1] atIndex:j];
[myArray removeLastObject];
}
NSLog(#"%#",myArray);
NSLog(#"%#",reverseArray);

For the second loop, you're using myArray.count as the end condition for the "for" loop, but myArray.count is decreasing by one each iteration of the loop because you're removing the last object from myArray each iteration. Think about it:
First iteration: j=0; myArray.count - 1 = 4
Second iteration: j=1; myArray.count - 1 = 3
Third iteration: j=2; myArray.count - 1 = 2
It stops here at the forth iteration because j=3 > myArray.count -1 = 1
Try something like this for the second loop (Note: I'm not in front of xCode right now, so there might be errors in the following block. Take it with a grain of salt):
for( int j = string1.length -1; j >= 0; j-- ) {
[reverseArray addObject:[myArray objectAtIndex:j]];
}

Related

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;
}

Checking to see if two positions are equal

Right now I have a NSMutableArray that holds 3 sprite objects. I need to be able to see if another sprite not in the Array shares the same position as any of the sprites in the array.
I tried doing this:
CCSprite *sect;
if (i > maxHealth) {
for (int j = 0; j < i; j++) {
sect = [tail objectAtIndex:j];
}
if (CGRectContainsPoint(sect.boundingBox, playerPos)) {
NSLog(#"On top");
return;
}
But it does't work. I think it's trying to see if it intersects all of them at once.
Your if is outside the for loop. It is only going to test one object; the last one accessed in the loop.

Problems sending messages to NSMutableArrays within C-Arrays

I'm currently trying to implement a pooling system, I have all the code, I just dont understand why a certain part of it doesn't work.
I have a c-array of NSMutable array made like this:
NSMutableArray *poolArray[xSize][ySize];
for (int n = 0; n < xSize; n++)
{
for (int m = 0; m < ySize; m++)
{
poolArray[n][m] = [[NSMutableArray alloc] init];
}
}
And whilst trying to access it I get the x and y coordinate of the pool and object is in and try to add it like this:
[poolArray[x][y] addObject:object]; //This raises a EXC_BAD_ACCESS error
I am totally open to editing how I write this - I am aware that I could declare a NSMutableArray and use indexes of ((y * width) + x) and I may have to rewite the code like that. But preferably I dont want to have to do that as I only want to actually create the arrays I'm using so something like this:
if (poolArray[x][y] == nil) poolArray[x][y] = [[NSMutableArray alloc] init];
[poolArray[x][y] addObject:object];
This is so that it can have 'holes' so I dont have to make anything at poolArray[2][3] for example if there is nothing there.
I don't know if there is anyway that I could rewrite that with objective-c types, but if I do I'm forced to keep creating a NSMutableArray at every space, the reason I dont want to do that is because I want to get every little bit of performance I can out of the system.
Thanks for taking the time to read this, and any response is appreciated :)
This works for me:
#import <Foundation/Foundation.h>
#define xSize 10
#define ySize 10
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *poolArray[xSize][ySize];
for (int n = 0; n < xSize; n++)
{
for (int m = 0; m < ySize; m++)
{
poolArray[n][m] = [[NSMutableArray alloc] init];
}
}
[poolArray[2][3] addObject: #"Hello"];
[poolArray[2][3] addObject: #"world!"];
NSLog(#"poolArray[2][3] objects: %# %#",
[poolArray[2][3] objectAtIndex: 0],
[poolArray[2][3] objectAtIndex: 1]);
[pool drain];
return 0;
}
(Yes, I know, I should release all NSMutableArray instances. Left out for brevity).
So there are a few things you should check:
Is object a valid object, i.e. was it initialized? The NSMutableArray will try to retain the object, and if it was never initialized, that will fail miserably, or if it was dealloc-ed already, it will fail too.
are x and y valid? You can easily go over the boundaries and not notice it.
Can't see anything wrong with the code you've provided, although a couple of ideas:
In the case where your checking poolArray[x][y] == nil have you actually reset all the values to nil when you initialize the array?
An alternative that should work, is to store the array on the heap. You could use calloc (which will initialize the memory to 0), or malloc and memset.
The following should work:
NSMutableArray ***poolArray = calloc(xSize * ySize, sizeof(NSMutableArray *));
if (poolArray[x][y] == nil) poolArray[x][y] = [[NSMutableArray alloc] init];
[poolArray[x][y] addObject:object];

Loop to make grid of NSButtons?

I am trying to loop through and programmatically make a grid of 256 NSButtons (16x16). The code I have so far is below. This is in Objective-C for my Mac app. So I am logging to see which tag I get when I click a button, but it keep returning the same tag every time.
I want it so that every button goes 1-256 from left to right, top to bottom. This code successfully makes them load into my view, but the tags are wrong.
#define N_ROWS 16
#define N_COLS 16
int btnSpaceDifference = 1;
int btnSpacing = N_ROWS + btnSpaceDifference;
for (int j = 0; j < N_ROWS; j++) {
for (int i = 0; i < N_COLS; i++) {
paintPixel = [[[NSButton alloc] initWithFrame:NSMakeRect(10 + (i * btnSpacing), 10 + (j * btnSpacing), 16, 16)] autorelease];
[paintPixel setTitle:#""];
[paintPixel setBezelStyle:NSBorderlessWindowMask];
[paintPixel setTag:j + i * N_ROWS + 1];
[paintPixel setAction:#selector(btnPaintAction:)];
[[[box.tabViewItems objectAtIndex:0]view] addSubview:paintPixel];
}
}
-(void)btnPaintAction:(id)sender{
NSLog(#"%ld", paintPixel.tag);
}
Instead of making all of these buttons yourself, why not use an NSMatrix? This is the sort of thing it's perfect for.
Not sure how its compiling, you might have paintPixel defined elsewhere. But you need to change your btnPaintAction from:
-(void)btnPaintAction:(id)sender {
NSLog(#"%ld", paintPixel.tag);
}
To something like this:
-(void)btnPaintAction:(id)sender {
NSButton * myButton = (NSButton *) sender;
NSLog(#"%ld", myButton.tag);
}
call setTag with an increment variable
int TagVal = 1;
for (int j = 0; j < N_ROWS; j++) {
....
[paintPixel setTag:TagVal++];
....
}
Then modify your btnPaintAction:
UIButton *button = (UIButton *)sender;
NSLog(#"%ld", button.tag);
It's returning the same tag every time because your action is referring to your (apparently) member variable paintPixel. Use the sender parameter to the action instead.
NSLog(#"%ld", ((NSButton *)sender).tag);
This is old post but I see no correct answer, thus my addition.
Q. " I want it so that every button goes 1-256 from left to right, top to bottom."
Kevin was on the good track, however one more alteration is required:
paintPixel = [[[NSButton alloc] initWithFrame:NSMakeRect(10 + (i * btnSpacing), 10 - (j * btnSpacing), 16, 16)] autorelease];
Thus minus(-) instead of plus(+) results in numbering top to bottom.

Objective-C - Loop played but loop condition is false

I'm trying to convert a sectionned table into a flat list using this function into didSelectRowAtIndexPath (I have a NSArray that is initialisated with the number of items contained in each section) :
Somewhere... :-)
self.sectionsArray = [NSArray arrayWithObjects:macroIntNumber(1), macroIntNumber(3), macroIntNumber(12), nil];
then into didSelectRowAtIndexPath :
int selectedRow = 0;
int a = indexPath.section;
for (int i=0; i<indexPath.section-1; i++) {
selectedRow += [[self.sectionsArray objectAtIndex:i] intValue];
}
selectedRow += indexPath.row;
But... This crashes for indexPath.section = 0 (first section).
Because the loop is played infinitly until crash of the NSArray call...
Strange !!!
forcing for (int i=0; i<0-1; i++) { works
forcing for (int i=0; i<a-1; i++) { works
What am I missing ?
section is an NSUInteger, so it's unsigned. Thus, subtracting 1 from 0 on that unsigned integer is taking you to a very large number rather than -1.
It works when using a, because you've declared a as an int. :)