Skip to content

Instantly share code, notes, and snippets.

@richardadalton
Created September 18, 2015 10:13
Show Gist options
  • Save richardadalton/014c2eeede38fb290ecd to your computer and use it in GitHub Desktop.
Save richardadalton/014c2eeede38fb290ecd to your computer and use it in GitHub Desktop.
Can I Make a Palindrome - Imperative vs Functional
Here's a little programming challenge, the kind you might be asked in a job interview.
Write a function that can tell if a sequence of characters can be rearranged to form a palindrome.
And here's a solution in C (The kind you might be expected to write in a job interview)
http://geeksquiz.com/check-characters-given-string-can-rearranged-form-palindrome/
bool canFormPalindrome(char *str)
{
// Create a count array and initialize all values as 0
int count[NO_OF_CHARS] = {0};
// For each character in input strings, increment count in
// the corresponding count array
for (int i = 0; str[i]; i++)
count[str[i]]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++)
if (count[i] & 1)
odd++;
// Return true if odd count is 0 or 1, otherwise false
return (odd <= 1);
}
Here's basically the same algorithm, using LINQ in C#.
private static bool canFormPalindrome(string s) {
return s.GroupBy(c => c)
.Select(c => c.Count())
.Where(i => i % 2 == 1)
.Count() <= 1;
}
Which do you prefer?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment