How to create an array of CGPoints by pairing values from two different NSArrays in objective-c?
Lets say I have an Array "A" with the values: 0, 1, 2, 3, 4
And I also have an Array "B" with the values: 21, 30, 33, 35, 31
I would like to create Array "AB" with CGPoint values: (0,21), (1,30), (2,33), (3,35), (4,31)
Thanks for your help.
Note that Objective-C collection classes can only hold objects, so I have assumed your input numbers are held in NSNumber objects. This also means that the CGPoint structs must be held in a NSValue object in the combined array:
NSArray *array1 = ...;
NSArray *array2 = ...;
NSMutableArray *pointArray = [[NSMutableArray alloc] init];
if ([array1 count] == [array2 count])
{
NSUInteger count = [array1 count], i;
for (i = 0; i < count; i++)
{
NSNumber *num1 = [array1 objectAtIndex:i];
NSNumber *num2 = [array2 objectAtIndex:i];
CGPoint point = CGPointMake([num1 floatValue], [num2 floatValue]);
[pointArray addObject:[NSValue valueWithCGPoint:point]];
}
}
else
{
NSLog(#"Array count mis-matched");
}
Someone else posted on making an NSArray of CGPoints, but you asked for an array of CGPoints. This ought to do that:
NSArray* a = #[ #(0.), #(1.), #(2.), #(3.), #(4.) ];
NSArray* b = #[ #(21.), #(30.), #(33.), #(35.), #(31.) ];
const NSUInteger aCount = a.count, bCount = b.count, count = MAX(aCount, bCount);
CGPoint* points = (CGPoint*)calloc(count, sizeof(CGPoint));
for (NSUInteger i = 0; i < count; ++i)
{
points[i] = CGPointMake(i < aCount ? [a[i] doubleValue] : 0 , i < bCount ? [b[i] doubleValue] : 0.0);
}
Related
I have an array inside an array named as officeList in the following format :-
(
(
Prospect,
Propose
),
(
Open,
Fund,
Propose
),
(
Settle,
Review
)
)
Problem is I got this array by converting the JSON file into an array and as a result of that I got this array of string inside an array. What I want is to fetch each value one by one like : "prospect", "propose", etc.
I am using following code to fetch data :
for (int i = 0;i<[_officelist count];i++)
{
id val=[officeSize objectAtIndex:i];
CGFloat val1=[val floatValue];
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, 20,val1,15)];
newLabel.text=[NSString stringWithFormat:#"%#",_officelist[i]];
newLabel.textAlignment = NSTextAlignmentCenter;
[self.roadmapCollectionView addSubview:newLabel];
x=x+val1;
}
Have you try this
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (NSArray *objArr in jsonArr) {
for (NSString *str in ObjArr) {
[arr addObject:str];
}
}
Here jsonArr is the array that you getting from response. Now use arr to access every object that you want.
Hope this will help you
Apply below code,
for (int i = 0; i < [_officelist count]; i++)
{
NSArray *valList=[_officelist objectAtIndex:i];
CGFloat val1 = [valList floatValue]; // Your Float val
for (int j = 0; j < [valList count]; j++)
{
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, 20,val1,15)];
newLabel.text = [NSString stringWithFormat:#"%#",valList[j]];
newLabel.textAlignment = NSTextAlignmentCenter;
[self.roadmapCollectionView addSubview:newLabel];
}
x=x+val1;
}
Hope this helps you.
I am sorting an array.
There are three types of elements in the array.
1. featured
2. organic and
3. claimed.
Among them, I want to sort only organic elements and keep the featured and claimed elements at their own index.
Below is my code in which, I am extracting the claimed and featured indices in a dictionary as key being the index and value is the array element.
//Initialization
NSMutableArray *sortedArray = nil;
NSMutableDictionary *tempFeaturedDictionary = [[NSMutableDictionary alloc]init];
NSMutableDictionary *tempClaimedDictionary = [[NSMutableDictionary alloc]init];
NSMutableArray *tempOrganicArray = [[NSMutableArray alloc]init];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)[array objectAtIndex:i];
if (isFeaturedObj.featured) {
[tempFeaturedDictionary setObject:isFeaturedObj forKey:[#(i)stringValue]];
}else if (isFeaturedObj.claimed)
{
[tempClaimedDictionary setObject:isFeaturedObj forKey:[#(i)stringValue]];
}else
[tempOrganicArray addObject:isFeaturedObj];
}
Again I am adding the claimed and featured back to their original indices after sorting as:
sortedArray = [NSMutableArray arrayWithArray:[tempOrganicArray sortedArrayUsingDescriptors:sortDescriptorsArray]];
for (int i = 0; i<sortedArray.count; i++) {
for (NSString *key in tempFeaturedDictionary) {
if ( [[#(i)stringValue] isEqualToString: key] ) {
[sortedArray insertObject:[tempFeaturedDictionary objectForKey:[#(i)stringValue]] atIndex:i];
}}
for (NSString *key in tempClaimedDictionary) {
if ([[#(i)stringValue]isEqualToString:key ]) {
[sortedArray insertObject:[tempClaimedDictionary objectForKey:[#(i)stringValue]] atIndex:i];
}
}
}
The code works good. Except there is claimed/(and)featured elements at the last index of the 'array'. Because the 'sortedArray' index remains less than the 'array.count' in this scenario.
Thanks in advance.
Update -
I receive response array of type:
[{featured1 featured2}, {organic1, organic2..}, {claimed1}, {featured11, featured12}, {organic11, organic12..}, {claimed2}, ..]
and I am allowed to sort only organic elements within this array. Featured and claimed should not loose their original index position.
I would iterate through the array, extracting the organics to sort. Then sort your organic array. Then iterate through the original array taking either the element from the original array or an element from the sorted organics array as appropriate.
NSMutableArray *organicsArray = [NSMutableArray new];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)array[i];
if ((!isFeaturedObj.featured) && (!isFeaturedObj.claimed)) {
[organicsArray addObject:isFeaturedObj];
}
}
NSMutableArray *sortedOrganicsArray = [[organicsArray sortedArrayUsingDescriptors:sortDescriptorsArray] mutableCopy];
NSMutableArray *outputArray = [NSMutableArray new];
for (int i = 0; i < array.count; i++) {
DRListing *isFeaturedObj = (DRListing*)array[i];
if ((!isFeaturedObj.featured) && (!isFeaturedObj.claimed)) {
[outputArray addObject:sortedOrganicsArray[0]];
[sortedOrganicsArray removeObjectAtIndex:0];
} else {
[outputArray addObject:isFeaturedObject];
}
}
You could possibly make it a little more efficient if you reversed your sort order for the organics array since then you could say
[outputArray addObject:[sortedOrganicsArray lastObject]];
[sortedOrganicsArray removeLastObject];
But if your array isn't particularly large then the performance improvement will probably be negligible.
Maybe this is an alternative:
NSMutableArray *organics = [NSMutableArray new];
NSMutableArray *others = [NSMutableArray new];
for (DRListing *isFeaturedObj in array) {
if (isFeaturedObj.organic) {
[organics addObject:isFeaturedObj];
} else {
[others addObject:isFeaturedObj];
}
}
NSMutableArray *sorted = [NSMutableArray alloc]initWithObjects:organics,others, nil];
You can take the first 2 functions. The others are what I used for testing.
- (DRListing *)getNextObjectFromArray:(NSArray *)array WithStartingIndex:(int)index
{
for (int i=index; i<array.count; i++) {
DRListing *obj = (DRListing*)[array objectAtIndex:i];
if (!obj.featured && !obj.claimed)
{
return obj;
}
}
return nil;
}
- (void)sortArray:(NSMutableArray *)array
{
for (int pass = 0; pass<array.count-1; pass++) {
for (int i=0; i<array.count-1; i++) {
DRListing *obj = [self getNextObjectFromArray:array WithStartingIndex:i];
int foundIndex = (int)[array indexOfObject:obj];
DRListing *obj2 = [self getNextObjectFromArray:array WithStartingIndex:foundIndex+1];
int foundIndex2 = (int)[array indexOfObject:obj2];
if (obj!=nil && obj2 !=nil) {
if (obj.value >= obj2.value) {
[array exchangeObjectAtIndex:foundIndex withObjectAtIndex:foundIndex2];
}
i = foundIndex;
}
}
}
NSLog(#"Sorted Data: %#",array);
}
- (NSMutableArray *)testData
{
NSMutableArray *array = [NSMutableArray new];
for (int i=0; i<20; i++) {
DRListing *obj = [DRListing new];
obj.featured = i*i%2;
obj.claimed = i%2;
obj.value = i*3%10;
[array addObject:obj];
}
NSLog(#"Test Data: %#",array);
return array;
}
#interface DRListing : NSObject
#property (nonatomic) BOOL featured;
#property (nonatomic) BOOL claimed;
#property (nonatomic) int value;
#end
I have a PickerView and I want to initialize it with integer values. For example PickerView with all integers lower than 10.
Thank you
NSArray *array =[NSArray arrayWithObjects:#1,#2,#3,#4,#5,#6,#7,#8,#9,nil];
NSMutableArray *yourArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[yourArray addObject:[NSNumber numberWithInt:i]];
}
NSInteger min = 1;
NSInteger max = 10;
NSInteger step = 1;
NSMutableArray<NSNumber *> *options = [NSMutableArray new];
for (NSInteger index = 0; index < ceilf(((float)max)/step); index++)
{
options[index] = #((index + min) * step);
}
NSLog(#"%#",options);
An alternate approach:
NSInteger from = 1;
NSInteger size = 10;
NSInteger step = 1;
NSMutableArray<NSNumber *> *options = [NSMutableArray new];
for (NSInteger index = 0; index < size; index++)
{
options[index] = #((index + from) * step);
}
NSLog(#"%#",options);
Both of the above print the following:
(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
)
int yourInt = 5;
[myMutableArray addObject:[NSNumber numberWithInt:yourInt]]; have look on this
It will just sample code to add the int value to the array nothing else
I need to get the highest repeated character in string and the count of the repeated character.
For that i stored the each character of the string in the array and using the for loops i got each character and the count. is there any other delegate methods to find it to reduce the code?
for example
NSRange theRange = {0, 1}; //{location, length}
NSMutableArray * array = [NSMutableArray array];
for ( NSInteger i = 0; i < [myFormattedString length]; i++) {
theRange.location = i;
[array addObject:[myFormattedString substringWithRange:theRange]];
}
int countForChar = 0;
for (int i=0; i<[array count]; i++) {
NSString *firstCharacter = [array objectAtIndex:i];
for (int j=1; j< [array count]; j++) {
if ([firstCharacter isEqualToString:[array objectAtIndex:j]]) {
countForChar = countForChar + 1;
}
}
NSLog(#"The Charcter is %# The count is %d", firstCharacter, countForChar);
countForChar = 0;
}
Thanks in advance...
Because the string may have more than a char have same most repeat count, so here is my solution:
- (NSArray *)mostCharInString:(NSString *)string count:(int *)count{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
int len = string.length;
NSRange theRange = {0, 1};
for (NSInteger i = 0; i < len; i++) {
theRange.location = i;
NSString *charStr = [string substringWithRange:theRange];
int preCount = 0;
if ([dict objectForKey:charStr]) {
preCount = [[dict objectForKey:charStr] unsignedIntegerValue];
}
[dict setObject:#(preCount+1) forKey:charStr];
}
NSArray *sortValues = [[dict allValues] sortedArrayUsingSelector:#selector(compare:)];
*count = [[sortValues lastObject] unsignedIntegerValue];
return [dict allKeysForObject:#(*count)];
}
How to use and test:
int mostRepeatCount = 0;
NSArray *mostChars = nil;
mostChars = [self mostCharInString:#"aaabbbcccc" count:&mostRepeatCount];
NSLog(#"count:%d char:%#", mostRepeatCount, mostChars);
the result is:
count:4 char:(
c
)
try:
mostChars = [self mostCharInString:#"aaabbbccccdddd" count:&mostRepeatCount];
the result is:
count:4 char:(
d,
c
)
Hope to help you.
Here is my code might be not good enough but I think its the fastest
NSString *myFormattedString = #"oksdflajdsfd";
NSMutableDictionary *lettersCount = [[NSMutableDictionary alloc] init];
for (NSInteger i = 0; i < [myFormattedString length]; i++) {
unichar charAtIndex = [myFormattedString characterAtIndex:i];
NSNumber *countForThisChar = [lettersCount objectForKey:[NSString stringWithFormat:#"%c",charAtIndex]];
int count = 1;
if(countForThisChar) {
count = [countForThisChar integerValue] + 1;
[lettersCount setObject:#(count) forKey:[NSString stringWithFormat:#"%c",charAtIndex]];
} else {
// not added yet, add it with 1 count
[lettersCount setObject:#(count) forKey:[NSString stringWithFormat:#"%c",charAtIndex]];
}
}
// for now the work is O(n)
// ignoring the work of this cycle or consider it as O(1)
NSString *mostFrequentChar = nil;
NSInteger maxCount = 0;
for(NSString *oneChar in lettersCount.keyEnumerator) {
NSNumber *count = [lettersCount objectForKey:oneChar];
if([count integerValue] > maxCount) {
mostFrequentChar = oneChar;
maxCount = [count integerValue];
}
}
NSLog(#"the char %# met for %d times", mostFrequentChar, maxCount);
Remember the search for an object in NsDictionary is O(1) for the average case scenario.
Here is an example that would work correctly with any string and has linear time complexity. This uses the NSCountedSet which can be pretty useful.
NSString* string = #"This is a very wonderful string. Ølsen & ジェイソン";
NSCountedSet* characterCounts = [[NSCountedSet alloc] init];
// This ensures that we deal with all unicode code points correctly
[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characterCounts addObject:substring];
}];
NSString* highestCountCharacterSequence = nil;
NSUInteger highestCharacterCount = 0;
for (NSString* characterSequence in characterCounts) {
NSUInteger currentCount = [characterCounts countForObject:characterSequence];
if (currentCount > highestCharacterCount) {
highestCountCharacterSequence = characterSequence;
highestCharacterCount = currentCount;
}
}
NSLog(#"Highest Character Count is %# with count of %lu", highestCountCharacterSequence, (unsigned long)highestCharacterCount);
Sadly, my silly example string ends up having space characters as the most repeated :)
Every character can be presented by its int value. Make an instance of NSArray with n size (n number of unique characters string can have). Loop through string and add +1 on (int)character index in array at every cycle. When you finish the character with greatest value in array is the highest repeated character.
I want to compare 2 NSMutableArray and get different object into third Array. How can i do that ?
Array1 can loop object .
Array1 = "a", "b","c","d","a","b","c";
Array2 = "a", "b", "c";
And then result
Array3 = "d";
Thanks in advance
Use sets for set operations:
NSSet *set1 = [NSSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2];
[set2 minusSet:set1];
You Can try this too.
NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"1", nil];
NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:#"2",#"1", nil];
NSMutableArray *largeArray;
NSMutableArray *shortArray;
if([array1 count] > [array2 count]){
largeArray = array1;
shortArray = array2;
} else {
largeArray = array2;
shortArray = array1;
}
[largeArray removeObjectsInArray:shortArray];
for (NSString *va in largeArray) {
NSLog(#"%#",va);
}
NSMutableArray *gotDiffArry= [[NSMutableArray alloc] init];
for(int i = 0 ; i < FirstArray.count; i++) {
if(i < seconArray.count){
if(![seconArray[i] isEqual:firstArray[i]]){
[gotDiffArry addObject:[NSNumber numberWithInt:i]];
}
} else {
[gotDiffArry addObject:[NSNumber numberWithInt:i]];
}
}
EDITED:
for (int i = 0 ; i < firstArray.count ; i ++)
{
NSString *search = [firstArray objectAtIndex:i];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY SELF CONTAINS %#", search];
NSMutableArray *temAraay = [secondArray filteredArrayUsingPredicate: predicate];
if(temArray.count >=0 )
{
NSLog("%#", [temArray objectAtIndex:0]);
}
}
I have used the following and got the desired results:
for(int i =0; i<[arraytwo count]; i++)
{
if (![arrayone containsObject:[arraytwo objectAtIndex:i]])
[arraythree addObject: [arraytwo obectAtIndex:i]];
}
NSLog(#"%#",arraythree);