Getting Top 10 Highest Numbers From Array?
I am having a bit of a issue. I have an NSMutableDictionary with 10 NSMutableArrays in it. Each array has somewhere between 0-10 numbers which could each be any integer, e.g. 12 or 103.
What I need to do is get the top 10 highest numbers from across each of the arrays. The trouble is, I need to keep a reference of the array it came from in the dictionary (the key) and the index position of the number from the array it came form.
objective-c nsmutablearray nsmutabledictionary
add a comment |
I am having a bit of a issue. I have an NSMutableDictionary with 10 NSMutableArrays in it. Each array has somewhere between 0-10 numbers which could each be any integer, e.g. 12 or 103.
What I need to do is get the top 10 highest numbers from across each of the arrays. The trouble is, I need to keep a reference of the array it came from in the dictionary (the key) and the index position of the number from the array it came form.
objective-c nsmutablearray nsmutabledictionary
add a comment |
I am having a bit of a issue. I have an NSMutableDictionary with 10 NSMutableArrays in it. Each array has somewhere between 0-10 numbers which could each be any integer, e.g. 12 or 103.
What I need to do is get the top 10 highest numbers from across each of the arrays. The trouble is, I need to keep a reference of the array it came from in the dictionary (the key) and the index position of the number from the array it came form.
objective-c nsmutablearray nsmutabledictionary
I am having a bit of a issue. I have an NSMutableDictionary with 10 NSMutableArrays in it. Each array has somewhere between 0-10 numbers which could each be any integer, e.g. 12 or 103.
What I need to do is get the top 10 highest numbers from across each of the arrays. The trouble is, I need to keep a reference of the array it came from in the dictionary (the key) and the index position of the number from the array it came form.
objective-c nsmutablearray nsmutabledictionary
objective-c nsmutablearray nsmutabledictionary
edited Jul 8 '18 at 9:13
halfer
14.6k758114
14.6k758114
asked Jun 24 '12 at 12:49
Josh KahaneJosh Kahane
7,77233112217
7,77233112217
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
Easiest way, is to sort the array in Descending order, and then grab the first 10 indexes
Or if they are inside dictionaries, iterate the dictionary allValues
, grab all the arrays, add all the elements inside a common array, and sort that
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
|
show 3 more comments
It seems as if the data structure you want to end up with is an array of objects, where each object is functionally similar to an "index path" except that it's composed of a string (key) and a value (offset).
Assuming that the actual search for highest numbers isn't in question, then I'd suggest creating one of these objects whenever you find a candidate number so that, once the top ten are found, the objects can be used as back-pointers to the numbers' source locations.
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
add a comment |
Sounds like some sort of homework :)
So you have this:
NSMutableDictionary* source = [@{
@"1" : @[ @10, @20, @100 … ],
@"2" : @[ @8, @42, @17 … ]
} mutableCopy];
So lets start by creating another arrangement:
NSMutableArray* numbers = [NSMutableArray new];
for (NSArray* array in source.allValues)
{
for (NSNumber* number in array)
{
[numbers addObject: @{ @"number" : number, @"parent" : array }];
}
}
This is what we get:
@[
@{ @"number" : @10, @"parent" : <array> },
@{ @"number" : @20, @"parent" : <array> },
…
]
Now we can sort and find the numbers you wanted.
[numbers sortUsingComparator: ^( id lhs, id rhs ){
return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
}];
NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
Here we are. topNumbers contains the numbers you needed along the source array.
This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.
Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)
This line[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first@
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)
– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does thenumbers
array not want to be a dictionary?
– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.
– fabrice truillot de chambrier
Jun 24 '12 at 13:57
add a comment |
Walk through the arrays creating an object/structure for each element, consisting of the numeric "key" value and the "path" (array indices) to the element. Sort the objects/structures so created. (This is referred to as a "tag sort".)
The other approach, if you only need the top N values (where N << total number of entries) is to create an array of N elements, consisting of the above key and path info. Scan through all the arrays and compare each array element to the smallest key of the N currently stored. If you find an element larger than the smallest stored, replace the smallest stored and sort the N elements to select a new smallest stored.
add a comment |
You have to short your array in descending order using 'C' logic. Here i'm going to give an example according to your condition....
// adding 20 elements in an array, suppose this is your original array (array1).
NSMutableArray *array1 = [[NSMutableArray alloc]init];
for(int i=0;i<20;i++)
{
NSString *str = [NSString stringWithFormat:@"%d",(i*4)];
[array1 addObject:str];
}
//make a copy of your original array
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:array1];
// this is the array which will get your sorting list
NSMutableArray *array3 = [[NSMutableArray alloc]init];
//declare an integer for compare as a maximum number and it to 0 initially
int max = 0;
// this is the logic to sort an array
for(int i=0;i<20;i++)
{
for(int j=0;j<[array2 count];j++)
{
int f = [[array2 objectAtIndex:j] intValue];
if(max<f)
{
max = f;
}
}
NSString *str = [[NSNumber numberWithInt:max]stringValue];
//max has a maximum value then add it to array3 and remove from array2
//for a new shorting
[array3 addObject:str];
[array2 removeObject:str];
// set 0 to max again
max = 0;
}
//now after all procedure print the **array3**
// and you will get all the objects in descending order,
//you can take top **10** variables from **array3**
NSLog(@"your sorting array %@", **array3**);
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11177564%2fgetting-top-10-highest-numbers-from-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Easiest way, is to sort the array in Descending order, and then grab the first 10 indexes
Or if they are inside dictionaries, iterate the dictionary allValues
, grab all the arrays, add all the elements inside a common array, and sort that
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
|
show 3 more comments
Easiest way, is to sort the array in Descending order, and then grab the first 10 indexes
Or if they are inside dictionaries, iterate the dictionary allValues
, grab all the arrays, add all the elements inside a common array, and sort that
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
|
show 3 more comments
Easiest way, is to sort the array in Descending order, and then grab the first 10 indexes
Or if they are inside dictionaries, iterate the dictionary allValues
, grab all the arrays, add all the elements inside a common array, and sort that
Easiest way, is to sort the array in Descending order, and then grab the first 10 indexes
Or if they are inside dictionaries, iterate the dictionary allValues
, grab all the arrays, add all the elements inside a common array, and sort that
answered Jun 24 '12 at 13:00
Omar AbdelhafithOmar Abdelhafith
20.5k54654
20.5k54654
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
|
show 3 more comments
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
I understand this would seem obvious and relatively simple, however, I can sort them as I need to retain (or at least be able to reference) the top 10 numbers original indexes.
– Josh Kahane
Jun 24 '12 at 13:31
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
when you get the top 10 items, you could create a new array that holds the indexes of the original items in the original array
– Omar Abdelhafith
Jun 24 '12 at 13:42
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
What is confusing me though, is how when sorting the numbers can you get the index of the top numbers before they have been shuffled?
– Josh Kahane
Jun 24 '12 at 13:51
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
you dont really get the indexes, you use, [originalArray indexOfObject:(here add any object of the newly sorted array)];
– Omar Abdelhafith
Jun 24 '12 at 13:52
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
This has worked well, until I have duplicate numbers. For example, if there are two or more zeros, and I use the method use just suggested, it thinks all zeros belong to the same index. Any way of getting around this?
– Josh Kahane
Jun 24 '12 at 22:46
|
show 3 more comments
It seems as if the data structure you want to end up with is an array of objects, where each object is functionally similar to an "index path" except that it's composed of a string (key) and a value (offset).
Assuming that the actual search for highest numbers isn't in question, then I'd suggest creating one of these objects whenever you find a candidate number so that, once the top ten are found, the objects can be used as back-pointers to the numbers' source locations.
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
add a comment |
It seems as if the data structure you want to end up with is an array of objects, where each object is functionally similar to an "index path" except that it's composed of a string (key) and a value (offset).
Assuming that the actual search for highest numbers isn't in question, then I'd suggest creating one of these objects whenever you find a candidate number so that, once the top ten are found, the objects can be used as back-pointers to the numbers' source locations.
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
add a comment |
It seems as if the data structure you want to end up with is an array of objects, where each object is functionally similar to an "index path" except that it's composed of a string (key) and a value (offset).
Assuming that the actual search for highest numbers isn't in question, then I'd suggest creating one of these objects whenever you find a candidate number so that, once the top ten are found, the objects can be used as back-pointers to the numbers' source locations.
It seems as if the data structure you want to end up with is an array of objects, where each object is functionally similar to an "index path" except that it's composed of a string (key) and a value (offset).
Assuming that the actual search for highest numbers isn't in question, then I'd suggest creating one of these objects whenever you find a candidate number so that, once the top ten are found, the objects can be used as back-pointers to the numbers' source locations.
edited Jun 24 '12 at 13:20
answered Jun 24 '12 at 12:59
Phillip MillsPhillip Mills
28.5k33452
28.5k33452
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
add a comment |
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Not sure I follow you. Use the top 10 numbers found as back pointers? But what if there are duplicate numbers? How would you match it to the correct original index?
– Josh Kahane
Jun 24 '12 at 13:01
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
Use the object containing the dictionary key and the array index as a path to the original.
– Phillip Mills
Jun 24 '12 at 13:17
add a comment |
Sounds like some sort of homework :)
So you have this:
NSMutableDictionary* source = [@{
@"1" : @[ @10, @20, @100 … ],
@"2" : @[ @8, @42, @17 … ]
} mutableCopy];
So lets start by creating another arrangement:
NSMutableArray* numbers = [NSMutableArray new];
for (NSArray* array in source.allValues)
{
for (NSNumber* number in array)
{
[numbers addObject: @{ @"number" : number, @"parent" : array }];
}
}
This is what we get:
@[
@{ @"number" : @10, @"parent" : <array> },
@{ @"number" : @20, @"parent" : <array> },
…
]
Now we can sort and find the numbers you wanted.
[numbers sortUsingComparator: ^( id lhs, id rhs ){
return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
}];
NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
Here we are. topNumbers contains the numbers you needed along the source array.
This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.
Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)
This line[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first@
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)
– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does thenumbers
array not want to be a dictionary?
– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.
– fabrice truillot de chambrier
Jun 24 '12 at 13:57
add a comment |
Sounds like some sort of homework :)
So you have this:
NSMutableDictionary* source = [@{
@"1" : @[ @10, @20, @100 … ],
@"2" : @[ @8, @42, @17 … ]
} mutableCopy];
So lets start by creating another arrangement:
NSMutableArray* numbers = [NSMutableArray new];
for (NSArray* array in source.allValues)
{
for (NSNumber* number in array)
{
[numbers addObject: @{ @"number" : number, @"parent" : array }];
}
}
This is what we get:
@[
@{ @"number" : @10, @"parent" : <array> },
@{ @"number" : @20, @"parent" : <array> },
…
]
Now we can sort and find the numbers you wanted.
[numbers sortUsingComparator: ^( id lhs, id rhs ){
return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
}];
NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
Here we are. topNumbers contains the numbers you needed along the source array.
This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.
Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)
This line[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first@
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)
– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does thenumbers
array not want to be a dictionary?
– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.
– fabrice truillot de chambrier
Jun 24 '12 at 13:57
add a comment |
Sounds like some sort of homework :)
So you have this:
NSMutableDictionary* source = [@{
@"1" : @[ @10, @20, @100 … ],
@"2" : @[ @8, @42, @17 … ]
} mutableCopy];
So lets start by creating another arrangement:
NSMutableArray* numbers = [NSMutableArray new];
for (NSArray* array in source.allValues)
{
for (NSNumber* number in array)
{
[numbers addObject: @{ @"number" : number, @"parent" : array }];
}
}
This is what we get:
@[
@{ @"number" : @10, @"parent" : <array> },
@{ @"number" : @20, @"parent" : <array> },
…
]
Now we can sort and find the numbers you wanted.
[numbers sortUsingComparator: ^( id lhs, id rhs ){
return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
}];
NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
Here we are. topNumbers contains the numbers you needed along the source array.
This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.
Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)
Sounds like some sort of homework :)
So you have this:
NSMutableDictionary* source = [@{
@"1" : @[ @10, @20, @100 … ],
@"2" : @[ @8, @42, @17 … ]
} mutableCopy];
So lets start by creating another arrangement:
NSMutableArray* numbers = [NSMutableArray new];
for (NSArray* array in source.allValues)
{
for (NSNumber* number in array)
{
[numbers addObject: @{ @"number" : number, @"parent" : array }];
}
}
This is what we get:
@[
@{ @"number" : @10, @"parent" : <array> },
@{ @"number" : @20, @"parent" : <array> },
…
]
Now we can sort and find the numbers you wanted.
[numbers sortUsingComparator: ^( id lhs, id rhs ){
return [((NSDictionary*) rhs)[@"number"] compare: ((NSDictionary*) lhs)[@"number"]];
}];
NSArray* topNumbers = [numbers subarrayWithRange: NSMakeRange( 0, 10 )];
Here we are. topNumbers contains the numbers you needed along the source array.
This is quite a naive way to do it. It can be optimized both in CPU time and memory usage by a fair amount. But hey, keep it simple is not a bad thing.
Not addressed: what if the tenth and eleventh numbers are equal? (adressed here: Pick Out Specific Number from Array?) range checks. not tested, not even compiled. ;)
edited May 23 '17 at 12:04
Community♦
11
11
answered Jun 24 '12 at 13:15
fabrice truillot de chambrierfabrice truillot de chambrier
5,24412021
5,24412021
This line[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first@
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)
– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does thenumbers
array not want to be a dictionary?
– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.
– fabrice truillot de chambrier
Jun 24 '12 at 13:57
add a comment |
This line[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first@
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)
– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does thenumbers
array not want to be a dictionary?
– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.
– fabrice truillot de chambrier
Jun 24 '12 at 13:57
This line
[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first @
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)– Josh Kahane
Jun 24 '12 at 13:28
This line
[numbers addObject: @{ @"number" : number, @"parent" : array }];
is throwing an error because of the first @
, but why? Sorry I haven't seen an objet being added to an array like this before. (Thanks for your answer!)– Josh Kahane
Jun 24 '12 at 13:28
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Xcode 4.4/4.5 with literals. You can use NSDictionary -dictionaryWithObjectsAndKeys: instead, and NSArray -arrayWithObjects: instead, but so much verbose. @{} -> NSDictionary, @ -> NSArray, @10 -> NSNumber.
– fabrice truillot de chambrier
Jun 24 '12 at 13:33
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does the
numbers
array not want to be a dictionary?– Josh Kahane
Jun 24 '12 at 13:38
Ahh! That will be the issue, Im on 4.3.3. Thanks for explaining that. Also, if Im not mistaken, does the
numbers
array not want to be a dictionary?– Josh Kahane
Jun 24 '12 at 13:38
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
Also, won't having multiple objects with the same key fail?
– Josh Kahane
Jun 24 '12 at 13:45
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.
numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.– fabrice truillot de chambrier
Jun 24 '12 at 13:57
You'll love the literals when you'll be able to use them. [NSDictionary dictionaryWithObjectsAndKeys: ...] sucks so much. Well. I do not know what are the keys of your original dictionary. It doesn't matter anyway, I do not use them.
numbers
is an array I can sort, containing an entry for every number in your original dictionary's arrays. Each entry is a dictionary containing the number (value for key @"number") and the source array (key @"parent"). No conflicts there. It's an index. Nothing more.– fabrice truillot de chambrier
Jun 24 '12 at 13:57
add a comment |
Walk through the arrays creating an object/structure for each element, consisting of the numeric "key" value and the "path" (array indices) to the element. Sort the objects/structures so created. (This is referred to as a "tag sort".)
The other approach, if you only need the top N values (where N << total number of entries) is to create an array of N elements, consisting of the above key and path info. Scan through all the arrays and compare each array element to the smallest key of the N currently stored. If you find an element larger than the smallest stored, replace the smallest stored and sort the N elements to select a new smallest stored.
add a comment |
Walk through the arrays creating an object/structure for each element, consisting of the numeric "key" value and the "path" (array indices) to the element. Sort the objects/structures so created. (This is referred to as a "tag sort".)
The other approach, if you only need the top N values (where N << total number of entries) is to create an array of N elements, consisting of the above key and path info. Scan through all the arrays and compare each array element to the smallest key of the N currently stored. If you find an element larger than the smallest stored, replace the smallest stored and sort the N elements to select a new smallest stored.
add a comment |
Walk through the arrays creating an object/structure for each element, consisting of the numeric "key" value and the "path" (array indices) to the element. Sort the objects/structures so created. (This is referred to as a "tag sort".)
The other approach, if you only need the top N values (where N << total number of entries) is to create an array of N elements, consisting of the above key and path info. Scan through all the arrays and compare each array element to the smallest key of the N currently stored. If you find an element larger than the smallest stored, replace the smallest stored and sort the N elements to select a new smallest stored.
Walk through the arrays creating an object/structure for each element, consisting of the numeric "key" value and the "path" (array indices) to the element. Sort the objects/structures so created. (This is referred to as a "tag sort".)
The other approach, if you only need the top N values (where N << total number of entries) is to create an array of N elements, consisting of the above key and path info. Scan through all the arrays and compare each array element to the smallest key of the N currently stored. If you find an element larger than the smallest stored, replace the smallest stored and sort the N elements to select a new smallest stored.
edited Jun 24 '12 at 14:10
answered Jun 24 '12 at 14:04
Hot LicksHot Licks
38k1578134
38k1578134
add a comment |
add a comment |
You have to short your array in descending order using 'C' logic. Here i'm going to give an example according to your condition....
// adding 20 elements in an array, suppose this is your original array (array1).
NSMutableArray *array1 = [[NSMutableArray alloc]init];
for(int i=0;i<20;i++)
{
NSString *str = [NSString stringWithFormat:@"%d",(i*4)];
[array1 addObject:str];
}
//make a copy of your original array
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:array1];
// this is the array which will get your sorting list
NSMutableArray *array3 = [[NSMutableArray alloc]init];
//declare an integer for compare as a maximum number and it to 0 initially
int max = 0;
// this is the logic to sort an array
for(int i=0;i<20;i++)
{
for(int j=0;j<[array2 count];j++)
{
int f = [[array2 objectAtIndex:j] intValue];
if(max<f)
{
max = f;
}
}
NSString *str = [[NSNumber numberWithInt:max]stringValue];
//max has a maximum value then add it to array3 and remove from array2
//for a new shorting
[array3 addObject:str];
[array2 removeObject:str];
// set 0 to max again
max = 0;
}
//now after all procedure print the **array3**
// and you will get all the objects in descending order,
//you can take top **10** variables from **array3**
NSLog(@"your sorting array %@", **array3**);
}
add a comment |
You have to short your array in descending order using 'C' logic. Here i'm going to give an example according to your condition....
// adding 20 elements in an array, suppose this is your original array (array1).
NSMutableArray *array1 = [[NSMutableArray alloc]init];
for(int i=0;i<20;i++)
{
NSString *str = [NSString stringWithFormat:@"%d",(i*4)];
[array1 addObject:str];
}
//make a copy of your original array
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:array1];
// this is the array which will get your sorting list
NSMutableArray *array3 = [[NSMutableArray alloc]init];
//declare an integer for compare as a maximum number and it to 0 initially
int max = 0;
// this is the logic to sort an array
for(int i=0;i<20;i++)
{
for(int j=0;j<[array2 count];j++)
{
int f = [[array2 objectAtIndex:j] intValue];
if(max<f)
{
max = f;
}
}
NSString *str = [[NSNumber numberWithInt:max]stringValue];
//max has a maximum value then add it to array3 and remove from array2
//for a new shorting
[array3 addObject:str];
[array2 removeObject:str];
// set 0 to max again
max = 0;
}
//now after all procedure print the **array3**
// and you will get all the objects in descending order,
//you can take top **10** variables from **array3**
NSLog(@"your sorting array %@", **array3**);
}
add a comment |
You have to short your array in descending order using 'C' logic. Here i'm going to give an example according to your condition....
// adding 20 elements in an array, suppose this is your original array (array1).
NSMutableArray *array1 = [[NSMutableArray alloc]init];
for(int i=0;i<20;i++)
{
NSString *str = [NSString stringWithFormat:@"%d",(i*4)];
[array1 addObject:str];
}
//make a copy of your original array
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:array1];
// this is the array which will get your sorting list
NSMutableArray *array3 = [[NSMutableArray alloc]init];
//declare an integer for compare as a maximum number and it to 0 initially
int max = 0;
// this is the logic to sort an array
for(int i=0;i<20;i++)
{
for(int j=0;j<[array2 count];j++)
{
int f = [[array2 objectAtIndex:j] intValue];
if(max<f)
{
max = f;
}
}
NSString *str = [[NSNumber numberWithInt:max]stringValue];
//max has a maximum value then add it to array3 and remove from array2
//for a new shorting
[array3 addObject:str];
[array2 removeObject:str];
// set 0 to max again
max = 0;
}
//now after all procedure print the **array3**
// and you will get all the objects in descending order,
//you can take top **10** variables from **array3**
NSLog(@"your sorting array %@", **array3**);
}
You have to short your array in descending order using 'C' logic. Here i'm going to give an example according to your condition....
// adding 20 elements in an array, suppose this is your original array (array1).
NSMutableArray *array1 = [[NSMutableArray alloc]init];
for(int i=0;i<20;i++)
{
NSString *str = [NSString stringWithFormat:@"%d",(i*4)];
[array1 addObject:str];
}
//make a copy of your original array
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:array1];
// this is the array which will get your sorting list
NSMutableArray *array3 = [[NSMutableArray alloc]init];
//declare an integer for compare as a maximum number and it to 0 initially
int max = 0;
// this is the logic to sort an array
for(int i=0;i<20;i++)
{
for(int j=0;j<[array2 count];j++)
{
int f = [[array2 objectAtIndex:j] intValue];
if(max<f)
{
max = f;
}
}
NSString *str = [[NSNumber numberWithInt:max]stringValue];
//max has a maximum value then add it to array3 and remove from array2
//for a new shorting
[array3 addObject:str];
[array2 removeObject:str];
// set 0 to max again
max = 0;
}
//now after all procedure print the **array3**
// and you will get all the objects in descending order,
//you can take top **10** variables from **array3**
NSLog(@"your sorting array %@", **array3**);
}
edited Jan 2 at 4:58
answered Jun 24 '12 at 13:15
TheTigerTheTiger
10.9k34467
10.9k34467
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11177564%2fgetting-top-10-highest-numbers-from-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown