Skip to content

Instantly share code, notes, and snippets.

@DeaconDesperado
Last active December 20, 2015 23:59
Show Gist options
  • Save DeaconDesperado/6216707 to your computer and use it in GitHub Desktop.
Save DeaconDesperado/6216707 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.Map.*;
/**
* A template file with basic JUnit tests has been provided.
* Note that your program will be evaluated by a more comprehensive test suite.
*
* Please consider the runtime and space complexity of your algorithms and comment on those trade offs.
*
* Good luck!
*/
public class ArrayFun {
/***
* @param chars an array of characters
* @return the same array with the character order reversed
*/
public static char[] reverse(char[] chars){
//Swap in place in memory by bisecting, logN
int idx = 0;
for (int i = chars.length - 1; i >= chars.length / 2; i--) {
char temp = chars[i];
chars[i] = chars[idx];
chars[idx] = temp;
idx++;
}
return chars;
}
/***
* A palindrome is a word, phrase, number, or other sequence of units that may be
* read the same way in either direction.
*
* Caveat 1 : punctuation and spaces do not count as contributing characters
* (hint) use the static method Character.isLetter(char c)
*
* Caveat 2 : upper case letters should still match with lower case
* (hint) use the static method Character.toLowerCase(char c)
*
* Examples of valid palindromes :
*
* "Never odd or even"
* "No trace; not one carton"
* "A Toyota! Race fast... safe car: a Toyota"
* "Sums are not set as a test on Erasmus"
*
* @return true if chars form a valid palindrome, otherwise false
*/
public static boolean isPalindrome(char[] chars){
//Convert to string and on omit irrelevant characters in one shot
String s = new String(chars).toLowerCase().replaceAll("\\W", "");;
int j=0;
int k = s.length() - 1;
while(j < s.length() / 2) {
if (s.charAt(j++) != s.charAt(k--)){
//break execution as soon as characters don't match
return false;
}
}
return true;
}
/***
* Find the most used char in the following char[]
* If a few chars share the top count, return them all.
*
* Caveat 1: exclude the space (' ') character from your count.
* Caveat 2: treat all uppercase characters as their lowercase counterpart
*
* @return the characters which appear most frequently
*/
public static List<Character> mostUsedCharacter(char [] chars){
//Should finish linearlly worst case N*2
//Iterate through the chars and track in a hashmap num of occurances
Map<Character,Integer> counts = new HashMap<Character,Integer>();
for (Character c : chars) {
//Ignore any non-letter chars in the count
if(Character.isLetter(c)){
Integer count = counts.get(c);
counts.put(Character.toLowerCase(c), count != null ? count+1 : 0);
}
}
ArrayList<Character> mostPops = new ArrayList<Character>();
int maxValueInMap=(Collections.max(counts.values()));
//for any chars that have like max counts, add to output list.
for (Entry<Character, Integer> entry : counts.entrySet()) {
if (entry.getValue()==maxValueInMap) {
mostPops.add(entry.getKey());
}
}
return mostPops;
}
/***
* Find the number of unique palindromes in the char array
*
* Example: for the array {'a', 'b', 'b', 'a', 'c', 'c', 'a', 'b' 'b', 'a', 'd', 'd', 'a'}
* the palindromes are
* abbaccabba
* bbaccabb
* baccab
* acca
* cc
* abba
* bb
* adda
* dd
*
* @return the number of unique palindromes in the character array
*/
public static int numberOfPalindromes(char[] chars){
int count = 0;
String str = new String(chars);
ArrayList<String> seen = new ArrayList<String>();
for (int i = 0; i < str.length() - 1; i++) {
char start = str.charAt(i);
//Increment from first char and do palindromic test against neighboring chars
String st = "";
st += start;
for (int j = i + 1; j < str.length(); j++) {
st += str.charAt(j);
if (ArrayFun.isPalindrome(st.toCharArray()) && st.length() > 1 && !seen.contains(st)) {
seen.add(st);
count++;
}
}
//reset string buffer every time we must start with a different char
st = "";
}
return count;
}
}
import org.junit.Assert;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ArrayFunTest {
@Test
public void testReverse() throws Exception {
final char[] chars = "Novus".toCharArray();
final char [] reversed = "suvoN".toCharArray();
Assert.assertArrayEquals(reversed, ArrayFun.reverse(chars));
}
@Test
public void testIsPalindrome() throws Exception {
final char[] palindrome = "A Toyota! Race fast... safe car: a Toyota".toCharArray();
final char[] notPalindrome = {'N','o','v','u','s'};
Assert.assertTrue(ArrayFun.isPalindrome(palindrome));
Assert.assertFalse(ArrayFun.isPalindrome(notPalindrome));
}
@Test
public void testMostUsedCharacter() throws Exception{
final char[] chars = "A Toyota! Race fast... safe car: a Toyota".toCharArray();
final List<Character> output = ArrayFun.mostUsedCharacter(chars);
Assert.assertEquals(output.size(), 1);
Assert.assertEquals(output.get(0), new Character('a'));
final char[] chars2 = "Abcba".toCharArray();
final List<Character> output2 = ArrayFun.mostUsedCharacter(chars2);
final Set<Character> resultSet = new HashSet<Character>(output2);
Assert.assertEquals(output2.size(), 2);
Assert.assertTrue(resultSet.contains('a'));
Assert.assertTrue(resultSet.contains('b'));
Assert.assertFalse(resultSet.contains('c'));
}
@Test
public void testNumberOfPalindromes() throws Exception {
char[] chars = "abbaccabbadda".toCharArray();
int numPalindromes = ArrayFun.numberOfPalindromes(chars);
Assert.assertEquals(numPalindromes, 9);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment