Problem of the Day
A new programming or logic puzzle every Mon-Fri

Even Occurance

You are given an array of unsorted integers. The numbers of this integer contain an odd number of occurrences of all the numbers except for one. One number occurs an even number of times. Can you figure out which number occurs an even number of times?

For bonus solve it without sorting the array.

[7,4,2,6,8,9,2,4,4,5,2,7]

Answer: 7

Permalink: http://problemotd.com/problem/even-occurance/

Comments:

  • Ben - 10 years, 3 months ago

    C#

    using System;
    using System.Linq;
    
    namespace EvenOccurances
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] arr = new int[] { 7, 4, 2, 6, 8, 9, 2, 4, 4, 5, 2, 7 };
                var evens = arr.Distinct().Where(x => arr.Where(y => y == x).Count() % 2 == 0);
                Console.WriteLine(string.Join(",", evens.Select(x => x.ToString())));
                Console.Read();
            }
        }
    }
    

    reply permalink

  • John - 10 years, 3 months ago

    function listOfEvenOccurances(arr) {
      return arr.reduce(function(p,c) {
          p[c]=p[c]?p[c]+1:1; return p;
        },[]).reduce(function(p,c,i) {
          if(c%2==0)
            p.push(i);
          return p;
        },[]);
    }
    

    reply permalink

  • Vinicius Pires - 10 years, 3 months ago

    a = [7,4,2,6,8,9,2,4,4,5,2,7];
    map = {};
    
    for (var i=0;i<a.length;i++) {
      var cur = a[i];
      if ( ! map[cur] ) {
        map[cur] = 0;
      }
      map[cur]++;
    }
    
    var answer;
    for(var j in map){
      if (map[j] % 2 == 0) {
        answer = parseInt( j );
        break;
      }
    }
    

    reply permalink

  • PyBanana - 10 years, 3 months ago

    def getEvenOccurances(integers):
        return set([i for i in integers if integers.count(i) % 2 == 0])
    

    reply permalink

Content curated by @MaxBurstein