import java.util.Arrays; import java.util.Scanner; import java.io.UnsupportedEncodingException; public class ASCII { /** * @param args * @throws UnsupportedEncodingException */ static String text = ""; static boolean[] counter = new boolean[256]; public static void main(String[] args) throws UnsupportedEncodingException { while (text == "") { System.out.println("Enter Your Text and Press ENTER:"); text = readText(); } byte[] result = text.getBytes("US-ASCII"); long[] intResult = new long[result.length]; long value = 0; //Converting Byte Array to its Integer equivalence for (int i = 0; i < result.length; i++) { value = (value << 8) + (result[i] & 0xff); intResult[i]= value; value=0; } long[] sortResult = sortArray(intResult); if (hasAllASCIIChars(sortResult)) System.out.println("Text has all ASCII characters"); else System.out.println("Text does not have all ASCII characters"); } /** * * @param sortedArray: sorted array of ASCII Codes of characters (Long) * @return */ private static boolean hasAllASCIIChars(long[] sortedArray) { for (int i = 0; i< sortedArray.length - 1; i++) if (!counter[(int)sortedArray[i]]) counter[(int)sortedArray[i]] = false; for (boolean bool : counter) if (bool == false) return false; return true; } public static String readText() { Scanner sc = new Scanner(System.in); if (sc.hasNext()) { return sc.nextLine(); } else { return ""; } } public static long[] sortArray(long[] array) { Arrays.sort(array); return array; } }
“If you can't explain it to a six year old, you don't understand it yourself.” ― Albert Einstein
Thursday, August 30, 2012
Interview Question: Determine Whether a Text includes all ASCII characters
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment