I have created an array of positive, negative and zero numbers but it treats all the elements in the array as positive numbers. Here in code, the positiveCount is 6. How to put negative numbers in an array in Objective-C?
NSInteger positiveCount = 0;
NSInteger zeroCount = 0;
NSInteger negativeCount = 0;
NSArray *arr = [NSArray arrayWithObjects:#-4,#-3,#-9,#0,#4,#1, nil];
for (NSInteger i = 0; i < arr.count; i++){
NSLog(#"%d",arr[i]);
if (arr[i] > 0)
{
positiveCount += 1;
} else if (arr[i] < 0){
negativeCount += 1;
} else {
zeroCount += 1;
}
}
NSLog(#"%d",positiveCount);
The elements in your array are not numbers, they are NSNumber instances, that is, pointers. Pointers are always positive:
for (NSNumber* number in arr) {
NSInteger intValue = number.integerValue;
NSLog(#"%d", intValue);
if (intValue > 0) {
positiveCount += 1;
} else if (intValue < 0) {
negativeCount += 1;
} else {
zeroCount += 1;
}
}
One more way for the solution using enumerateObjectsUsingBlock,
__block NSInteger positiveCount = 0;
__block NSInteger zeroCount = 0;
__block NSInteger negativeCount = 0;
NSArray *arr = [NSArray arrayWithObjects:#-4,#-3,#-9,#0,#4,#1, nil];
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSInteger value = ((NSNumber *)obj).integerValue;
if (value > 0) {
positiveCount += 1;
} else if (value < 0) {
negativeCount += 1;
} else {
zeroCount += 1;
}
}];
NSLog(#"%ld",(long)positiveCount);
Related
Let say number = 0 and otherNumber = 10. The loop will execute. But what if number = 10 and otherNumber = 0. I want the compiler to pick the smallest number and use it to proceed.
The code I have so far is here:
- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
if (number <= otherNumber) {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= number; i <= otherNumber; i++) {
[indices appendFormat:#"%d", i];
}
} else {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= otherNumber; i <= number; i++) {
[indices appendFormat:#"%d", i];
}
}
return #"%#", indices;
}
A simple fix is to move the declaration of indices outside the conditional:
- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
if (number <= otherNumber) {
for (NSInteger i= number; i <= otherNumber; i++) {
[indices appendFormat:#"%d", i];
}
} else {
for (NSInteger i= otherNumber; i <= number; i++) {
[indices appendFormat:#"%d", i];
}
}
return indices;
}
You could further unify your like this:
- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
NSInteger from, to;
if (number <= otherNumber) {
from = number;
to = otherNumber;
} else {
from = otherNumber;
to = number;
}
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= from; i <= tp; i++) {
[indices appendFormat:#"%d", i];
}
return indices;
}
One option would be:
- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
NSInteger minNum = MIN(number, otherNumber);
NSInteger maxNum = MAX(number, otherNumber);
NSMutableString *indices = [NSMutableString stringWithCapacity:maxNum - minNum + 1];
for (NSInteger i = minNum; i <= maxNum; i++) {
[indices appendFormat:#"%d", i];
}
return indices; // or [indices copy];
}
Pick one of the variables to always be considered the larger variable, and then do a simple swap-test before the function body proper.
- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber {
if (number < otherNumber) {
NSInteger temp = number;
number = otherNumber;
otherNumber = temp;
}
NSMutableString *indices = [NSMutableString stringWithCapacity:1];
for (NSInteger i= otherNumber; i <= number; i++) {
[indices appendFormat:#"%d", i];
}
return #"%#", indices;
}
(Apologies for any code errors, Objective-C isn't my primary language)
I want to create creepify text in my app with js code (creepify())
https://github.com/combatwombat/Lunicode.js/blob/master/lunicode.js
website using this js code: http://lunicode.com/creepify
My problem is when i try to combine characters, the result is'nt like in website.
I try to create 3 NSMutableArray
NSMutableArray *diacriticsTop;
NSMutableArray *diacriticsMiddle;
NSMutableArray *diacriticsBottom;
and store value like this
for (int i = 768; i <= 789; i++) {
[diacriticsTop addObject:[NSNumber numberWithInt:i]];
}
for (int i = 790; i <= 819; i++) {
if (i != 794 && i != 795) {
[diacriticsBottom addObject:[NSNumber numberWithInt:i]];
}
}
...
then i convert creepify() in js code to
- (NSString *)creepifyString:(NSString *)inputString
{
BOOL isTop = YES;
BOOL isMiddle = YES;
BOOL isBottom = YES;
NSInteger maxHeight = 15;
NSInteger randomization = 100;
NSMutableString *outputString = [[NSMutableString alloc] init];
unichar output = 0;
for (int i = 0; i < inputString.length; i++) {
unichar c = [inputString characterAtIndex:i];
if (isMiddle) {
NSNumber *temp = diacriticsMiddle[lroundf(drand48()*diacriticsMiddle.count)];
c = c + (unichar) temp;
}
// Top
if (isTop) {
// Put up to this.options.maxHeight random diacritics on top.
// optionally fluctuate the number via the randomization value (0-100%)
// randomization 100%: 0 to maxHeight
// 30%: 70% of maxHeight to maxHeight
// x%: 100-x% of maxHeight to maxHeight
int diacriticsTopLength = diacriticsTop.count - 1;
for (int count = 0,
len = maxHeight - drand48()*((randomization/100)*maxHeight); count < len; count++) {
NSNumber *temp = diacriticsTop[lroundf(drand48()*diacriticsTopLength)];
c = c + (unichar) temp;
}
}
// Bottom
if (isBottom) {
int diacriticsBottomLength = diacriticsBottom.count - 1;
for (int count = 0,
len = maxHeight - drand48()*((randomization/100)*maxHeight); count < len; count++) {
NSNumber *temp =diacriticsBottom[lroundf(drand48()*diacriticsBottomLength)];
c = c + (unichar) temp;
}
}
output = output + c;
}
[outputString appendFormat:#"%C", output];
NSLog(#"%#", outputString);
return outputString;
}
I want to change the following code
NSString* loop = #"";
for (int i = 1; i <= 5; i++)
{
loop = [loop stringByAppendingString:#"0"];
NSLog(#" %#", loop);
}
for (int i = 10; i >= 1; i--)
{
loop = [loop substringFromIndex:1];
NSLog(#" &#", loop);
}
to be result in the pattern of pyramid below. What should I do?
1
101
21012
3210123
432101234
and
0
01
012
0123
01234
012345
01234
0123
012
01
0
For second pattern you can use code:
NSString *loop=#"";
for (int i = 0; i <= 10; i++) {
if (i > 5) {
loop = [loop substringToIndex:[loop length] - 1];
}
else {
loop = [loop stringByAppendingString:[NSString stringWithFormat:#"%i", i]];
}
NSLog (#" %#" , loop);
}
For first
NSString *loop = #"";
NSString *spaces = #" ";
for (int i = 1; i <= 5; i++)
{
if (i==1) {
loop = [loop stringByAppendingString:[NSString stringWithFormat:#"%#%i", [spaces substringFromIndex:i], i - 1]];
} else {
loop = [loop substringFromIndex:6 - i];
loop = [[NSString stringWithFormat:#"%#%i",[spaces substringFromIndex:i], i - 1] stringByAppendingString:[loop stringByAppendingString:[NSString stringWithFormat:#"%i", i - 1]]];
}
NSLog(#" %#", loop);
}
I am trying this code for generating a random number and saving the list of numbers in an array, then i am trying to delete those numbers from the list one by one which appeared once, e.g
1, 5, 9 , 4, 3, 7 ,6 ,10, 11, 8, 2 are the list of integers now 9 is appeared once and now i do not need 9 again.. this is my code of random non repeating numbers array.
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
{
x = arc4random() % 10;//generating random number
if(i==0)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
Try this,
NSArray *arrRandoms = [[NSArray alloc]initWithObjects:1,5,8,7,36,17,96,32,5,7,8,13,36,nil] ; // This contains your random numbers
NSMutableArray *arrFresh = [[NSMutableArray alloc]init];
// Now removing the duplicate numbers
BOOL checkRepeat = NO;
int _Current;
for (int i=0; i<[arrRandoms count]; i++)
{
_Current = [arrRandoms objectAtIndex:i];
if (i == 0)
[arrFresh addObjects:_Current];
else
{
checkRepeat = NO;
for(int j=0; j< [arrFresh count]; j++)
{
if ( _Current == [arrFresh objectAtIndex:j])
checkRepeat = YES;
}
if (checkRepeat == NO)
[arrFresh addObjects:_Current];
}
}
I think this code will work. Check It.
try it
//**************remove repeat objects from array***************************//
NSArray *noDuplicates = [[NSSet setWithArray: yourArray] allObjects];
you add
.h file
BOOL isSame;
NSMutableArray *countArray;
NSInteger randomNumber;
.m file
countArray=[[NSMutableArray alloc]init];
//get randon no
-(NSInteger)getRandomNo:(NSInteger)range
{
isSame=TRUE;
while (isSame){
isSame = FALSE;
randomNumber = arc4random() % range;
for (NSNumber *number in countArray){
if([number intValue] ==randomNumber){
isSame = TRUE;
break;
}
}
}
[countArray addObject:[NSNumber numberWithInt:randomNumber]];
return randomNumber;
}
Tested Please try this,
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
NSMutableSet * setUnique = [[NSMutableSet alloc] init];
for (int i=0; [setUnique count] < 10; i++) //Loop for generate different random values
{
[setUnique addObject:[NSNumber numberWithInt:arc4random() % 10]];
}
storeArray = [[setUnique allObjects] mutableCopy];
// check this how to get random number in array (i.e.. this array(below arr_numbers) contain non repeated number)
// for general purpose i am posting this.. so people cannot check for another answer
int num_count = 10;
int RandomNumber;
NSMutableArray *arr_numbers = [[NSMutableArray alloc] init];
for (int j =0; j < num_count; j++)
{
RandomNumber = 0 + arc4random() % num_count;
NSLog(#"%d",RandomNumber);
if ([arr_numbers count]>0)
{
if (![arr_numbers containsObject:[NSNumber numberWithInt:RandomNumber]])//
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
if (j == num_count-1)
{
if ([arr_numbers count] != num_count)
{
j = 0;
}
}
}
else
{
[arr_numbers addObject:[NSNumber numberWithInt:RandomNumber]];
}
}
NSLog(#"%#",arr_numbers);
Example. I've got an array with 15 objects. I want to start enumerating from a given index. Say start at index 5 and then the index above, the index under, above, under etc... I don't want it to wrap around, but rather stop and continue in unexplored direction.
So the order of indexes in my example would be.
5, 6, 4, 7, 3, 8, 2, 9, 1, 10, 0, 11, 12, 13, 14
How can this be done?
Here's a more compact implementation that doesn't require creating subarrays:
#implementation NSArray (Extensions)
- (void)enumerateFromIndex:(NSUInteger)index goBothWaysUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
{
BOOL stop = NO;
for (NSUInteger i = 0; i < self.count && !stop; i++) {
if (index + i < self.count) {
block([self objectAtIndex:index + i], index + i, &stop);
}
if (i != 0 && !stop && i <= index) {
block([self objectAtIndex:index - i], index - i, &stop);
}
}
}
#end
-(void)enumerateArray:(NSArray *)array inBothDirectionsFromIndex:(int)startIndex
{
for (int i=0; i<array.count; i++)
{
int index = startIndex;
int indexAfter = startIndex + round(i/2.f) + (i%2 ? 0 : 1);
int indexBefore = startIndex - round(i/2.f);
if ((i%2 && indexAfter < array.count) || indexBefore < 0)
{
index = indexAfter;
if (indexBefore < 0)
index -= indexBefore + 1;
}
else if ((i > 0 && indexBefore > -1) || indexAfter > array.count-1)
{
index = indexBefore;
if (indexAfter > array.count-1)
index -= indexAfter - array.count;;
}
id item = [array objectAtIndex:index];
//Do what you want with the item here
}
}
It answers the question, but is not especially DRY and creating subarrays makes it less efficient than what it should be.
#implementation NSArray (Extensions)
- (void)enumerateFromIndex:(NSUInteger)index goBothWaysUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
{
NSArray *lastObjects = [self subarrayFromIndex:index];
NSArray *firstObjects = [self subarrayToIndex:index];
int currentIndex = 0;
NSEnumerator *firstObjectsEnumerator = [firstObjects reverseObjectEnumerator];
NSEnumerator *lastObjectsEnumerator = [lastObjects objectEnumerator];
BOOL shouldStop = NO;
NSUInteger numberOfIndexesEnumerated = 0;
id obj = nil;
while(numberOfIndexesEnumerated < self.count)
{
if (obj = [lastObjectsEnumerator nextObject])
{
NSInteger objIndex = [self indexOfObject:obj];
block(obj, objIndex, &shouldStop);
currentIndex++;
numberOfIndexesEnumerated++;
}
if (shouldStop)
{
return;
}
if (obj = [firstObjectsEnumerator nextObject])
{
NSInteger objIndex = [self indexOfObject:obj];
block(obj, objIndex, &shouldStop);
currentIndex++;
numberOfIndexesEnumerated++;
}
if (shouldStop)
{
return;
}
}
}
#end
Credits to #jalmaas for this answer