Objective-c regex checking for sequence of two numbers - objective-c

Can't seem to figure out how to check a string so that the same two characters in a row are not allowed.
I don't want anyone to be able to submit data with "00".

What about just:
(\d)\1+
The \d matches any digit and the \1+ matches whatever was matched in the first bit when it appears more than one time.
Pertaining to your comments though, it's much easier just to check:
if ([expiryDate rangeOfString:#"00"].location != NSNotFound)
{
//Invalid date
}
or even perhaps more validating:
NSArray *components = [expiryDate componentsSeparatedByString:#"/"];
int month = [components[0] intValue];
int year = [components[1] intValue];
NSAssert(month > 0 && month <= 12, #"Invalid Month");
NSAssert(year >= 13 /*current year*/ /* (optionally) && year < 20 (or some other future year)*/, #"Invalid year");

Related

additional logic to this exercise missing

Writing a basic program to count the number of words in a string. I've changed my original code to account for multiple spaces between words. By setting one variable to the current index and one variable to the previous index and comparing them, I can say "if this current index is a space, but the previous index contains something other than a space (basically saying a character), then increase the word count".
int main(int argc, const char * argv[]) {
#autoreleasepool {
//establishing the string that we'll be parsing through.
NSString * paragraph = #"This is a test paragraph and we will be testing out a string counter.";
//we're setting our counter that tracks the # of words to 0
int wordCount = 0;
/*by setting current to a blank space ABOVE the for loop, when the if statement first runs, it's comparing [paragraph characterAtIndex:i to a blank space. Once the loop runs through for the first time, the next value that current will have is characterAtIndex:0, while the if statement in the FOR loop will hold a value of characterAtIndex:1*/
char current = ' ';
for (int i=0; i< paragraph.length; i++) {
if ([paragraph characterAtIndex:i] == ' ' && (current != ' ')) {
wordCount++;
}
current = [paragraph characterAtIndex:i];
//after one iteration, current will be T and it will be comparing it to paragraph[1] which is h.
}
wordCount ++;
NSLog(#"%i", wordCount);
}
return 0;
}
I tried adding "or" statements to account for delimiters such as ";" "," and "." instead of just looking at a space. It didn't work...any idea what I can do, logically speaking, to account for anything that isn't a letter (but preferably just limiting it to these four delimiters - . , ; and space.
A standard way to solve these types of problems is to build a finite state machine, your code isn't quite one but its close.
Instead of thinking about comparing the previous and current characters think in terms of states - you can start with just two, in a word and not in a word.
Now for each state you consider what the current character implies in terms of actions and changes to the state. For example, if the state is not in a word and the current character is a letter then the action is increment word count and the next state is in a word.
In (Objective-)C you can build a simple finite state machine using an enum to give the states names and a case statement inside a loop. In pseudo-code this is something like:
typedef enum { NotInWord, InWord } State;
State currentState = NotInWord;
NSUInteger wordCount = 0;
for currentChar in sourceString
case currentState of
NotInWord:
if currentChar is word start character -- e.g. a letter
then
increment wordCount;
currentState = InWord;
InWord:
if currentChar is not a word character -- e.g. a letter
then
currentState = NotInWord;
end case
end for
The above is just a step from your original algorithm - recasting it in terms of states rather than the previous character.
Now if you want to get smarter you can add more states. For example how many words are there in "Karan's question"? Two. So you might want to allow a single apostrophe in a word. To handle that you can add a state AfterApostrophe whose logic is the same as the current InWord; and modify InWord logic to include if the current character is an apostrophe the next state is AfterApostrophe - that would allow one apostrophe in a word (or its end, which is also valid). Next you might want to consider hyphenated words, etc...
To test if a character is a particular type you have two easy choices:
If this is just an exercise and you are happy to stick with the ASCII range of characters there are functions such as isdigit(), isletter() etc.
If you want to handle full Unicode you can use the NSCharacterSet type with its pre-defined sets for letters, digits, etc.
See the documentation for both of the above choices.
HTH
I don't understand, You should be able to add or statements....
int main(void) {
char paragraph[] = "This is a test paragraph,EXTRAWORDHERE and we will be testing out a string.";
char current = ' ';
int i;
int wordCount = 0;
for (i = 0; i < sizeof(paragraph); i++){
if ((paragraph[i] == 32 || paragraph[i] == 44) && !(current == 32 || current == 44)){ //32 = ascii for space, 44 for comma
wordCount++;
}
current = paragraph[i];
}
wordCount++;
printf("%d\n",wordCount);
return 0;
}
I suppose it would be better to change the comparison of current from a not equal to into an equal to. Hopefully that helps.

How do you check if an NSInteger is greater than another NSinteger?

I'm trying to write code that detects if an integer is greater than another integer. Is this possible?
Here is what i've done so far.
if (NumCorrect >> NumWrong) {
btnCool.title = #"Awww";
}
else {
btnCool.title = #"Cool!";
}
All its doing is going to the else
EDIT:
NSString *numCorrect = [NSString stringWithFormat:#"%d",NumCorrect];
NSString *numWrong = [NSString stringWithFormat:#"%d", NumWrong];
lblWrong.text = numWrong;
lblCorrect.text = numCorrect;
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}
Use single >
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}
Double >> is a bit shift operation. You shift every bit in the binary representation of your variable NumCorrect NumWrong amount of bytes to the right. In almost all cases this will return in a number other then 0, which will then treated as a false value and thus the else block is executed.
Almost perfect - just take off one of those >'s. >> and << are for "bit-shifting", a weird hold-over from the earliest days of programming. You're not gonna use them much. What you really want is > and <, which is for testing if numbers are greater than each other or less than each other.
In addition, you may remember from math class that ≥ and ≤ (greater-than-or-equal-to and less-than-or-equal-to) are useful operations as well. Because there's no symbols for those on most keyboards, however, C and Xcode use >= and <= instead.
Finally, you may already know this, but to check if two numbers are exactly equal to each other you can use == (because = is used for setting the contents of variables).
Hope that's helpful!

get an integer -unit digit in a simple way

i am not sure about my english, but i need to get the unit digit of an integer.
WITHOUT complex algorithm but with some API or another trick.
for example :
int a= 53;
int b=76;
this i add because i almost always dont "meet the quality standards" to post! its drive me crazy! please , fix it ! it took me 10 shoots to post this,and other issue also.
i need to get a=3 and b=6 in a simple smart way.
same about the other digit.
thanks a lot .
here is how to split the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5
You're looking for % operator.
a=a%10;//divides 'a' by 10, assigns remainder to 'a'
WARNING
here is how to divine the number into parts
int unitDigit = a % 10; //is 3
int tens= (a - unitDigit)/10; //is 53-3=50 /10 =5
this answer is totally incorrect. It may work only in a number of cases. For example try to get the first digit of 503 via this way
It seems the simplest answer (but not very good in performance):
int a = ...;
int digit = [[[NSString stringWithFormat:#"%d", a] substringToIndex:1] intValue]; //or use substringWithRange to get ANY digit
Modulo operator will help you (as units digit is a reminder when number is divided by 10):
int unitDigit = a % 10;
The following code "gets" the digits of a given number and counts how many of them divide the number exactly.
int findDigits(long long N){
int count = 0;
long long newN = N;
while(newN) // kinda like a right shift
{
int div = newN % 10;
if (div != 0)
if (N % div == 0) count++;
newN = newN / 10;
}
return count;
}

Objective C - Core Text, number of characters in a line?

Given an index for current character, how can I determine the number of line that the selected character is at?
Given a CTLine how can I determine the number of characters in it?
For the first one:
int currentCharacterIndex = 12; // You define this.
CFArrayRef lines = CTFrameGetLines(frame);
int currentLine = 0;
for (CTLineRef line in lines) {
currentLine++;
CFRange range = CTLineGetStringRange(line);
if (currentCharacterIndex > range.location)
break;
}
// Current line is now the line that the currentCharacterIndex resides at
For the second one:
CFRange range = CTLineGetStringRange(line);
CFIndex length = range.length; // Number of characters
Can't be sure these work as I haven't tested them but it's worth a go.

Given 4 objects, how to figure out whether exactly 2 have a certain property

I have another question on how to make most elegant solution to this problem, since I cannot afford to go to computer school right so my actual "pure programming" CS knowledge is not perfect or great. This is basically an algorhythm problem (someone please correct me if I am using that wrong, since I don't want to keep saying them and embarass myself)
I have 4 objects. Each of them has an species property that can either be a dog, cat, pig or monkey. So a sample situation could be:
object1.species=pig
object2.species=cat
object3.species=pig
object4.species=dog
Now, if I want to figure out if all 4 are the same species, I know I could just say:
if ( (object1.species==object2.species)
&& (object2.species==object3.species)
&& (object3.species==object4.species)
) {
// They are all the same animal (don't care WHICH animal they are)
}
But that isn't so elegant right? And if I suddenly want to know if EXACTLY 3 or 2 of them are the same species (don't care WHICH species it is though), suddenly I'm in spaghetti code.
I am using Objective C although I don't know if that matters really, since the most elegant solution to this is I assume the same in all languages conceptually? Anyone got good idea?
Thanks!!
You can use a hash table (or dictionary in objective-C) with the key on the species, incrementing the count every time.
For clarity (pseudo-code):
// N is 4 for your particular case
for ( int i = 0; i < N; i++ )
hashtable[ object[i].species ]++;
hashtable[ Species.PIG ]; // number of pigs (constant)
or if you want to unroll it manually:
hashtable[ object1.species ]++;
hashtable[ object2.species ]++;
hashtable[ object3.species ]++;
hashtable[ object4.species ]++;
now you can check through the species to see the count:
for each key in hashtable
if ( hashtable[ key ] == 3 ) // species "key" has 3 items
/* Code */
of course, "hashtable" can be just a simple array if species is just a simple enum/integer. The above should be the same theory in either case.
This is precisely what sets and counted sets are for.
BOOL allSameSpecies(NSArray *animals) {
NSSet *speciesSet = [NSSet setWithArray:[animals valueForKey:#"species"]];
return [[speciesSet] count] == 1;
}
BOOL sameSpeciesNumber(NSArray *animals, NSUInteger targetCount) {
NSCountedSet *speciesCounts = [NSCountedSet setWithArray:[animals valueForKey:#"species"]];
for (id species in speciesCounts) {
if ([speciesCounts countForObject:species] == targetCount)
return YES;
}
return NO.
}
You can count how many comparisons match of all possible comparisons. If exactly 1 comparison is true, then exactly 2 items are the same, if 3 comparisons match, exactly 3 items are the same. This example is in C, you'll have to convert it to objective-C on your own.
int count = 0;
count += object1.species == object2.species;
count += object1.species == object3.species;
count += object1.species == object4.species;
count += object2.species == object2.species;
count += object2.species == object3.species;
count += object3.species == object4.species;
// count 0 - all different
// count 1 - exactly 2 are the same
// count 2 - two pairs of 2
// count 3 - exactly 3 are the same
// count 6 - all are the same
The counting can also be implemented as a loop:
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++)
count += objects[i].species == objects[j].species;
This approach only works if the amount of objects is 5 or less. Because of this and the fact that the amount of comparisons scales quadratically, it's better to use a hashtable if the amount of objects is larger.