Most common array elements - Swift

I need to find the most common (modal) elements in an array. I have racked my brain for a clever way of doing it. The simplest way I could think of was to set variables for each unique element, and assign a count variable for each one, which increases every time it is recorded in a for loop which runs through the array. Unfortunately the size of the array is unknown and will be very large, so this method is useless. I have come across a similar question in Objective-C that uses an NSCountedSet method to rank the array elements. Unfortunately I am very new to programming, and could only translate the first line into swift. The suggested method is as follows

var yourArray: NSArray! // My swift translation NSCountedSet *set = [[NSCountedSet alloc] initWithArray:yourArray]; NSMutableDictionary *dict=[NSMutableDictionary new]; for (id obj in set) { [dict setObject:[NSNumber numberWithInteger:[set countForObject:obj]] forKey:obj]; //key is date } NSLog(@"Dict : %@", dict); NSMutableArray *top3=[[NSMutableArray alloc]initWithCapacity:3]; //which dict obj is = max if (dict.count>=3) { while (top3.count<3) { NSInteger max = [[[dict allValues] valueForKeyPath:@"@max.intValue"] intValue]; for (id obj in set) { if (max == [dict[obj] integerValue]) { NSLog(@"--> %@",obj); [top3 addObject:obj]; [dict removeObjectForKey:obj]; } } } } NSLog(@"top 3 = %@", top3);

In my program I will need to find the top five place names in an array. Any help would be really appreciated.

-------------Problems Reply------------

edit: now with Swift 2.0 below

Not the most efficient of solutions but a simple one:

let a = [1,1,2,3,1,7,4,6,7,2]

var frequency: [Int:Int] = [:]

for x in a {
// set frequency to the current count of this element + 1
frequency[x] = (frequency[x] ?? 0) + 1

let descending = sorted(frequency) { $0.1 > $1.1 }

descending now consists of an array of pairs: the value and the frequency, sorted most frequent first. So the “top 5” would be the first 5 entries (assuming there were 5 or more distinct values). It shouldn't matter how big the source array is.

Here's a generic function version that would work on any sequence:

func frequencies
<S: SequenceType where S.Generator.Element: Hashable>
(source: S) -> [(S.Generator.Element,Int)] {

var frequency: [S.Generator.Element:Int] = [:]

for x in source {
frequency[x] = (frequency[x] ?? 0) + 1

return sorted(frequency) { $0.1 > $1.1 }


For Swift 2.0, you can adapt the function to be a protocol extension:

extension SequenceType where Generator.Element: Hashable {
func frequencies() -> [(Generator.Element,Int)] {

var frequency: [Generator.Element:Int] = [:]

for x in self {
frequency[x] = (frequency[x] ?? 0) + 1

return frequency.sort { $0.1 > $1.1 }


Category:ios Views:0 Time:2014-12-22

Related post

  • Programming language where you can refer to a array element by . (dot) 2008-12-01

    In C# language when you refer to an array element you can write: myclass.my_array['element_name'] = new Point(1,1); I think about refering to a element with name element_name by using dot in place of backets: myclass.my_array.element_name = new Point

  • html form fields as array elements in a struts form 2008-12-16

    What I would like to do is add dynamically HTML input fields in one page, and each one of them correspond to an element of a struts array property. Let's say I have a number of identical fields in an HTML page: < input type="file" name="myfile" /

  • Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not? 2009-06-12

    I have seen it asserted several times now that the following code is not allowed by the C++ Standard: int array[5]; int *array_begin = &array[0]; int *array_end = &array[5]; Is &array[5] legal C++ code in this context? I would like an ans

  • Is there a generally accepted way to add meta information to array-elements indicating how to handle them? 2009-09-14

    I am using an array which contains the results of a database-query, which is later formatted as html (for a webapplication) or as csv (for import in a spreadsheet). I want to attach information to the array-element which has some additional informati

  • how to add array element values with javascript? 2009-11-25

    I am NOT talking about adding elements together, but their values to another separate variable. Like this: var TOTAL = 0; for (i=0; i<10; i++){ TOTAL += myArray[i] } With this code, TOTAL doesn't add mathematically element values together, but it

  • Any shortcut to initialize all array elements to zero? 2010-01-28

    In C/C++ I used to do int arr[10] = {0}; to initialize all my array elements to 0. Is there a similar shortcut in Java? I want to avoid using the loop, is it possible? int arr[] = new int[10]; for(int i=0;i<arr.length;i++) arr[i] = 0; ------------

  • Printing array elements 2010-08-01

    The expected output of the following C program is to print the array elements. But when actually run, it doesn't do so. #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main(

  • how to modify a class array element via reference 2011-04-24

    I am new to Java. I can't figure out how to do this without pointers: // hash table with seperate chaining class HashTbl { class Node { int data; Node next; } private Node tbl[]; HashTbl(int size) { tbl[] = new Node[size * 1.25]; } public int insert(

  • How to insert prefix to all array elements but first and last? 2011-12-19

    How can I add a prefix to all array elements except the first and last ones? Is there a one line solution to that? Or a 'nicer' solution than mine? result = ["svn up", "20111128025010", "20111128025022", "pass"] for i in 1..result.length-2 result[i]=

  • mongo updating array element and racing condition? 2012-02-24

    I am imagining foo is doing update on the third comment, comments.2.value, while bar is $pull-ing, removing the first comment. If foo finishes first, then the third comment is updated successfully, since the index is still correct. But if bar finishe

  • Accessing values from Dictionaries that are part of an Array in Swift 2014-09-30

    G'day, I'm trying to use a for loop to access the values for the same key within an array of dictionaries in Swift. For example, let dictionaryOne = [ "name": "Peter", "age": "42", "location": "Milwaukee"] let dictionaryTwo = [ "name": "Paul", "age":

  • How to shrink array in swift 2015-01-19

    Array in swift can grow dynamically according to the size, but it does not seem to be shrinking. var x: [Int] = [] for i in 0...1000 { x.append(i) } for i in reverse(1000...0) { x.removeAtIndex(0) } The capacity of x remains large. I also tried remov

  • How to JSON decode array elements in JavaScript? 2008-10-08

    I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be. But if I try to do a redirect or simply do an 'alert'

  • PHP Regex - /i caseless not working and weird empty array elements 2009-02-05

    Source texts (7): give 4 cars ga 5 cars GA 5 Cars @mustang six exhausts are necessary Give -1 Cars @mustang Give Cars @mustang Give 3 Cars @ford Give 5 Cars @cobra_gt The ones which should be successful ate 1,2,3,6,7 preg_match('/Give (\d+) Cars @(\w

  • C# - Why do you need to instantiate each array element? 2009-02-24

    I use this type of construct often. response = new LocationResponse (); response.LocationDetails = new LocationDetail[4]; response.LocationDetails[0] = new LocationDetail(); response.LocationDetails[0].site = "ABCDE"; ... The piece I don't fully unde

  • How can I count the unique numbers in an array without rearranging the array elements? 2009-03-05

    I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements. How can I accomplish this? --------------Solutions------------- If you have .NET 3.5 you can easily achieve this with LINQ via: in

  • LINQ for LIKE queries of array elements 2009-03-30

    Let's say I have an array, and I want to do a LINQ query against a varchar that returns any records that have an element of the array anywhere in the varchar. Something like this would be sweet. string[] industries = { "airline", "railroad" } var que

  • How to change the value of array elements 2009-04-01

    int A = 300; int B = 400; int C = 1000; int D = 500; int []abcd = {A,B,C,D}; Arrays.sort(abcd); // the sequence of array elements will be {300, 400, 500,1000} I wanted to change the value of the variables A,B,C,D according to their location in the ar

  • How do I output each Perl array element surrounded in quotes? 2009-04-11

    I want to output the elements of an array in a specific format in Perl. @myArray = ("A", "B", "C"); $text = something; Something should be the string '"A" "B" "C"' (each element enclosed in double quotes). However, if @myArray is empty, then $text sh

Copyright (C), All Rights Reserved.

processed in 0.097 (s). 11 q(s)