How do I loop through NSString N number of times? - ios

how do I loop the string 9 times ? (z x c v b n z x c)
NSString *fl = #"zxcvbn";

Here's a fast and dirty snippet:
NSString *string = #"abcdef";
NSString *letter = nil;
int n = 9;
for (int index = 0; index < n; index++) {
// start over if it's more than the length
int currentIndex = index % string.length;
letter = [string substringWithRange:NSMakeRange(currentIndex, 1)];
NSLog(#"letter: %#", letter);
}
If you want a low-level example with detailed explanation check this out.

In addition to using substringWithRange (which returns a NSString), you can also use characterAtIndex to get the character value:
NSInteger n = 9;
for (NSInteger index = 0; index < n; index++) {
unichar character = [fl characterAtIndex:index % fl.length];
// do something with `character`, e.g.
//
// if (character == 'z') { ... }
}

Related

Why am I getting wrong answer for this SPOJ Question

I still dont know weather I am allowed discuss Competetive Programming Doubts here, please let me know..
Can someone help me on this SPOJ question, I am getting wrong Answer:
https://www.spoj.com/problems/SPIKES/
I have tried all the test cases I could think of and the code always gives correct output.
Before posting it here, I also asked it in spoj forum but Its been two days, no one replies...
#include<bits/stdc++.h>
using namespace std;
// # = 35
// # = 64
// . = 46
// s = 115
// Using Dijkstra to find the path with minimum no. of Spikes
int n,m,j;
const int N = 100;
const int INF = 9;
vector<int> g[N];
int vis[N][N];
pair<int,int> dist[N][N];
vector<pair<int,int>> movements = {
{0,1},{0,-1},{1,0},{-1,0}
};
bool isvalid(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
void bfs(int sourcei, int sourcej){
set<pair<int,pair<int,int>>> q;
q.insert({0,{sourcei,sourcej}});
dist[sourcei][sourcej] = {0,INF};
while(q.size()>0){
auto curr_v = *q.begin();
int curr_i = (curr_v.second).first;
int curr_j = (curr_v.second).second;
int spikes = curr_v.first;
q.erase(q.begin());
if(vis[curr_i][curr_j]) continue;
vis[curr_i][curr_j] = 1;
for(auto m : movements){
int child_i = curr_i + m.first;
int child_j = curr_j + m.second;
int spikec = spikes;
if(!isvalid(child_i,child_j)) continue;
if(g[child_i][child_j] == 115) spikec = spikes+1;
if(vis[child_i][child_j]) continue;
if(g[child_i][child_j]==35) continue;
if(dist[child_i][child_j].second > spikec){
dist[child_i][child_j] = {(dist[curr_i][curr_j].first +1),spikec};
q.insert({spikec , {child_i,child_j}});
}
}
}
}
int main(){
cin>>n>>m>>j;
int start_j,start_i;
int end_j,end_i;
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
dist[i][j].second = INF;
dist[i][j].first = 0;
}
}
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
char x; cin>>x;
g[i].push_back((int)x);
if(x=='#') {
start_i = i;
start_j = j;
}
if(x=='x'){
end_i = i;
end_j = j;
}
}
}
bfs(start_i,start_j);
// for (int i = 0; i < n; ++i){
// for (int j = 0; j < m; ++j){
// cout<<dist[i][j].first<<","<<dist[i][j].second<<" ";
// }cout<<endl;
// }
if(dist[end_i][end_j].second <= (int)j/2) cout<<"SUCCESS"<<endl;
else cout<<"IMPOSSIBLE"<<endl;
return 0;
}

Calculating the standard deviation of a string

I want the user to provide a string. The string will be divided into individual characters. Each character will be put into a number (a = 1, b = 2, c = 3, etc) and then put into an array with the values, and then the standard deviation will be calculated.
I already have the code to convert the letters:
for (int i = 0 ; i < str.length ; ++i ) {
// 'A' unicode value is 65, so by substracting 64 you'll get 1 for A, 2 for B, 3 for C...
total += [str characterAtIndex:i] - 64;
But that code only uses the string (maybe there is a way to just put the values directly into a string?)
And the code for standard deviation:
NSArray *numbers = #[#1, #2];
NSExpression *expression = [NSExpression expressionForFunction:#"stddev:" arguments:#[[NSExpression expressionForConstantValue:numbers]]];
NSNumber *value = [expression expressionValueWithObject:nil context:nil];
NSLog(#"%#,", value);
If your question is "how would I convert the string of letters into an array of numbers?", try something like this:
NSMutableArray * array = [NSMutableArray arrayWithCapacity:str.length];
for (int i = 0; i < str.length; ++i) {
[array addObject:[NSNumber numberWithInt:[str characterAtIndex:i]-64]];
}

c style 2d array not retaining value between functions

Ok so I'm creating a map using a c-style 2d array containing position structs:
typedef struct{
int x;
int y;
} posn;
I upload the values fine and print them out to make sure the values are correct. The 2d array is stored as an instance variable in my class.
In my next function I start by printing the array to make sure it's the same but it's not. The values are totally different and the array is even shortened. Can anyone tell me why I'm getting this issue. I'm using structs and c style arrays because I'm designing a game and I figured using them would be faster than NSMutableArray.
this is how I fill the array
mapa_camino = (posn *)malloc(w * h * sizeof(posn));
int i, j = 0;
for (i = 0; i < w; i++){
for (j = 0; j < h; j++){
SKNode *act;
act = [self.main_view nodeAtPoint:CGPointMake(i-algorimo_compensado.x, j-algorimo_compensado.y)];
if([act isKindOfClass:[BasicActor class]] && ![act isKindOfClass:[CMActor class]]){
//crea pt
posn pt = {.x = i,
.y = j,
.ocupado = YES,
.visitado = NO};
//fija posicion actual como pt
*(mapa_camino + i*h + j) = pt;
}else{
posn pt = {.x = i,
.y = j,
.ocupado = NO,
.visitado = NO};
*(mapa_camino + i*h + j) = pt;
}
}
}
this is how I print it:
- (NSMutableArray*) printtwodarray:(posn*)matriz{
int array_w = self.frame.size.width;
int array_h = self.frame.size.height;
NSMutableArray* regresa_matriz = [[NSMutableArray alloc] initWithCapacity:array_w];
for(int i=0;i<array_w;i++){
[regresa_matriz addObject:[[NSMutableArray alloc] initWithCapacity:array_h]];
for(int j=0;j<array_h;j++){
posn *pt = (matriz + i*array_h + j);
[[regresa_matriz objectAtIndex:i] insertObject:[[Posn alloc] initWithX:pt->x Y:pt->y H:pt->h G:pt->g Ocupado:pt->ocupado Goal:pt->is_goal] atIndex:j];
}
}
return regresa_matriz;
}
In order to store a 2D array in an instance variable from one function and use it in another function you need to declare the variable as an array, not as a pointer. Assignment would not work, so you would need to initialize the data with memcpy:
#interface Foo : NSObject {
posn p[20][30];
}
#end
...
-(void)bar {
posn d[20][30] = {{...}, {...},...,{...}};
memcpy(p, d, sizeof(p));
}

How do I randomize the questions pulled from my dictionary-plist

Hey Guys any ideas for randomising the questions that I pull from my -plist file?
-(NSUInteger)nextQuestionID:(NSUInteger)question_number{
return (question_number>=[self.questions count]-1) ? 0 : (question_number+1);
return 0;
}
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
return [self.questions objectAtIndex:question_number];
return NULL;
}
To get a random integer, I would suggest using arc4random function, here is some code to do this:
int randomInt = arc4random() % questionNumber;
return [self.questions objectAtIndex: randomInt];
You can use the arc4random_uniform(upper_bound) function. The parameter is the upper bound of your random number.
An example:
int index = arc4random_uniform([self.question count]);
question_number = arc4random() % self.questions.count;
set question number as random number
replace the function
-(NSDictionary*) getQuestion:(NSUInteger)question_number{
if (question_number>=[self.questions count]) question_number = 0;
question_number = arc4random()%[self.questions count];// changes made here
return [self.questions objectAtIndex:question_number];
return NULL;
}
the random integers:
srand(time(nil));
for (int i = 0; i < 100; i++) {
NSLog(#"random number between 72 and 96 : %d", rand() % (96 - 72) + 72);
}
UPDATE
and for your specific case:
- (NSUInteger)nextQuestionID {
srand(time(nil));
return rand() % [self.questions count];
}
- (NSDictionary*)getQuestion {
return [self.questions objectAtIndex:[self nextQuestionID]];
}
UPDATE#2
test the following loop two, three or more times and compare the outputs:
srand(time(nil));
for (int i = 0; i < 10; i++) {
NSLog(#"random number : %d", rand() % 89 + 10);
}
you should get 10 random numbers between 10 and 99, I've tested it on a real device, not on the simulator but it should work on the simulator as well.
if you get the same result always, let me know.

Generating 3 unique random numbers in Objective-C?

I'm trying to generate 3 random numbers between 0 to 25. I used arc4random_uniform(25) for this and it generate 3 random numbers.but problem is that some time I get two or even all three numbers are same, but I require 3 unique numbers.
As #Thilo said you have to check they are random and repeat if they are not:
// This assumes you don't want 0 picked
u_int32_t numbers[3] = { 0, 0, 0 };
for (unsigned i = 0; i < 3; i++)
{
BOOL found = NO;
u_int32_t number;
do
{
number = arc4random_uniform(25);
if (i > 0)
for (unsigned j = 0; j < i - 1 && !found; j++)
found = numbers[j] == number;
}
while (!found);
numbers[i] = number;
}
int checker[3];
for(int i = 0 ; i < 3 ; i++){
checker[i] = 0;
}
for(int i = 0 ; i < 3 ; i++){
random = arc4random() % 3;
while(checker[random] == 1){
random = arc4random() % 20;
}
checker[random] = 1;
NSLog(#"random number %d", random);
}
I am generating an Array of unique Random Number in the following way:
-(void)generateRandomUniqueNumberThree{
NSMutableArray *unqArray=[[NSMutableArray alloc] init];
int randNum = arc4random() % (25);
int counter=0;
while (counter<3) {
if (![unqArray containsObject:[NSNumber numberWithInt:randNum]]) {
[unqArray addObject:[NSNumber numberWithInt:randNum]];
counter++;
}else{
randNum = arc4random() % (25);
}
}
NSLog(#"UNIQUE ARRAY %#",unqArray);
}

Resources