2010-04-16 8 views
13

come ottenere il valore più comune in un array Int utilizzando C#Come ottenere il valore più comune in un array Int? (C#)

es: Array ha i seguenti valori: 1, 1, 1, 2

Ans dovrebbe essere 1

+0

C'è una restrizione sul dominio dei vostri valori interi? IE. sono tutti i valori tra 0 e 10? –

+0

@ Michael Petito: Sì. Se l'intervallo non è troppo grande, può essere fatto molto velocemente. –

+0

tutti int sarà positivo e valore non superiore a 5 – mouthpiec

risposta

26
var query = (from item in array 
     group item by item into g 
     orderby g.Count() descending 
     select new { Item = g.Key, Count = g.Count() }).First(); 

solo per il valore e non il conteggio, si può fare

var query = (from item in array 
       group item by item into g 
       orderby g.Count() descending 
       select g.Key).First(); 

versione Lambda al secondo:

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First(); 
+0

+1 dangit, migliore e più veloce del mio. –

+0

Non sta facendo l'ordinamento O (nlogn)? – liori

+1

@liori: Sì. L'ordinamento non è il modo più efficace per trovare il conteggio più alto. – Guffa

14

Alcuni vecchi cicli efficienti stile:

var cnt = new Dictionary<int, int>(); 
foreach (int value in theArray) { 
    if (cnt.ContainsKey(value)) { 
     cnt[value]++; 
    } else { 
     cnt.Add(value, 1); 
    } 
} 
int mostCommonValue = 0; 
int highestCount = 0; 
foreach (KeyValuePair<int, int> pair in cnt) { 
    if (pair.Value > highestCount) { 
     mostCommonValue = pair.Key; 
     highestCount = pair.Value; 
    } 
} 

Ora mostCommonValue contiene il valore più comune, e highestCount contiene quante volte si è verificato.

+1

+1 Niente di sbagliato nell'estrarre il grasso di gomito e farlo funzionare. –

+0

Questa seconda parte potrebbe essere semplificata usando 'MaxBy()'. Peccato che non è in realtà in LINQ (ma è in [MoreLinq] (http://code.google.com/p/morelinq/wiki/OperatorsOverview)). – svick

1

Forse O (n log n), ma veloce:

sort the array a[n] 

// assuming n > 0 
int iBest = -1; // index of first number in most popular subset 
int nBest = -1; // popularity of most popular number 
// for each subset of numbers 
for(int i = 0; i < n;){ 
    int ii = i; // ii = index of first number in subset 
    int nn = 0; // nn = count of numbers in subset 
    // for each number in subset, count it 
    for (; i < n && a[i]==a[ii]; i++, nn++){} 
    // if the subset has more numbers than the best so far 
    // remember it as the new best 
    if (nBest < nn){nBest = nn; iBest = ii;} 
} 

// print the most popular value and how popular it is 
print a[iBest], nBest 
+0

All'inizio non hai detto di ordinare la matrice :). Ad ogni modo, puoi farlo più semplice se vuoi ordinare. Uno per ciclo e alcune variabili dovrebbe essere sufficiente. – IVlad

+0

@IVlad: non era la prima riga di codice? Ad ogni modo, hai ragione. –

1
public static int get_occure(int[] a) 
    { 
     int[] arr = a; 
     int c = 1, maxcount = 1, maxvalue = 0; 
     int result = 0; 
     for (int i = 0; i < arr.Length; i++) 
     { 
      maxvalue = arr[i]; 
      for (int j = 0; j <arr.Length; j++) 
      { 

       if (maxvalue == arr[j] && j != i) 
       { 
        c++; 
        if (c > maxcount) 
        { 
         maxcount = c; 
         result = arr[i]; 

        } 
       } 
       else 
       { 
        c=1; 

       } 

      } 


     } 
     return result; 
    } 
1

So che questo post è vecchio, ma qualcuno mi ha chiesto l'inverso di questa domanda oggi.

LINQ Raggruppamento

sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First(); 

Temp Collection, simile a Guffa di:

var counts = new Dictionary<int, int>(); 
foreach (var i in sourceArray) 
{ 
    if (!counts.ContainsKey(i)) { counts.Add(i, 0); } 
    counts[i]++; 
} 
return counts.OrderByDescending(kv => kv.Value).First().Key;