Created
September 26, 2017 07:32
-
-
Save SourceCode/f04d10f52b938d689a02934120938069 to your computer and use it in GitHub Desktop.
Odd Occurrences in Array - Codibility - C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| namespace ConsoleApp1 | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| int[] example = { 0, 0, 1, 2, 2, 3, 3, 0, 0, 2, 2, 2, 3, 3, 1, 8 }; | |
| var S = new Solution(); | |
| Console.WriteLine($"Our Odd Val was {S.solution(example)}"); | |
| } | |
| } | |
| class Solution | |
| { | |
| public int solution(int[] A) | |
| { | |
| var dictionary = new Dictionary<int, short>(); | |
| int? oddVal = null; | |
| for (var i = 0; i < A.Length; i++) | |
| { | |
| if (dictionary.ContainsKey(A[i])) | |
| { | |
| dictionary[A[i]] = 2; | |
| } else | |
| { | |
| dictionary.Add(A[i], 1); | |
| } | |
| } | |
| foreach (KeyValuePair<int, short> entry in dictionary) | |
| { | |
| if (entry.Value == 1) | |
| { | |
| oddVal = entry.Key; | |
| break; | |
| } | |
| } | |
| return (int)oddVal; | |
| } | |
| } | |
| } |
using System;
using System.Linq;
class Solution {
public int solution(int[] A) {
var output = A.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.Where(x=>x.Count % 2 == 1)?.FirstOrDefault()?.Value;
return output ?? 0;
}
}
Author
A lot of this code is from writing (poor) implementations for the first time in C#. By no means should anyone use it for any purpose (it totally sucks).
using System; using System.Linq;
class Solution { public int solution(int[] A) { var output = A.GroupBy(x => x) .Select(g => new {Value = g.Key, Count = g.Count()}) .Where(x=>x.Count % 2 == 1)?.FirstOrDefault()?.Value;
return output ?? 0; }}
This answer is awesome
This is another simplified solution, that does not handle if there is no "alone" element.
using System;
using System.Linq;
class Solution {
public int solution(int[] A)
{
var result = A.GroupBy(i => i).First(i => i.Count() % 2 == 1).Key;
return result;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

This code fails some of the performance test and sum up upto 66% correctness only.
