Most common occurrence of an int in an arrayFind the odd occurrences in an arrayLongest Common Prefix in an...
How did Arya survive the stabbing?
How to be diplomatic in refusing to write code that breaches the privacy of our users
Would a high gravity rocky planet be guaranteed to have an atmosphere?
How to Reset Passwords on Multiple Websites Easily?
Is there a good way to store credentials outside of a password manager?
Was Spock the First Vulcan in Starfleet?
Why Were Madagascar and New Zealand Discovered So Late?
Sort a list by elements of another list
How is it posible to add a double into an ArrayList of Integer? (Java)
Go Pregnant or Go Home
Does the Brexit deal have to be agreed by both Houses?
Where does the Z80 processor start executing from?
Why not increase contact surface when reentering the atmosphere?
How does it work when somebody invests in my business?
Abbreviate author names as "Lastname AB" (without space or period) in bibliography
Grabbing quick drinks
Apart from "berlinern", do any other German dialects have a corresponding verb?
'Given that' in a matrix
Is HostGator storing my password in plaintext?
Only print output after finding pattern
Opposite of a diet
Does the Vanguard Style bonus stack with itself?
Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?
Magento 2 custom phtml file not calling to all products view pages
Most common occurrence of an int in an array
Find the odd occurrences in an arrayLongest Common Prefix in an array of StringsFinding all integers in an array with odd occurrenceFind the common element in two int arraysFinding the most common character in a string with a hash mapTuple<int, int> replacementMaximum product of 3 integers in an int arrayImplementing common fraction using TDDAnalysis of the most common words in a textOdd Occurrence ArrayLongest common subsequence solution
$begingroup$
I am prepping for a junior level interview in C#. I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int
in an array.
using System;
using System.Collections;
namespace FrequentInt
{
class MainClass
{
static void CommomOcurrence (int [] array, Hashtable hs)
{
int mostCommom = array[0];
int occurences = 0;
foreach (int num in array)
{
if (!hs.ContainsKey (num)) {
hs.Add (num, 1);
}
else
{
int tempOccurences = (int)hs [num];
tempOccurences++;
hs.Remove (num);
hs.Add (num, tempOccurences);
if (occurences < tempOccurences)
{
occurences = tempOccurences;
mostCommom = num;
}
}
}
foreach(DictionaryEntry entry in hs)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}
Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
}
public static void Main (string[] args)
{
int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7};
Hashtable hs = new Hashtable ();
CommomOcurrence (array, hs);
}
}
}
c# interview-questions hash-table
$endgroup$
add a comment |
$begingroup$
I am prepping for a junior level interview in C#. I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int
in an array.
using System;
using System.Collections;
namespace FrequentInt
{
class MainClass
{
static void CommomOcurrence (int [] array, Hashtable hs)
{
int mostCommom = array[0];
int occurences = 0;
foreach (int num in array)
{
if (!hs.ContainsKey (num)) {
hs.Add (num, 1);
}
else
{
int tempOccurences = (int)hs [num];
tempOccurences++;
hs.Remove (num);
hs.Add (num, tempOccurences);
if (occurences < tempOccurences)
{
occurences = tempOccurences;
mostCommom = num;
}
}
}
foreach(DictionaryEntry entry in hs)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}
Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
}
public static void Main (string[] args)
{
int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7};
Hashtable hs = new Hashtable ();
CommomOcurrence (array, hs);
}
}
}
c# interview-questions hash-table
$endgroup$
add a comment |
$begingroup$
I am prepping for a junior level interview in C#. I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int
in an array.
using System;
using System.Collections;
namespace FrequentInt
{
class MainClass
{
static void CommomOcurrence (int [] array, Hashtable hs)
{
int mostCommom = array[0];
int occurences = 0;
foreach (int num in array)
{
if (!hs.ContainsKey (num)) {
hs.Add (num, 1);
}
else
{
int tempOccurences = (int)hs [num];
tempOccurences++;
hs.Remove (num);
hs.Add (num, tempOccurences);
if (occurences < tempOccurences)
{
occurences = tempOccurences;
mostCommom = num;
}
}
}
foreach(DictionaryEntry entry in hs)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}
Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
}
public static void Main (string[] args)
{
int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7};
Hashtable hs = new Hashtable ();
CommomOcurrence (array, hs);
}
}
}
c# interview-questions hash-table
$endgroup$
I am prepping for a junior level interview in C#. I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int
in an array.
using System;
using System.Collections;
namespace FrequentInt
{
class MainClass
{
static void CommomOcurrence (int [] array, Hashtable hs)
{
int mostCommom = array[0];
int occurences = 0;
foreach (int num in array)
{
if (!hs.ContainsKey (num)) {
hs.Add (num, 1);
}
else
{
int tempOccurences = (int)hs [num];
tempOccurences++;
hs.Remove (num);
hs.Add (num, tempOccurences);
if (occurences < tempOccurences)
{
occurences = tempOccurences;
mostCommom = num;
}
}
}
foreach(DictionaryEntry entry in hs)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}
Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
}
public static void Main (string[] args)
{
int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7};
Hashtable hs = new Hashtable ();
CommomOcurrence (array, hs);
}
}
}
c# interview-questions hash-table
c# interview-questions hash-table
edited Aug 8 '15 at 16:58
Jamal♦
30.4k11121227
30.4k11121227
asked Aug 8 '15 at 16:53
AaronAaron
4981715
4981715
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
$begingroup$
The one thing I find really wrong is that you're using a HashTable
.
It is not generic, which means it will box every int
to an object.
Use a Dictionary<int, int>
instead.
And there is no reason to supply it as a parameter: it should be local to the method, so declare it there.
Last thing: you don't need the if-else
to check if a Key
is present.Dictionary
has a method TryGetValue
for that. It also has an indexer.
Also realize, this will only find one number. If two numbers appear an equal number of times, only the first one will be found.
static void CommonOccurrence(int[] numbers) {
var counts = new Dictionary<int, int>();
foreach (int number in numbers) {
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts) {
if (pair.Value > occurrences ) {
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine ("The most common number is {0} and it appears {1} times",
mostCommonNumber, occurrences);
}
$endgroup$
1
$begingroup$
I would suggest placing theConsole.WriteLine
outside the function, and simply returningmostCommonNumber
andoccurrences
.
$endgroup$
– Quill
Aug 8 '15 at 22:02
add a comment |
$begingroup$
Whenever you're dealing with collections in C#, there's often a simple Linq solution.
Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy
method on the integers. This makes each integer a key with a list of values for each occurrence.
Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending
and .First
methods do this for you.
static void CommonOccurrence(int[] numbers)
{
var groups = numbers.GroupBy(x => x);
var largest = groups.OrderByDescending(x => x.Count()).First();
Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:
static void CommonOccurrence(int[] numbers)
{
var dictionary = GroupByOccurrence(numbers);
var mostCommonNumber = KeyOfLargestValue(dictionary);
var occurrences = dictionary[mostCommonNumber];
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}
static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
var result = new Dictionary<int, int>();
foreach (int i in numbers)
{
if (!result.ContainsKey(i))
{
result[i] = 0;
}
result[i]++;
}
return result;
}
static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
int result = dictionary.Keys.First();
foreach (var entry in dictionary)
{
if (entry.Value > dictionary[result])
{
result = entry.Key;
}
}
return result;
}
$endgroup$
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
add a comment |
$begingroup$
This is on top of the points by @Dennis_E.
Single responsibility principle
CommomOcurrence
is poorly named (+ has a typo too),
but most importantly,
it doesn't follow the single responsibility principle.
It does too much:
- Builds a map of counts
- Prints the map of counts
- Prints the most frequent item with its count
Multiple smaller methods, each with a single clear responsibility would score you extra points at interviews.
Such methods are easier to understand,
and easier to unit test too.
Also easier to give a good name.
Naming
As mentioned earlier,
CommomOcurrence
is poorly named.
So are the names occurences
and tempOccurences
.
It would be better to rename these:
occurences
->maxOccurrences
tempOccurences
->occurences
Algorithm
Your algorithm using a map of counts is fine.
But, if the goal is to find the element that occurs the most,
then you can do a bit better:
once you found an element that occurs more times then the number of remaining elements, you can stop searching. If you want to know the number of occurrences, then you can scan the remaining elements to find the final count, but no need to count the other elements at that point.
$endgroup$
add a comment |
$begingroup$
For contrast - if it helps; this is what I used for checking booleans (/objects with a boolean property), whereby I return 'null' if there's an even number:
public static class EnumerableExtensions
{
public static bool? MostCommonValue<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selector)
{
var sourceLength = 0;
var trueCount = 0;
foreach (var currEle in source)
{
if (selector(currEle))
{
trueCount ++;
}
sourceLength ++;
}
var halfLength = sourceLength / 2;
var rem = sourceLength - trueCount;
var res =
trueCount == halfLength &&
(sourceLength % 2) == 0
? (bool?)null
: rem <= halfLength;
return res;
}
}
New contributor
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
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: "196"
};
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: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
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%2fcodereview.stackexchange.com%2fquestions%2f100349%2fmost-common-occurrence-of-an-int-in-an-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
The one thing I find really wrong is that you're using a HashTable
.
It is not generic, which means it will box every int
to an object.
Use a Dictionary<int, int>
instead.
And there is no reason to supply it as a parameter: it should be local to the method, so declare it there.
Last thing: you don't need the if-else
to check if a Key
is present.Dictionary
has a method TryGetValue
for that. It also has an indexer.
Also realize, this will only find one number. If two numbers appear an equal number of times, only the first one will be found.
static void CommonOccurrence(int[] numbers) {
var counts = new Dictionary<int, int>();
foreach (int number in numbers) {
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts) {
if (pair.Value > occurrences ) {
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine ("The most common number is {0} and it appears {1} times",
mostCommonNumber, occurrences);
}
$endgroup$
1
$begingroup$
I would suggest placing theConsole.WriteLine
outside the function, and simply returningmostCommonNumber
andoccurrences
.
$endgroup$
– Quill
Aug 8 '15 at 22:02
add a comment |
$begingroup$
The one thing I find really wrong is that you're using a HashTable
.
It is not generic, which means it will box every int
to an object.
Use a Dictionary<int, int>
instead.
And there is no reason to supply it as a parameter: it should be local to the method, so declare it there.
Last thing: you don't need the if-else
to check if a Key
is present.Dictionary
has a method TryGetValue
for that. It also has an indexer.
Also realize, this will only find one number. If two numbers appear an equal number of times, only the first one will be found.
static void CommonOccurrence(int[] numbers) {
var counts = new Dictionary<int, int>();
foreach (int number in numbers) {
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts) {
if (pair.Value > occurrences ) {
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine ("The most common number is {0} and it appears {1} times",
mostCommonNumber, occurrences);
}
$endgroup$
1
$begingroup$
I would suggest placing theConsole.WriteLine
outside the function, and simply returningmostCommonNumber
andoccurrences
.
$endgroup$
– Quill
Aug 8 '15 at 22:02
add a comment |
$begingroup$
The one thing I find really wrong is that you're using a HashTable
.
It is not generic, which means it will box every int
to an object.
Use a Dictionary<int, int>
instead.
And there is no reason to supply it as a parameter: it should be local to the method, so declare it there.
Last thing: you don't need the if-else
to check if a Key
is present.Dictionary
has a method TryGetValue
for that. It also has an indexer.
Also realize, this will only find one number. If two numbers appear an equal number of times, only the first one will be found.
static void CommonOccurrence(int[] numbers) {
var counts = new Dictionary<int, int>();
foreach (int number in numbers) {
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts) {
if (pair.Value > occurrences ) {
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine ("The most common number is {0} and it appears {1} times",
mostCommonNumber, occurrences);
}
$endgroup$
The one thing I find really wrong is that you're using a HashTable
.
It is not generic, which means it will box every int
to an object.
Use a Dictionary<int, int>
instead.
And there is no reason to supply it as a parameter: it should be local to the method, so declare it there.
Last thing: you don't need the if-else
to check if a Key
is present.Dictionary
has a method TryGetValue
for that. It also has an indexer.
Also realize, this will only find one number. If two numbers appear an equal number of times, only the first one will be found.
static void CommonOccurrence(int[] numbers) {
var counts = new Dictionary<int, int>();
foreach (int number in numbers) {
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts) {
if (pair.Value > occurrences ) {
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine ("The most common number is {0} and it appears {1} times",
mostCommonNumber, occurrences);
}
edited Aug 8 '15 at 22:00
Quill
10.5k53387
10.5k53387
answered Aug 8 '15 at 17:50
Dennis_EDennis_E
1,00758
1,00758
1
$begingroup$
I would suggest placing theConsole.WriteLine
outside the function, and simply returningmostCommonNumber
andoccurrences
.
$endgroup$
– Quill
Aug 8 '15 at 22:02
add a comment |
1
$begingroup$
I would suggest placing theConsole.WriteLine
outside the function, and simply returningmostCommonNumber
andoccurrences
.
$endgroup$
– Quill
Aug 8 '15 at 22:02
1
1
$begingroup$
I would suggest placing the
Console.WriteLine
outside the function, and simply returning mostCommonNumber
and occurrences
.$endgroup$
– Quill
Aug 8 '15 at 22:02
$begingroup$
I would suggest placing the
Console.WriteLine
outside the function, and simply returning mostCommonNumber
and occurrences
.$endgroup$
– Quill
Aug 8 '15 at 22:02
add a comment |
$begingroup$
Whenever you're dealing with collections in C#, there's often a simple Linq solution.
Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy
method on the integers. This makes each integer a key with a list of values for each occurrence.
Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending
and .First
methods do this for you.
static void CommonOccurrence(int[] numbers)
{
var groups = numbers.GroupBy(x => x);
var largest = groups.OrderByDescending(x => x.Count()).First();
Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:
static void CommonOccurrence(int[] numbers)
{
var dictionary = GroupByOccurrence(numbers);
var mostCommonNumber = KeyOfLargestValue(dictionary);
var occurrences = dictionary[mostCommonNumber];
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}
static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
var result = new Dictionary<int, int>();
foreach (int i in numbers)
{
if (!result.ContainsKey(i))
{
result[i] = 0;
}
result[i]++;
}
return result;
}
static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
int result = dictionary.Keys.First();
foreach (var entry in dictionary)
{
if (entry.Value > dictionary[result])
{
result = entry.Key;
}
}
return result;
}
$endgroup$
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
add a comment |
$begingroup$
Whenever you're dealing with collections in C#, there's often a simple Linq solution.
Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy
method on the integers. This makes each integer a key with a list of values for each occurrence.
Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending
and .First
methods do this for you.
static void CommonOccurrence(int[] numbers)
{
var groups = numbers.GroupBy(x => x);
var largest = groups.OrderByDescending(x => x.Count()).First();
Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:
static void CommonOccurrence(int[] numbers)
{
var dictionary = GroupByOccurrence(numbers);
var mostCommonNumber = KeyOfLargestValue(dictionary);
var occurrences = dictionary[mostCommonNumber];
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}
static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
var result = new Dictionary<int, int>();
foreach (int i in numbers)
{
if (!result.ContainsKey(i))
{
result[i] = 0;
}
result[i]++;
}
return result;
}
static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
int result = dictionary.Keys.First();
foreach (var entry in dictionary)
{
if (entry.Value > dictionary[result])
{
result = entry.Key;
}
}
return result;
}
$endgroup$
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
add a comment |
$begingroup$
Whenever you're dealing with collections in C#, there's often a simple Linq solution.
Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy
method on the integers. This makes each integer a key with a list of values for each occurrence.
Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending
and .First
methods do this for you.
static void CommonOccurrence(int[] numbers)
{
var groups = numbers.GroupBy(x => x);
var largest = groups.OrderByDescending(x => x.Count()).First();
Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:
static void CommonOccurrence(int[] numbers)
{
var dictionary = GroupByOccurrence(numbers);
var mostCommonNumber = KeyOfLargestValue(dictionary);
var occurrences = dictionary[mostCommonNumber];
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}
static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
var result = new Dictionary<int, int>();
foreach (int i in numbers)
{
if (!result.ContainsKey(i))
{
result[i] = 0;
}
result[i]++;
}
return result;
}
static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
int result = dictionary.Keys.First();
foreach (var entry in dictionary)
{
if (entry.Value > dictionary[result])
{
result = entry.Key;
}
}
return result;
}
$endgroup$
Whenever you're dealing with collections in C#, there's often a simple Linq solution.
Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy
method on the integers. This makes each integer a key with a list of values for each occurrence.
Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending
and .First
methods do this for you.
static void CommonOccurrence(int[] numbers)
{
var groups = numbers.GroupBy(x => x);
var largest = groups.OrderByDescending(x => x.Count()).First();
Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:
static void CommonOccurrence(int[] numbers)
{
var dictionary = GroupByOccurrence(numbers);
var mostCommonNumber = KeyOfLargestValue(dictionary);
var occurrences = dictionary[mostCommonNumber];
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}
static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
var result = new Dictionary<int, int>();
foreach (int i in numbers)
{
if (!result.ContainsKey(i))
{
result[i] = 0;
}
result[i]++;
}
return result;
}
static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
int result = dictionary.Keys.First();
foreach (var entry in dictionary)
{
if (entry.Value > dictionary[result])
{
result = entry.Key;
}
}
return result;
}
edited Aug 8 '15 at 21:01
answered Aug 8 '15 at 20:04
GallantGallant
51326
51326
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
add a comment |
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
Thanks, but I was told not to depend on libraries like Linq for interviews
$endgroup$
– Aaron
Aug 8 '15 at 20:22
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
$begingroup$
It depends on the interviewer, I suppose. I always ask if I can use certain libraries, and a lot of the times they will be interested/impressed in seeing it solved both ways. See my updated answer on a manual implementation.
$endgroup$
– Gallant
Aug 8 '15 at 20:59
9
9
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
$begingroup$
LINQ is a core part of C# and probably about 50% of the code I write. I'd be ecstatic if an interviewee came up with Gallant's solution. Not allowing LINQ is as silly as not allowing a Dictionary or HashSet; at that point, you're not writing C#, you're doing Sudoku.
$endgroup$
– Carl Leth
Aug 8 '15 at 21:23
add a comment |
$begingroup$
This is on top of the points by @Dennis_E.
Single responsibility principle
CommomOcurrence
is poorly named (+ has a typo too),
but most importantly,
it doesn't follow the single responsibility principle.
It does too much:
- Builds a map of counts
- Prints the map of counts
- Prints the most frequent item with its count
Multiple smaller methods, each with a single clear responsibility would score you extra points at interviews.
Such methods are easier to understand,
and easier to unit test too.
Also easier to give a good name.
Naming
As mentioned earlier,
CommomOcurrence
is poorly named.
So are the names occurences
and tempOccurences
.
It would be better to rename these:
occurences
->maxOccurrences
tempOccurences
->occurences
Algorithm
Your algorithm using a map of counts is fine.
But, if the goal is to find the element that occurs the most,
then you can do a bit better:
once you found an element that occurs more times then the number of remaining elements, you can stop searching. If you want to know the number of occurrences, then you can scan the remaining elements to find the final count, but no need to count the other elements at that point.
$endgroup$
add a comment |
$begingroup$
This is on top of the points by @Dennis_E.
Single responsibility principle
CommomOcurrence
is poorly named (+ has a typo too),
but most importantly,
it doesn't follow the single responsibility principle.
It does too much:
- Builds a map of counts
- Prints the map of counts
- Prints the most frequent item with its count
Multiple smaller methods, each with a single clear responsibility would score you extra points at interviews.
Such methods are easier to understand,
and easier to unit test too.
Also easier to give a good name.
Naming
As mentioned earlier,
CommomOcurrence
is poorly named.
So are the names occurences
and tempOccurences
.
It would be better to rename these:
occurences
->maxOccurrences
tempOccurences
->occurences
Algorithm
Your algorithm using a map of counts is fine.
But, if the goal is to find the element that occurs the most,
then you can do a bit better:
once you found an element that occurs more times then the number of remaining elements, you can stop searching. If you want to know the number of occurrences, then you can scan the remaining elements to find the final count, but no need to count the other elements at that point.
$endgroup$
add a comment |
$begingroup$
This is on top of the points by @Dennis_E.
Single responsibility principle
CommomOcurrence
is poorly named (+ has a typo too),
but most importantly,
it doesn't follow the single responsibility principle.
It does too much:
- Builds a map of counts
- Prints the map of counts
- Prints the most frequent item with its count
Multiple smaller methods, each with a single clear responsibility would score you extra points at interviews.
Such methods are easier to understand,
and easier to unit test too.
Also easier to give a good name.
Naming
As mentioned earlier,
CommomOcurrence
is poorly named.
So are the names occurences
and tempOccurences
.
It would be better to rename these:
occurences
->maxOccurrences
tempOccurences
->occurences
Algorithm
Your algorithm using a map of counts is fine.
But, if the goal is to find the element that occurs the most,
then you can do a bit better:
once you found an element that occurs more times then the number of remaining elements, you can stop searching. If you want to know the number of occurrences, then you can scan the remaining elements to find the final count, but no need to count the other elements at that point.
$endgroup$
This is on top of the points by @Dennis_E.
Single responsibility principle
CommomOcurrence
is poorly named (+ has a typo too),
but most importantly,
it doesn't follow the single responsibility principle.
It does too much:
- Builds a map of counts
- Prints the map of counts
- Prints the most frequent item with its count
Multiple smaller methods, each with a single clear responsibility would score you extra points at interviews.
Such methods are easier to understand,
and easier to unit test too.
Also easier to give a good name.
Naming
As mentioned earlier,
CommomOcurrence
is poorly named.
So are the names occurences
and tempOccurences
.
It would be better to rename these:
occurences
->maxOccurrences
tempOccurences
->occurences
Algorithm
Your algorithm using a map of counts is fine.
But, if the goal is to find the element that occurs the most,
then you can do a bit better:
once you found an element that occurs more times then the number of remaining elements, you can stop searching. If you want to know the number of occurrences, then you can scan the remaining elements to find the final count, but no need to count the other elements at that point.
edited Apr 13 '17 at 12:40
Community♦
1
1
answered Aug 8 '15 at 18:04
janosjanos
99.1k12125351
99.1k12125351
add a comment |
add a comment |
$begingroup$
For contrast - if it helps; this is what I used for checking booleans (/objects with a boolean property), whereby I return 'null' if there's an even number:
public static class EnumerableExtensions
{
public static bool? MostCommonValue<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selector)
{
var sourceLength = 0;
var trueCount = 0;
foreach (var currEle in source)
{
if (selector(currEle))
{
trueCount ++;
}
sourceLength ++;
}
var halfLength = sourceLength / 2;
var rem = sourceLength - trueCount;
var res =
trueCount == halfLength &&
(sourceLength % 2) == 0
? (bool?)null
: rem <= halfLength;
return res;
}
}
New contributor
$endgroup$
add a comment |
$begingroup$
For contrast - if it helps; this is what I used for checking booleans (/objects with a boolean property), whereby I return 'null' if there's an even number:
public static class EnumerableExtensions
{
public static bool? MostCommonValue<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selector)
{
var sourceLength = 0;
var trueCount = 0;
foreach (var currEle in source)
{
if (selector(currEle))
{
trueCount ++;
}
sourceLength ++;
}
var halfLength = sourceLength / 2;
var rem = sourceLength - trueCount;
var res =
trueCount == halfLength &&
(sourceLength % 2) == 0
? (bool?)null
: rem <= halfLength;
return res;
}
}
New contributor
$endgroup$
add a comment |
$begingroup$
For contrast - if it helps; this is what I used for checking booleans (/objects with a boolean property), whereby I return 'null' if there's an even number:
public static class EnumerableExtensions
{
public static bool? MostCommonValue<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selector)
{
var sourceLength = 0;
var trueCount = 0;
foreach (var currEle in source)
{
if (selector(currEle))
{
trueCount ++;
}
sourceLength ++;
}
var halfLength = sourceLength / 2;
var rem = sourceLength - trueCount;
var res =
trueCount == halfLength &&
(sourceLength % 2) == 0
? (bool?)null
: rem <= halfLength;
return res;
}
}
New contributor
$endgroup$
For contrast - if it helps; this is what I used for checking booleans (/objects with a boolean property), whereby I return 'null' if there's an even number:
public static class EnumerableExtensions
{
public static bool? MostCommonValue<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selector)
{
var sourceLength = 0;
var trueCount = 0;
foreach (var currEle in source)
{
if (selector(currEle))
{
trueCount ++;
}
sourceLength ++;
}
var halfLength = sourceLength / 2;
var rem = sourceLength - trueCount;
var res =
trueCount == halfLength &&
(sourceLength % 2) == 0
? (bool?)null
: rem <= halfLength;
return res;
}
}
New contributor
New contributor
answered 5 mins ago
DennisVM-D2iDennisVM-D2i
11
11
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- 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.
Use MathJax to format equations. MathJax reference.
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%2fcodereview.stackexchange.com%2fquestions%2f100349%2fmost-common-occurrence-of-an-int-in-an-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