method2testcases
stringlengths 118
3.08k
|
---|
### Question:
PracticeQuestionsCh5 { public static int stringToInt(String s) { final String regex = "^-?\\d+"; if (s == null || !s.matches(regex)) { throw new NumberFormatException(s + " is not a valid integer encoding."); } return parseInt(s, 10, s.length() - 1); } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }### Answer:
@Test public void testStringToInt() { try { stringToInt(null); Assert.fail(); } catch (NumberFormatException iae) { } try { stringToInt("123abc"); Assert.fail(); } catch (NumberFormatException iae) { } int result = stringToInt("-123"); Assert.assertEquals(-123, result); result = stringToInt("123"); Assert.assertEquals(123, result); } |
### Question:
XMLSigner { public void sign(String inputFile, String outputFile, String referenceURI) throws Exception { File ipFile = new File(inputFile); File opFile = new File(outputFile); SecurityUtil.print(ipFile); KeyPair keyPair = KeyStoreManager.getKeyPair(XMLSigner.class .getResource("/" + KEYSTORE).getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); SignatureManager sigMgr = new SignatureManager(keyPair, XMLSigner.class .getResource("/" + CERTIFICATE).getPath(), referenceURI); sigMgr.sign(ipFile, opFile); SecurityUtil.print(opFile); } void sign(String inputFile, String outputFile, String referenceURI); void validate(String inputFile); }### Answer:
@Test public void testSign() { String inputFile = XMLSignerTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; try { XMLSigner.sign(inputFile, outputFile, REFERENCE_URI); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } } |
### Question:
PracticeQuestionsCh5 { private static StringBuilder convertToBase(int x, int b) { StringBuilder buffer = new StringBuilder(); buffer.insert(0, encode(x % b)); if (x >= b) { buffer.insert(0, convertToBase(x / b, b)); } return buffer; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }### Answer:
@Test public void testConvertToBase() { Assert.assertNull(changeBase(null, 10, 2)); Assert.assertEquals("", changeBase("", 10, 2)); Assert.assertEquals("1001", changeBase("9", 10, 2)); Assert.assertEquals("1F", changeBase("31", 10, 16)); } |
### Question:
CircularQueue { public int enqueue(int element) { if (isCapacityFull()) { resize(); } queue[++end] = element; return element; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }### Answer:
@Test public void testEnqueue() { queue.enqueue(11); Assert.assertEquals(CircularQueue.DEFAULT_CAPACITY, queue.capacity()); Assert.assertEquals(1, queue.size()); } |
### Question:
CircularQueue { public int dequeue() { if (isEmpty()) { throw new NoSuchElementException("Cannot dequeue from an empty queue."); } return queue[begin++]; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }### Answer:
@Test public void testDequeue() { queue.enqueue(11); queue.enqueue(12); queue.enqueue(13); Assert.assertEquals(11, queue.dequeue()); Assert.assertEquals(CircularQueue.DEFAULT_CAPACITY, queue.capacity()); Assert.assertEquals(2, queue.size()); }
@Test(expected = NoSuchElementException.class) public void testDequeueWhenEmpty() { queue.dequeue(); } |
### Question:
CircularQueue { public int capacity() { return capacity; } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }### Answer:
@Test public void testCapacity() { CircularQueue cq = new CircularQueue(1); Assert.assertEquals(1, cq.capacity()); Assert.assertEquals(0, cq.size()); } |
### Question:
CircularQueue { private void resize() { LOGGER.debug("Resizing queue from {} to {}.", capacity, capacity * 2); queue = Arrays.copyOf(queue, capacity *= 2); } CircularQueue(); CircularQueue(final int capacity); int size(); int capacity(); int enqueue(int element); int dequeue(); boolean isEmpty(); static final Logger LOGGER; static final int DEFAULT_CAPACITY; }### Answer:
@Test public void testResize() { CircularQueue cq = new CircularQueue(1); Assert.assertEquals(1, cq.capacity()); Assert.assertEquals(0, cq.size()); cq.enqueue(1); cq.enqueue(2); Assert.assertEquals(2, cq.capacity()); Assert.assertEquals(2, cq.size()); } |
### Question:
MaxStack { public int push(int element) { if (maxStack.isEmpty()) { maxStack.add(element); } else { maxStack.add(0, Math.max(element, maxStack.peek().intValue())); } stack.add(0, element); return element; } int push(int element); int pop(); int max(); int size(); }### Answer:
@Test public void testPush() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(3, maxStack.size()); } |
### Question:
MaxStack { public int pop() { maxStack.remove(0); return stack.remove(0); } int push(int element); int pop(); int max(); int size(); }### Answer:
@Test public void testPop() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(2, maxStack.pop()); Assert.assertEquals(3, maxStack.pop()); Assert.assertEquals(1, maxStack.pop()); }
@Test(expected = NoSuchElementException.class) public void testPopWhenEmpty() { new MaxStack().pop(); } |
### Question:
MaxStack { public int max() { return maxStack.peek(); } int push(int element); int pop(); int max(); int size(); }### Answer:
@Test public void testMax() { MaxStack maxStack = new MaxStack(); maxStack.push(1); maxStack.push(3); maxStack.push(2); Assert.assertEquals(3, maxStack.max()); } |
### Question:
XMLSigner { public void validate(String inputFile) throws Exception { File signedFile = new File(inputFile); KeyPair keyPair = KeyStoreManager.getKeyPair(XMLSigner.class .getResource("/" + KEYSTORE).getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); SignatureManager sigMan = new SignatureManager(keyPair, XMLSigner.class .getResource("/" + CERTIFICATE).getPath(), null); sigMan.validate(signedFile); } void sign(String inputFile, String outputFile, String referenceURI); void validate(String inputFile); }### Answer:
@Test public void testValidate() { String inputFile = XMLSignerTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; try { XMLSigner.validate(outputFile); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } } |
### Question:
PracticeQuestionsCh8 { public static int evalRpn(String expr) { final String basicRpnPattern = "-?\\d+"; if (expr != null && expr.matches(basicRpnPattern)) { return Integer.valueOf(expr); } Stack<String> rpnStack = new Stack<String>(); String[] tokens = expr.split(","); int value = 0; for (String token : tokens) { if (token.matches(basicRpnPattern)) { rpnStack.push(token); } else { int operand2 = Integer.valueOf(rpnStack.pop()); int operand1 = Integer.valueOf(rpnStack.pop()); value = eval(operand1, operand2, token); rpnStack.push(String.valueOf(value)); } } value = Integer.valueOf(rpnStack.pop()); LOGGER.info("Expression \"{}\" evaluated to {}.", expr, value); return value; } static int evalRpn(String expr); static final Logger LOGGER; }### Answer:
@Test public void testEvalRpn() { Assert.assertEquals(123, evalRpn("123")); Assert.assertEquals(3, evalRpn("1,2,+")); Assert.assertEquals(60, evalRpn("1,2,+,4,5,x,x")); Assert.assertEquals(-4, evalRpn("1,1,+,-2,x")); Assert.assertEquals(0, evalRpn("4,6,/,2,/")); } |
### Question:
PracticeQuestionsCh9 { public static BinaryTreeNode<Integer> lowestCommonAncestor(BinaryTreeNode<Integer> root, BinaryTreeNode<Integer> n1, BinaryTreeNode<Integer> n2) { if (root == null || root == n1 || root == n2) { return root; } BinaryTreeNode<Integer> left = lowestCommonAncestor(root.leftChild(), n1, n2); BinaryTreeNode<Integer> right = lowestCommonAncestor(root.rightChild(), n1, n2); if (left != null && right != null) { return root; } return left != null ? left : right; } static BinaryTreeNode<Integer> lowestCommonAncestor(BinaryTreeNode<Integer> root,
BinaryTreeNode<Integer> n1, BinaryTreeNode<Integer> n2); static final Logger LOGGER; }### Answer:
@Test public void testLowestCommonAncestor() { BinaryTreeNode<Integer> lca = lowestCommonAncestor(root, three, five); Assert.assertEquals(4, lca.data().intValue()); lca = lowestCommonAncestor(root, one, three); Assert.assertEquals(2, lca.data().intValue()); lca = lowestCommonAncestor(root, three, eight); Assert.assertEquals(6, lca.data().intValue()); } |
### Question:
PracticeQuestionsCh12 { @SuppressWarnings("unchecked") public static List<List<String>> anagrams(final List<String> dictionary) { final MultiMap<Integer, Integer> anagramMap = new MultiValueMap<Integer, Integer>(); char[] arr = null; int hashCode = -1; for (int i = 0; i < dictionary.size(); ++i) { arr = dictionary.get(i).toCharArray(); Arrays.sort(arr); hashCode = String.valueOf(arr).hashCode(); anagramMap.put(hashCode, i); } final List<List<String>> anagrams = new ArrayList<>(); final Set<Entry<Integer, Object>> anagramIndices = anagramMap.entrySet(); List<Integer> aSet = null; for (final Object o : anagramIndices) { aSet = (List<Integer>) ((Entry<Integer, Object>) o).getValue(); if (aSet.size() > 1) { final List<String> an = new ArrayList<>(); for (final int i : aSet) { an.add(dictionary.get(i)); } anagrams.add(an); } } return anagrams; } @SuppressWarnings("unchecked") static List<List<String>> anagrams(final List<String> dictionary); static final Logger LOGGER; }### Answer:
@Test public void testAnagrams() { List<String> dictionary = new ArrayList<>(); dictionary.add("urn"); dictionary.add("won"); dictionary.add("bear"); dictionary.add("bare"); dictionary.add("run"); dictionary.add("cafe"); dictionary.add("now"); List<List<String>> anagrams = anagrams(dictionary); Assert.assertEquals(3, anagrams.size()); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "urn", "run" }))); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "won", "now" }))); Assert.assertTrue(anagrams.contains(Arrays.asList(new String[] { "bear", "bare" }))); } |
### Question:
PracticeQuestionsCh7 { public static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2) { final int sizeL1 = l1.size(); final int sizeL2 = l2.size(); LOGGER.info("List 1 size: {}.", sizeL1); LOGGER.info("List 2 size: {}.", sizeL2); int diff = sizeL1 - sizeL2; LinkedListNode<Integer> l1Pointer = l1.head(); LinkedListNode<Integer> l2Pointer = l2.head(); if (diff < 0) { for (; diff > 0; l2Pointer = l2Pointer.successor(), --diff) ; } else { for (; diff > 0; l1Pointer = l1Pointer.successor(), --diff) ; } while (l1Pointer != l1.tail() && l2Pointer != l2.tail()) { LOGGER.info("List 1 pointer is at: {}.", l1Pointer); LOGGER.info("List 2 pointer is at: {}.", l2Pointer); if (l1Pointer.equals(l2Pointer)) { return l1Pointer; } l1Pointer = l1Pointer.successor(); l2Pointer = l2Pointer.successor(); } return null; } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }### Answer:
@Test public void testIntersection() { LinkedList<Integer> l1 = newLinkedList(2, 3, 5, 7); LinkedList<Integer> l2 = newLinkedList(1, 5, 7); LinkedListNode<Integer> intersection = intersection(l1, l2); Assert.assertNotNull(intersection); Assert.assertEquals(5, intersection.data().intValue()); } |
### Question:
PracticeQuestionsCh7 { public static void reverse(LinkedList<Integer> l) { LinkedListNode<Integer> previous = l.head(); LinkedListNode<Integer> current = previous.successor(); LinkedListNode<Integer> next = current.successor(); while (next != l.tail()) { LOGGER.info("Previous: {}, current: {}, next: {}.", previous, current, next); current.setSuccessor(previous); previous = current; current = next; next = next.successor(); } LOGGER.info("Swapping head and tail."); LOGGER.info("Previous: {}, current: {}, next: {}.", previous, current, next); current.setSuccessor(previous); previous = l.head().successor(); l.head().setSuccessor(current); next.setSuccessor(previous); } static LinkedListNode<Integer> mergeLists(LinkedList<Integer> l, LinkedList<Integer> f); static LinkedListNode<Integer> startOfLoop(LinkedList<Integer> l); static LinkedListNode<Integer> intersection(LinkedList<Integer> l1, LinkedList<Integer> l2); static void evenOddMerge(LinkedList<Integer> l); static void reverse(LinkedList<Integer> l); static final Logger LOGGER; }### Answer:
@Test public void testReverse() { LinkedList<Integer> l = newLinkedList(1, 2, 3, 4, 5); reverse(l); LinkedListNode<Integer> runningNode = l.head(); int[] reversed = new int[] { 5, 4, 3, 2, 1 }; assertArrayEqualsList(reversed, runningNode); } |
### Question:
PracticeQuestionsCh6 { public static List<String> keypadPermutation(int num) { final List<String> perms = new ArrayList<>(); final String numSeq = String.valueOf(num); return permute(numSeq, 0, perms); } static List<String> keypadPermutation(int num); static final Logger LOGGER; }### Answer:
@Test public void testKeypadPermutation() { List<String> expected = new ArrayList<>(); expected.add("AD"); expected.add("AE"); expected.add("AF"); expected.add("BD"); expected.add("BE"); expected.add("BF"); expected.add("CD"); expected.add("CE"); expected.add("CF"); Assert.assertEquals(expected, keypadPermutation(23)); expected.clear(); expected.add("A"); expected.add("B"); expected.add("C"); Assert.assertEquals(expected, keypadPermutation(12)); } |
### Question:
BingoNumberCaller { public String callBingoNumber() throws NoMoreBingoNumbersException { if (numbersCalled.size() == LARGEST_NUMBER) { throw new NoMoreBingoNumbersException( "All possible Bingo numbers have been called."); } final int randomBingoNumberIndex = generator.nextInt(LARGEST_NUMBER); final String bingoNumber = BINGO_NUMBER_POOL[randomBingoNumberIndex % BUCKET_SIZE][randomBingoNumberIndex / BUCKET_SIZE]; if (numbersCalled.add(bingoNumber)) { return bingoNumber; } return callBingoNumber(); } String callBingoNumber(); Set<String> getNumbersCalled(); boolean isCalled(String bingoNumber); static final String[][] BINGO_NUMBER_POOL; }### Answer:
@Test public void testGenerateBingoNumber() { for (int i = 1; i <= LARGEST_NUMBER; i++) { try { String result = generator.callBingoNumber(); assertNotNull(result); assertTrue(BINGO.contains(String.valueOf(result.charAt(0)))); assertTrue(Integer.parseInt(result.substring(1)) <= LARGEST_NUMBER); } catch (NoMoreBingoNumbersException ex) { assertEquals(LARGEST_NUMBER, i); } } } |
### Question:
PracticeQuestionsCh5 { public static int insertMIntoN(int N, int M, int i, int j) { LOGGER.debug("N = {}, M = {}, i = {}, j = {}.", N, M, i, j); final int mask1 = ~0 << (j + 1); final int mask2 = (1 << i) - 1; final int mask = mask1 | mask2; final int maskAndN = mask & N; final int leftShiftedM = M << i; LOGGER.debug("mask 1 = {}, mask 2 = {}.", mask1, mask2); LOGGER.debug("mask = {}.", mask); LOGGER.debug("maskAndN = {}.", maskAndN); LOGGER.debug("leftShiftedM = {}.", leftShiftedM); return maskAndN | leftShiftedM; } static int insertMIntoN(int N, int M, int i, int j); static final Logger LOGGER; }### Answer:
@Test public void testInsertMIntoN() { Assert.assertEquals(2124, PracticeQuestionsCh5.insertMIntoN(2048, 19, 2, 6)); } |
### Question:
StackWithMin extends Stack<E> { public E min() { return this.min; } @Override E push(E element); @Override E pop(); E min(); }### Answer:
@Test public void testMin() { assertEquals(Integer.valueOf(1), stack.min()); } |
### Question:
SetOfStacks { public boolean isEmpty() { return stacks.isEmpty() || stacks.getFirst().isEmpty(); } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }### Answer:
@Test public void testIsEmpty() { assertTrue(stacks.isEmpty()); } |
### Question:
SetOfStacks { public E push(E element) { if (isFull()) { stacks.addFirst(new ArrayDeque<E>()); } stacks.getFirst().addFirst(element); return element; } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }### Answer:
@Test public void testPush() { stacks.push(1); stacks.push(2); assertEquals(2, stacks.size()); assertEquals(2, stacks.numElements()); } |
### Question:
SetOfStacks { public E pop() { final E element = stacks.getFirst().remove(); if (stacks.getFirst().isEmpty() && stacks.size() != 1) { stacks.remove(); } return element; } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }### Answer:
@Test public void testPop() { stacks.push(1); stacks.push(2); int e = stacks.pop(); assertEquals(2, e); assertEquals(1, stacks.size()); assertEquals(1, stacks.numElements()); } |
### Question:
SetOfStacks { public E peek() { return stacks.getFirst().getFirst(); } SetOfStacks(); SetOfStacks(int capacity); E push(E element); E pop(); E peek(); boolean isEmpty(); int size(); int numElements(); }### Answer:
@Test public void testPeek() { stacks.push(1); stacks.push(2); int e = stacks.peek(); assertEquals(2, e); assertEquals(2, stacks.size()); assertEquals(2, stacks.numElements()); } |
### Question:
PracticeQuestionsCh2 { public static <E> void removeDupes(LinkedList<E> linkedList) { Set<E> dupes = new HashSet<E>(); LinkedListNode<E> current = linkedList.head().successor(); E data = null; for (int idx = 0; idx < linkedList.size(); idx++) { data = current.data(); current = current.successor(); if (dupes.contains(data)) { linkedList.remove(idx); } else { dupes.add(data); } } } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }### Answer:
@Test public void testRemoveDupes() { LinkedList<Integer> linkedList = new LinkedList<Integer>(); linkedList.add(1); linkedList.add(2); linkedList.add(1); removeDupes(linkedList); assertEquals(2, linkedList.size()); assertEquals(Integer.valueOf(1), linkedList.remove()); assertEquals(Integer.valueOf(2), linkedList.remove()); assertEquals(0, linkedList.size()); } |
### Question:
PracticeQuestionsCh2 { public static <E extends Comparable<E>> void partition(LinkedList<E> linkedList, E pivot) { int lastIdx = linkedList.size() - 1; int pivotIdx = linkedList.indexOf(pivot); if (pivotIdx != linkedList.lastIndexOf(pivot)) { throw new IllegalArgumentException("Can't handle dupes in input list."); } swap(linkedList, pivotIdx, lastIdx); int storeIdx = 0; for (int runningIdx = 0; runningIdx < lastIdx; runningIdx++) { if (linkedList.get(runningIdx).compareTo(pivot) <= 0) { swap(linkedList, runningIdx, storeIdx); storeIdx++; } } swap(linkedList, storeIdx, lastIdx); } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }### Answer:
@Test public void testPartition() { LinkedList<Integer> linkedList = new LinkedList<Integer>(); linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(1); partition(linkedList, 4); assertEquals(4, linkedList.size()); assertEquals(Integer.valueOf(2), linkedList.get(0)); assertEquals(Integer.valueOf(1), linkedList.get(1)); assertEquals(Integer.valueOf(4), linkedList.get(2)); assertEquals(Integer.valueOf(5), linkedList.get(3)); } |
### Question:
PracticeQuestionsCh2 { public static <E> boolean isPalindrome(LinkedList<E> linkedList) { int lastIdx = linkedList.size() - 1; for (int runningIdx = 0; runningIdx < lastIdx; runningIdx++, lastIdx--) { if (!linkedList.get(runningIdx).equals(linkedList.get(lastIdx))) { return false; } } return true; } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }### Answer:
@Test public void testIsPalindrome() { LinkedList<Character> linkedList = new LinkedList<Character>(); linkedList.add('c'); linkedList.add('i'); linkedList.add('v'); linkedList.add('i'); linkedList.add('c'); assertTrue(isPalindrome(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('n'); linkedList.add('a'); assertTrue(isPalindrome(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('m'); linkedList.add('a'); assertFalse(isPalindrome(linkedList)); } |
### Question:
PracticeQuestionsCh2 { public static <E> boolean isPalindromeVariant(LinkedList<E> linkedList) { LinkedListNode<E> slow = linkedList.head().successor(); LinkedListNode<E> fast = slow; Stack<E> stack = new Stack<E>(); while (fast != linkedList.tail() && fast.successor() != linkedList.tail()) { stack.push(slow.data()); slow = slow.successor(); fast = fast.successor().successor(); } if (fast == linkedList.tail() && !slow.data().equals(stack.pop())) { return false; } do { slow = slow.successor(); if (!slow.data().equals(stack.pop())) { return false; } } while (slow.successor() != linkedList.tail()); return true; } static void removeDupes(LinkedList<E> linkedList); static void partition(LinkedList<E> linkedList, E pivot); static boolean isPalindrome(LinkedList<E> linkedList); static boolean isPalindromeVariant(LinkedList<E> linkedList); }### Answer:
@Test public void testIsPalindromeVariant() { LinkedList<Character> linkedList = new LinkedList<Character>(); linkedList.add('c'); linkedList.add('i'); linkedList.add('v'); linkedList.add('i'); linkedList.add('c'); assertTrue(isPalindromeVariant(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('n'); linkedList.add('a'); assertTrue(isPalindromeVariant(linkedList)); linkedList = new LinkedList<Character>(); linkedList.add('a'); linkedList.add('n'); linkedList.add('m'); linkedList.add('a'); assertFalse(isPalindromeVariant(linkedList)); } |
### Question:
BinaryTreeWalker { public static <E> List<E> recursiveInorder(BinaryTreeNode<E> root) { List<E> visited = new ArrayList<>(); if (root.leftChild() != null) { visited.addAll(recursiveInorder(root.leftChild())); } visited.add(root.data()); if (root.rightChild() != null) { visited.addAll(recursiveInorder(root.rightChild())); } return visited; } static List<E> iterativeInorder(BinaryTreeNode<E> root); static List<E> recursiveInorder(BinaryTreeNode<E> root); static final Logger LOGGER; }### Answer:
@Test public void testRecursiveInorder() { assertInorder(recursiveInorder(root)); } |
### Question:
PracticeQuestionsCh1 { public static boolean isUnique(String s) { int[] arr = new int[3]; int len = s.length(); int ch = -1; final int numASCIICtrlChars = 32; for (int i = 0; i < len; i++) { ch = s.charAt(i) - numASCIICtrlChars; int bitmask = ch & 0x1f; int bitVectorIdx = ch >> 5; ch = arr[bitVectorIdx] & bitmask; if (ch == 1) { return false; } arr[bitVectorIdx] |= bitmask; } return true; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }### Answer:
@Test public void testIsUnique() { assertTrue(isUnique("abc")); assertFalse(isUnique("aba")); } |
### Question:
PracticeQuestionsCh1 { public static boolean isPermutation(String s1, String s2) { int len = s1.length(); if (s2.length() != len) { return false; } char[] charArr1 = s1.toCharArray(); char[] charArr2 = s2.toCharArray(); short sum1 = 0; short sum2 = 0; for (short i = 0; i < len; i++) { sum1 += ((short) charArr1[i]); sum2 += ((short) charArr2[i]); } return sum1 == sum2; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }### Answer:
@Test public void testIsPermutation() { assertTrue(isPermutation("abc", "cba")); assertTrue(isPermutation("aBc", "acB")); assertFalse(isPermutation("abc", "c")); assertFalse(isPermutation("abc", "def")); } |
### Question:
PracticeQuestionsCh1 { public static String encodeRepeatedChars(final String str) { final AtomicInteger repeatCount = new AtomicInteger(1); final StringBuilder previousChar = new StringBuilder(" "); final StringBuilder buffer = new StringBuilder(); final int len = str.length() - 1; IntStream.range(0, str.length()).forEach(idx -> { if (str.charAt(idx) == previousChar.charAt(0)) { repeatCount.incrementAndGet(); } else { if (idx != 0) { buffer.append(previousChar.charAt(0)).append(repeatCount.get()); } repeatCount.set(1); previousChar.setCharAt(0, str.charAt(idx)); } if (idx == len) { buffer.append(str.charAt(idx)).append(repeatCount.get()); } }); return buffer.length() < str.length() ? buffer.toString() : str; } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }### Answer:
@Test public void testEncodeRepeatedChars() { assertEquals("a3b2", encodeRepeatedChars("aaabb")); assertEquals("abc", encodeRepeatedChars("abc")); assertEquals("a3b3a1", encodeRepeatedChars("aaabbba")); assertEquals("a1b3c3", encodeRepeatedChars("abbbccc")); } |
### Question:
PracticeQuestionsCh1 { public static void fillIfZero(int[][] matrix) { int numRows = matrix.length; int numCols = matrix[0].length; int rowWhereZeroFound = -1; int colWhereZeroFound = -1; for (int rowNum = 0; rowNum < numRows; rowNum++) { boolean isZeroFound = false; for (int colNum = 0; colNum < numCols; colNum++) { isZeroFound = (matrix[rowNum][colNum] == 0) | isZeroFound; if (isZeroFound) { LOGGER.debug("Zero found at [{},{}].", rowNum, colNum); colWhereZeroFound = colNum; rowWhereZeroFound = rowNum; break; } } if (isZeroFound) { LOGGER.debug("Setting to zero [{},{}].", rowNum, colWhereZeroFound); matrix[rowNum][colWhereZeroFound] = 0; } } LOGGER.debug("Setting to zero [{}].", rowWhereZeroFound); Arrays.fill(matrix[rowWhereZeroFound], 0); for (int rowNum = 0; rowNum < rowWhereZeroFound; rowNum++) { LOGGER.debug("Setting to zero [{},{}].", rowNum, colWhereZeroFound); matrix[rowNum][colWhereZeroFound] = 0; } } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }### Answer:
@Test public void testFillIfZero() { int[][] matrix = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 0 } }; fillIfZero(matrix); assertEquals(0, matrix[0][1]); assertEquals(0, matrix[1][1]); assertEquals(0, matrix[2][0]); assertEquals(0, matrix[2][1]); assertEquals(1, matrix[0][0]); assertEquals(3, matrix[1][0]); } |
### Question:
PracticeQuestionsCh1 { public static boolean isRotation(String s1, String s2) { int len = s1.length(); if (s2.length() != len) { return false; } char[] charArr1 = s1.toCharArray(); char[] charArr2 = s2.toCharArray(); int j = 0; for (int i = 0; i < len && j < len; i++) { if (charArr1[i] == charArr2[j]) { j++; } } return isSubstring(s1, String.valueOf(Arrays.copyOfRange(charArr2, j, len))); } static boolean isUnique(String s); static boolean isPermutation(String s1, String s2); static String encodeRepeatedChars(final String str); static void fillIfZero(int[][] matrix); static boolean isRotation(String s1, String s2); static final Logger LOGGER; }### Answer:
@Test public void testIsRotation() { assertTrue(isRotation("erbottlewat", "waterbottle")); assertFalse(isRotation("erbottlewat", "waterbottel")); } |
### Question:
DeckOfCards extends AbstractList<Card> { public DeckOfCards() { Suit[] suits = Suit.values(); Rank[] ranks = Rank.values(); int numCard = 0; for (Suit aSuit : suits) { for (Rank aRank : ranks) { Card newCard = new Card(aSuit, aRank); cards[numCard++] = newCard; } } } DeckOfCards(); @Override Card get(int index); Card set(int index, Card card); @Override int size(); static final int NUM_CARDS; }### Answer:
@Test public void testDeckOfCards() { Assert.assertEquals(deck.get(0).getSuit(), deck.get(12).getSuit()); Assert.assertEquals(deck.get(13).getSuit(), deck.get(25).getSuit()); Assert.assertEquals(deck.get(26).getSuit(), deck.get(38).getSuit()); Assert.assertEquals(deck.get(39).getSuit(), deck.get(51).getSuit()); Assert.assertEquals(deck.get(0).getRank(), deck.get(13).getRank()); Assert.assertEquals(deck.get(0).getRank(), deck.get(26).getRank()); Assert.assertEquals(deck.get(0).getRank(), deck.get(39).getRank()); } |
### Question:
JigsawPuzzle { public boolean solve() { Piece aPiece = null; Piece anotherPiece = null; Stack<Piece> stackOfPieces = stackOfPieces(); while (stackOfPieces.size() > 1) { aPiece = stackOfPieces.pop(); while (!stackOfPieces.isEmpty()) { anotherPiece = stackOfPieces.pop(); if (aPiece.fitsWith(anotherPiece)) { Piece bigPiece = aPiece.joinWith(anotherPiece); stackOfPieces.push(bigPiece); break; } } } return stackOfPieces.size() == 1; } JigsawPuzzle(Piece[] pieces); Piece[] piecesOfPuzzle(); boolean solve(); public Piece[] piecesOfPuzzle; }### Answer:
@Test public void testSolve() { Piece[] pieces = new Piece[5]; Piece first = new Piece(0); Piece second = new Piece(1); Piece third = new Piece(1); Piece fourth = new Piece(2); Piece fifth = new Piece(3); pieces[0] = first; pieces[1] = second; pieces[2] = third; pieces[3] = fourth; pieces[4] = fifth; JigsawPuzzle puzzle = new JigsawPuzzle(pieces); Assert.assertTrue(puzzle.solve()); }
@Test public void testCannotSolve() { Piece[] pieces = new Piece[5]; Piece first = new Piece(0); Piece second = new Piece(1); Piece third = new Piece(1); Piece fourth = new Piece(2); Piece fifth = new Piece(6); pieces[0] = first; pieces[1] = second; pieces[2] = third; pieces[3] = fourth; pieces[4] = fifth; JigsawPuzzle puzzle = new JigsawPuzzle(pieces); Assert.assertFalse(puzzle.solve()); } |
### Question:
PracticeQuestionsCh9 { public static int magicIndex(int[] array, int startIndex, int endIndex) { if (startIndex >= endIndex) { return -1; } long avg = startIndex + endIndex >> 1; if (avg >= Integer.MAX_VALUE) { return -1; } int midIdx = (int) avg; int val = array[midIdx]; if (val == midIdx) { LOGGER.debug("Found magic index{}.%n", midIdx); return midIdx; } LOGGER.debug("Start index = {}, end index = {}, middle index = {}.%n", startIndex, endIndex, midIdx); LOGGER.debug("val = {}.%n", val); if (midIdx < val) { return magicIndex(array, startIndex, --midIdx); } return magicIndex(array, ++midIdx, endIndex); } static int magicIndex(int[] array, int startIndex, int endIndex); static Set<String> perm(String s); static final Logger LOGGER; }### Answer:
@Test public void testMagicIndex() { int[] array = new int[] { -1, 0, 2 }; assertEquals(2, magicIndex(array, 0, array.length)); array = new int[] { 1, 2, 3 }; assertEquals(-1, PracticeQuestionsCh9.magicIndex(array, 0, array.length)); } |
### Question:
PracticeQuestionsCh9 { public static Set<String> perm(String s) { Set<String> perms = new HashSet<String>(); recursivePerm(s, s.length() - 1, perms); return perms; } static int magicIndex(int[] array, int startIndex, int endIndex); static Set<String> perm(String s); static final Logger LOGGER; }### Answer:
@Test public void testPerm() { String s = "abc"; String[] expected = new String[] { "cab", "abc", "bac", "acb" }; Set<String> allPerms = perm(s); assertEquals(expected.length, allPerms.size()); stream(expected).forEach(aPerm -> assertTrue(allPerms.contains(aPerm))); } |
### Question:
LinkedList { public boolean add(E e) { return add(size, e); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); }### Answer:
@Test public void testAdd() { Assert.assertEquals(3, linkedList.size()); Assert.assertTrue(linkedList.add(4)); Assert.assertEquals(4, linkedList.size()); Assert.assertTrue(linkedList.add(linkedList.size(), 0)); Assert.assertEquals(5, linkedList.size()); Assert.assertEquals(Integer.valueOf(4), linkedList.remove(3)); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); }
@Test(expected = IndexOutOfBoundsException.class) public void testInvalidIndexOperation() { linkedList.add(10, 1); } |
### Question:
LinkedList { public E remove() { return remove(0); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); }### Answer:
@Test public void testRemove() { Assert.assertEquals(3, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(2, linkedList.size()); Assert.assertEquals(Integer.valueOf(2), linkedList.remove(0)); Assert.assertEquals(1, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(0, linkedList.size()); } |
### Question:
LinkedList { public void reverse() { if (size <= 1) { return; } LinkedListNode<E> predecessor = head; LinkedListNode<E> current = head.successor(); LinkedListNode<E> successor = null; while (current != this.tail) { successor = current.successor(); current.setSuccessor(predecessor); predecessor = current; current = successor; } tail = head; tail.setSuccessor(null); head = current; head.setSuccessor(predecessor); } LinkedList(); LinkedList(Collection<E> elements); boolean add(E e); boolean add(int index, E e); boolean addAll(Collection<E> elements); E remove(); E remove(int index); E peek(); int size(); boolean isEmpty(); void reverse(); LinkedListNode<E> head(); LinkedListNode<E> tail(); E get(int index); void set(int index, E element); int indexOf(E element); int lastIndexOf(E element); @Override String toString(); }### Answer:
@Test public void testReverse() { linkedList.reverse(); Assert.assertEquals(3, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(2, linkedList.size()); Assert.assertEquals(Integer.valueOf(2), linkedList.remove()); Assert.assertEquals(1, linkedList.size()); Assert.assertEquals(Integer.valueOf(1), linkedList.remove()); Assert.assertEquals(0, linkedList.size()); } |
### Question:
Hashtable { @SuppressWarnings("unchecked") public Hashtable() { buckets = new LinkedList[capacity]; } @SuppressWarnings("unchecked") Hashtable(); V put(K key, V value); V get(K key); final int size(); final float loadFactor(); static final Logger LOGGER; }### Answer:
@Test public void testHashtable() { Assert.assertEquals(2, hashtable.size()); Assert.assertEquals(Integer.valueOf(3), hashtable.get(2)); Assert.assertEquals(Integer.valueOf(2), hashtable.get(1)); hashtable.put(2, 5); Assert.assertEquals(Integer.valueOf(5), hashtable.get(2)); Assert.assertEquals(null, hashtable.get(10)); } |
### Question:
Sorter { public static int[] mergeSort(int[] arr) { return recursiveMergeSort(arr, 0, arr.length - 1); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); }### Answer:
@Test public void testMergeSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.mergeSort(arr); Assert.assertArrayEquals(expected, actual); } |
### Question:
IOUtils { public static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf) { MapFile.Reader reader = null; Writable value = null; LOGGER.debug("MapFile URI: {}.", dirURI); try { final Path inputPath = new Path(dirURI); final FileSystem fs = inputPath.getFileSystem(conf); reader = new MapFile.Reader(fs, dirURI.toString(), conf); value = reader.get(key, new Text()); } catch (IOException ioe) { ioe.printStackTrace(); } finally { closeStreams(reader); } LOGGER.debug("Returning value: {}, for key: {}.", value, key); return value; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; }### Answer:
@Test public void testKeyFound() { final String key = "3858243"; final String expectedValue = "1975 5485 1973 \"FR\" \"\" 445095 3 12 2 6 63 7 2 0.8571 0 0.2778 6 8.1429 0 0 0 0"; final Writable actualValue = findInMapFile(new Text(key), dirURI, conf); Assert.assertNotNull("Value for key: " + key + " shouldn't be null", actualValue); Assert.assertEquals("Wrong value retirned for key: " + key, expectedValue, actualValue.toString()); }
@Test public void testKeyNotFound() { final String key = "1"; final Writable actualValue = findInMapFile(new Text(key), dirURI, conf); Assert.assertNull("Value for key: " + key + " should be null", actualValue); } |
### Question:
Sorter { public static int[] quickSort(int[] arr) { return recursiveQuickSort(arr, 0, arr.length - 1); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); }### Answer:
@Test public void testQuickSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.quickSort(arr); Assert.assertArrayEquals(expected, actual); } |
### Question:
Sorter { public static int[] bucketSort(int[] arr) { int[][] buckets = scatter(arr); ArrayDeque<int[]> stack = new ArrayDeque<int[]>(); for (int[] bucket : buckets) { if (bucket != null) { stack.add(mergeSort(bucket)); } } return gather(stack); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); }### Answer:
@Test public void testBucketSort() { int[] arr = new int[] { 17, 3, 99, 51 }; int[] expected = new int[] { 3, 17, 51, 99 }; int[] actual = Sorter.bucketSort(arr); Assert.assertArrayEquals(expected, actual); } |
### Question:
Sorter { public static Integer[] countingSort(final int[] arr) { final Map<Integer, Pair> countMap = new HashMap<>(); for (final int i : arr) { Pair p = new Pair(i, 1); if (countMap.containsKey(i)) { p.value += countMap.get(i).value; } countMap.put(i, p); } BinarySearchTree<Pair> bst = new BinarySearchTree<>(countMap.values()); final List<Pair> sortedPairs = BinaryTreeWalker.recursiveInorder(bst.root()); return CollectionUtils.collect(sortedPairs, TransformerUtils.<Pair, Integer> invokerTransformer("getKey")) .toArray(new Integer[] {}); } static int[] mergeSort(int[] arr); static int[] quickSort(int[] arr); static int[] bucketSort(int[] arr); static Integer[] countingSort(final int[] arr); }### Answer:
@Test public void testCountingSort() { int[] arr = new int[] { 17, 3, 99, 51 }; Integer[] expected = { 3, 17, 51, 99 }; Integer[] actual = Sorter.countingSort(arr); Assert.assertArrayEquals(expected, actual); } |
### Question:
Searcher { public static <E extends Comparable<E>> BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, BinaryTreeNode<E> startNode, E value) { if (startNode == null || value.equals(startNode.data())) { return startNode; } if (value.compareTo(startNode.data()) < 0) { return binarySearch(binTree, startNode.leftChild(), value); } return binarySearch(binTree, startNode.rightChild(), value); } static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> binarySearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> breadthFirstSearch(BinarySearchTree<E> binTree, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree,
BinaryTreeNode<E> startNode, E value); static BinaryTreeNode<E> depthFirstSearch(BinarySearchTree<E> binTree, E value); static final Logger LOGGER; }### Answer:
@Test public void testBinarySearch() { for (int i = 1; i < 6; i++) { Assert.assertNotNull(Searcher.binarySearch(binTree, i)); } Assert.assertNull(Searcher.binarySearch(binTree, 10)); BinaryTreeNode<Integer> four = Searcher.binarySearch(binTree, 4); Assert.assertNotNull(four); Assert.assertFalse(four.isLeaf()); Assert.assertNull(four.leftChild()); Assert.assertNotNull(four.rightChild()); Assert.assertEquals(Integer.valueOf(5), four.rightChild().data()); BinaryTreeNode<Integer> five = Searcher.binarySearch(binTree, 5); Assert.assertTrue(five.isLeaf()); } |
### Question:
Rentals extends ArrayList<AbstractRental> { public Rentals(String customerName) { this.customerName = customerName; } Rentals(String customerName); String rentalStatement(); }### Answer:
@Test public void testRentals() { Rentals rentals = new Rentals("John Doe"); Assert.assertEquals("Wrong size", 0, rentals.size()); Movie theShining = new Movie("The Shining", Movie.REGULAR); AbstractRental theShiningRentalForADay = new RegularRental(theShining, 1); rentals.add(theShiningRentalForADay); Movie topGun = new Movie("Top Gun", Movie.REGULAR); AbstractRental topGunRentalFor3Days = new RegularRental(topGun, 3); rentals.add(topGunRentalFor3Days); Assert.assertEquals("Wrong size", 2, rentals.size()); AbstractRental firstRental = rentals.get(0); AbstractRental secondRental = rentals.get(1); Assert.assertEquals("Wrong number of rental days", 1, firstRental.getDaysRented()); Assert.assertEquals("Wrong number of rental days", 3, secondRental.getDaysRented()); Assert.assertEquals("Wrong movie title", "The Shining", firstRental .getMovie().getTitle()); Assert.assertEquals("Wrong movie title", "Top Gun", secondRental .getMovie().getTitle()); } |
### Question:
HttpHeadTask implements Callable<String> { @Override public String call() { CloseableHttpResponse response = null; try { response = httpClient.execute(httpHead, context); response.getEntity(); log.info("Successfully received response from: {}.", httpHead.getURI().getHost()); return httpHead.getURI().getHost(); } catch (IOException ex) { log.error("Something bad happened while getting from: {}.", ex, httpHead.getURI().getHost()); return ""; } finally { if (response != null) { try { response.close(); } catch (IOException e) { log.error("Failed to close response: {}.", e, httpHead.getURI().getHost()); } } } } HttpHeadTask(CloseableHttpClient httpClient, String uri); @Override String call(); }### Answer:
@Test @DisplayName("Keep alive doesn't prevent a connection from being used for a different route") public void test1() throws IOException, InterruptedException { connMgr.setDefaultMaxPerRoute(5); connMgr.setMaxTotal(5); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connMgr) .setDefaultRequestConfig(requestConfig) .setKeepAliveStrategy((response, context) -> 10000l) .build(); StepVerifier.create(Flux.range(1, 5) .parallel(10) .runOn(Schedulers.parallel()) .map(i -> "https: .flatMap(uri -> Mono.fromCallable(new HttpHeadTask(httpClient, uri)) .delayElement(Duration.ofMillis(3000l)))) .recordWith(ArrayList::new) .expectNextCount(5) .consumeRecordedWith(results -> assertThat(results) .hasSize(5) .allSatisfy(verifier)) .verifyComplete(); HttpHeadTask headFromYahooTask = new HttpHeadTask(httpClient, "https: assertThat(headFromYahooTask.call()).isEqualTo("www.yahoo.com"); httpClient.close(); } |
### Question:
JackOfAllTrades { public static IntegerNode reverseList(IntegerNode head) { IntegerNode first = reverse(head.next(), head); return IntegerNode.builder() .next(first) .build(); } static IntegerNode reverseList(IntegerNode head); }### Answer:
@Test void testReverseList() { IntegerNode head = LinkedListFactory.newLinkedList(); for (IntegerNode current = head; current != null; current = current.next()) { System.out.printf("%s%s", current.toString(), current.next() == null ? "\n" : "--->"); } head = JackOfAllTrades.reverseList(head); for (IntegerNode current = head; current != null; current = current.next()) { System.out.printf("%s%s", current.toString(), current.next() == null ? "\n" : "--->"); } } |
### Question:
BinaryTreeUtil { public static int height(IntegerNode root) { if (root == null) { return 0; } return Math.max(height(root.left()), height(root.right())) + 1; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); }### Answer:
@Test void testHeight() { assertThat(BinaryTreeUtil.height(ROOT)).isEqualTo(4); } |
### Question:
BinaryTreeUtil { public static boolean isSame(IntegerNode root1, IntegerNode root2) { boolean same = false; if (root1 == root2) { same = true; } else if (root1 != null && root2 != null && root1.value() == root2.value()) { same = isSame(root1.left(), root2.left()) && isSame(root1.right(), root2.right()); } return same; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); }### Answer:
@Test void testIsSame() { IntegerNode sameAsRoot = newBinaryTree(); assertThat(isSame(ROOT, sameAsRoot)).isTrue(); IntegerNode five = IntegerNode.builder() .value(5) .build(); IntegerNode three = IntegerNode.builder() .left(five) .value(3) .build(); IntegerNode six = IntegerNode.builder() .value(6) .build(); IntegerNode fifteen = IntegerNode.builder() .left(three) .right(six) .value(15) .build(); assertThat(isSame(ROOT, fifteen)).isFalse(); } |
### Question:
BinaryTreeUtil { public static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2) { Map.Entry<IntegerNode, Boolean> lca = internalLCA(root, value1, value2); return lca != null && lca.getValue() ? lca.getKey() : null; } private BinaryTreeUtil(); static int height(IntegerNode root); static boolean isBST(ParentAwareIntegerNode root); static boolean isSame(IntegerNode root1, IntegerNode root2); static IntegerNode lowestCommonAncestor(IntegerNode root, int value1, int value2); }### Answer:
@Test void testLowestCommonAncestor() { IntegerNode five = IntegerNode.builder() .value(5) .build(); IntegerNode nine = IntegerNode.builder() .value(9) .build(); IntegerNode eleven = IntegerNode.builder() .left(nine) .right(five) .value(11) .build(); IntegerNode two = IntegerNode.builder() .value(2) .build(); IntegerNode six = IntegerNode.builder() .left(two) .right(eleven) .value(6) .build(); IntegerNode seven = IntegerNode.builder() .value(7) .build(); IntegerNode thirteen = IntegerNode.builder() .left(seven) .value(13) .build(); IntegerNode eight = IntegerNode.builder() .right(thirteen) .value(8) .build(); IntegerNode three = IntegerNode.builder() .left(six) .right(eight) .value(3) .build(); print(three); IntegerNode lca = lowestCommonAncestor(three, 2, 5); assertThat(lca).isNotNull(); assertThat(lca.value()).isEqualTo(6); lca = lowestCommonAncestor(three, 8, 11); assertThat(lca).isNotNull(); assertThat(lca.value()).isEqualTo(3); lca = lowestCommonAncestor(three, 2, 19); assertThat(lca).isNull(); } |
### Question:
BinarySearchTree { public List<Integer> nodes() { return unmodifiableList(nodes(rootNode)); } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); }### Answer:
@Test void testNodes() { List<Integer> nodes = TREE.nodes(); assertThat(nodes).hasSize(6); assertThat(nodes).containsExactlyInAnyOrder(10, -5, -8, 7, 16, 18); } |
### Question:
BinarySearchTree { public final boolean contains(int value) { return find(value) != null; } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); }### Answer:
@Test void testContains() { assertThat(TREE.nodes().stream() .allMatch(TREE::contains)).isTrue(); assertThat(TREE.contains(99)).isFalse(); } |
### Question:
IOUtils { public static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension) { if (filename != null && filename.length() <= 1) { return filename; } LOGGER.debug("Received: {}.", filename); if (removeExistingExtension) { filename = removeExtension(filename); } LOGGER.debug("Returning: {}.", filename + newExtension); return filename + newExtension; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; }### Answer:
@Test public void testAddExtension() { Assert.assertEquals("Wrong extension", "/a/b/c.txt.log", addExtension("/a/b/c.txt", ".log", false)); Assert.assertEquals("Wrong extension", "/a/b/c.log", addExtension("/a/b/c.txt", ".log", true)); Assert.assertEquals("Wrong extension", ".log", addExtension(".txt", ".log", true)); Assert.assertEquals("Wrong extension", ".txt.log", addExtension(".txt", ".log", false)); Assert.assertEquals("Wrong extension", ".", addExtension(".", ".txt", true)); Assert.assertEquals("Wrong extension", ".", addExtension(".", ".txt", false)); Assert.assertEquals("Wrong extension", "a.txt", addExtension("a.", ".txt", true)); } |
### Question:
BinarySearchTree { public ParentAwareIntegerNode root() { return rootNode; } @Builder private BinarySearchTree(Integer root, @Singular List<Integer> nodes); ParentAwareIntegerNode root(); List<Integer> nodes(); final ParentAwareIntegerNode insert(int value); final boolean contains(int value); final ParentAwareIntegerNode delete(int value); }### Answer:
@Test void testIsBST() { assertThat(isBST(TREE.root())).isTrue(); ParentAwareIntegerNode fifteen = ParentAwareIntegerNode.builder() .value(15) .build(); ParentAwareIntegerNode three = ParentAwareIntegerNode.builder() .value(3) .build(); ParentAwareIntegerNode five = ParentAwareIntegerNode.builder() .left(fifteen) .right(three) .value(5) .build(); three.setParent(five); fifteen.setParent(five); assertThat(isBST(five)).isFalse(); } |
### Question:
JackOfAllTrades { public static List<String> allPermutations(String str) { Map<Character, Integer> countMap = str.chars() .mapToObj(i -> (char) i) .collect(collectingAndThen(toMap(identity(), i -> 1, (i, j) -> i + j, TreeMap::new), Collections::unmodifiableMap)); return allPermutations(countMap, 0, str); } static List<String> allPermutations(String str); }### Answer:
@Test void testAllPermutationsOfAString() { assertThat(JackOfAllTrades.allPermutations("AABC")) .containsExactlyInAnyOrder("AABC", "AACB", "ABAC", "ABCA", "ACAB", "ACBA", "BAAC", "BACA", "BCAA", "CAAB", "CABA", "CBAA"); } |
### Question:
ClientConfig { @Bean Client omdbApiClient() { return new OmdbApiClient(env.getProperty("omdbapi.endpoint")); } }### Answer:
@Test public void testOmdbApiClient() { assertNotNull(omdbApiClient); assertTrue(omdbApiClient instanceof OmdbApiClient); assertEquals("http: } |
### Question:
ClientConfig { @Bean Client deanClatworthyClient() { return new DeanClatworthyClient( env.getProperty("deanclatworthyapi.endpoint")); } }### Answer:
@Test public void testDeanClatworthyClient() { assertNotNull(deanClatworthyClient); assertTrue(deanClatworthyClient instanceof DeanClatworthyClient); assertEquals("http: deanClatworthyClient.getEndpoint()); } |
### Question:
ClientConfig { @Bean RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(clientRequestFactory()); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(jsonMessageConverter()); restTemplate.setMessageConverters(messageConverters); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new HttpRequestInterceptor()); restTemplate.setInterceptors(interceptors); return restTemplate; } }### Answer:
@Test public void testRestTemplate() { List<HttpMessageConverter<?>> messageConverters = restTemplate .getMessageConverters(); assertNotNull(messageConverters); assertTrue(messageConverters.size() == 1); HttpMessageConverter<?> messageConverter = messageConverters.get(0); assertNotNull(messageConverter); assertTrue(messageConverter instanceof MappingJacksonHttpMessageConverter); List<MediaType> mediaTypes = messageConverter.getSupportedMediaTypes(); assertNotNull(mediaTypes); assertTrue(mediaTypes.contains(MediaType.TEXT_HTML)); assertTrue(mediaTypes.contains(MediaType.APPLICATION_JSON)); ClientHttpRequestFactory requestFactory = restTemplate .getRequestFactory(); assertNotNull(requestFactory); } |
### Question:
OmdbApiClient extends AbstractClient { @SafeVarargs public final Movie getMovieInfoByTitleAndYear(String title, short year, Map<String, String>... param) { Map<String, String> queryParam = getQueryParam(param); queryParam.put(getEnv().getProperty("omdbapi.title"), title); queryParam .put(getEnv().getProperty("omdbapi.year"), Short.toString(year)); return getMovieInfoInternal(queryParam, OmdbApiStyleMovie.class); } OmdbApiClient(String endpoint); @SafeVarargs final Movie getMovieInfoByTitleAndYear(String title, short year,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoByTitleOnly(String title,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoById(String id, Map<String, String>... param); }### Answer:
@Test public void testGetMovieInfoByTitleAndYear() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client.getMovieInfoByTitleAndYear( "Star Trek", (short) 1996); assertNotNull("At least one Star Trek movie should've been found", omdbApiStyleMovie); assertEquals("Wrong IMDB Id", "tt0117731", omdbApiStyleMovie.getImdbId()); assertEquals("Wrong title", "Star Trek: First Contact", omdbApiStyleMovie.getTitle()); assertEquals("Wrong release year", 1996, omdbApiStyleMovie.getYear()); assertNotNull("Wrong genre", omdbApiStyleMovie.getGenre()); assertNotNull("Wrong rating", omdbApiStyleMovie.getImdbRating()); assertNotNull("Wrong runtime", omdbApiStyleMovie.getRuntime()); assertNotNull("Wrong votes", omdbApiStyleMovie.getImdbVotes()); System.out.println("testGetMovieInfoByTitleAndYear: " + omdbApiStyleMovie); } |
### Question:
OmdbApiClient extends AbstractClient { @SafeVarargs public final Movie getMovieInfoByTitleOnly(String title, Map<String, String>... param) { Map<String, String> queryParam = getQueryParam(param); queryParam.put(getEnv().getProperty("omdbapi.title"), title); return getMovieInfoInternal(queryParam, OmdbApiStyleMovie.class); } OmdbApiClient(String endpoint); @SafeVarargs final Movie getMovieInfoByTitleAndYear(String title, short year,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoByTitleOnly(String title,
Map<String, String>... param); @SafeVarargs final Movie getMovieInfoById(String id, Map<String, String>... param); }### Answer:
@Test public void testGetMovieInfoByTitleOnly() { @SuppressWarnings("unchecked") Movie omdbApiStyleMovie = client .getMovieInfoByTitleOnly("Star Trek"); assertNotNull("At least one Star Trek movie should've been found", omdbApiStyleMovie); assertEquals("Wrong IMDB Id", "tt0796366", omdbApiStyleMovie.getImdbId()); assertEquals("Wrong title", "Star Trek", omdbApiStyleMovie.getTitle()); assertEquals("Wrong release year", 2009, omdbApiStyleMovie.getYear()); assertNotNull("Wrong genre", omdbApiStyleMovie.getGenre()); assertNotNull("Wrong rating", omdbApiStyleMovie.getImdbRating()); assertNotNull("Wrong runtime", omdbApiStyleMovie.getRuntime()); assertNotNull("Wrong votes", omdbApiStyleMovie.getImdbVotes()); System.out.println("testGetMovieInfoByTitleOnly: " + omdbApiStyleMovie); } |
### Question:
ClientFactory { public static final ClientFactory getInstance() { if (factory == null) factory = new ClientFactory(); return factory; } private ClientFactory(); static final ClientFactory getInstance(); final Client getClient(ClientType type); }### Answer:
@Test public void testFactory() { assertNotNull(factory); assertSame(factory, ClientFactory.getInstance()); } |
### Question:
IOUtils { public static String removeExtension(String filename) { if ((filename != null && filename.length() <= 1) || filename == null) { return filename; } LOGGER.debug("Received: {}.", filename); final int idx = filename.lastIndexOf('.'); if (idx >= 0) { filename = filename.substring(0, idx); } LOGGER.debug("Returning: {}.", filename); return filename; } static Writable findInMapFile(final Text key, URI dirURI, final Configuration conf); @SuppressWarnings("resource") static URI createMapFile(URI inputURI, final Configuration conf); static URI compressFile(final URI uncompressedURI, final String codecName, final Configuration conf); static String addExtension(String filename, final String newExtension, final boolean removeExistingExtension); static String removeExtension(String filename); static URI uncompressFile(final URI archiveURI, final Configuration conf); static final Logger LOGGER; }### Answer:
@Test public void testRemoveExtension() { Assert.assertEquals("Wrong extension", "/a/b/c.txt", removeExtension("/a/b/c.txt.log")); Assert.assertEquals("Wrong extension", "/a/b/c", removeExtension("/a/b/c.log")); Assert.assertEquals("Wrong extension", "", removeExtension(".txt")); Assert.assertEquals("Wrong extension", ".", removeExtension(".")); Assert.assertEquals("Wrong extension", "a", removeExtension("a.txt")); } |
### Question:
ClientFactory { public final Client getClient(ClientType type) { if (clients.get(type) == null) { switch (type) { case THE_OMDB_API: clients.put(type, ctx.getBean("omdbApiClient", Client.class)); break; case DEAN_CLATWORTHY: clients.put(type, ctx.getBean("deanClatworthyClient", Client.class)); break; } } return clients.get(type); } private ClientFactory(); static final ClientFactory getInstance(); final Client getClient(ClientType type); }### Answer:
@Test public void testClients() { Client omdbApiClient = factory.getClient(ClientType.THE_OMDB_API); Client deanClatworthyClient = factory .getClient(ClientType.DEAN_CLATWORTHY); assertNotNull(omdbApiClient); assertTrue(omdbApiClient instanceof OmdbApiClient); assertNotNull(deanClatworthyClient); assertTrue(deanClatworthyClient instanceof DeanClatworthyClient); assertEquals("http: assertEquals("http: deanClatworthyClient.getEndpoint()); } |
### Question:
TowerOfHanoi { public void move(int numDisks, int fromPeg, int toPeg) { if (numDisks == 1) { move(fromPeg, toPeg); } else { move(numDisks - 1, fromPeg, sparePeg(fromPeg, toPeg)); move(fromPeg, toPeg); move(numDisks - 1, sparePeg(fromPeg, toPeg), toPeg); } } TowerOfHanoi(int numPegs, int numDisks); List<Peg<Disk>> pegs(); void move(int numDisks, int fromPeg, int toPeg); static final Logger LOGGER; }### Answer:
@Test public void testMove() { tower.move(3, 0, 2); List<Peg<Disk>> pegs = tower.pegs(); Assert.assertEquals(3, pegs.size()); Assert.assertEquals(3, pegs.get(2).size()); Assert.assertEquals(0, pegs.get(0).size()); Assert.assertEquals(0, pegs.get(1).size()); } |
### Question:
LRUCache extends LinkedHashMap<K, V> { public LRUCache(final int capacity) { super(capacity, LOAD_FACTOR, ACCESS_ORDER); this.capacity = capacity; } LRUCache(final int capacity); }### Answer:
@Test public void testLRUCache() { LRUCache<String, String> cache = new LRUCache<>(1); cache.put("k1", "v1"); Assert.assertTrue(cache.containsKey("k1")); cache.put("k2", "v2"); Assert.assertFalse(cache.containsKey("k1")); Assert.assertTrue(cache.containsKey("k2")); } |
### Question:
Algorithms { public static String longestRepeatedSubstring(String str) { final String[] suffixArray = buildSuffixArray(str); Arrays.sort(suffixArray); String temp = ""; String lrs = ""; String aSuffix = null; String anotherSuffix = null; int len = -1; for (int i = 0; i < suffixArray.length - 1; ++i) { aSuffix = suffixArray[i]; anotherSuffix = suffixArray[i + 1]; if (aSuffix.trim().isEmpty() || anotherSuffix.trim().isEmpty()) { continue; } else if (anotherSuffix.startsWith(aSuffix)) { LOGGER.debug("\"{}\" starts with \"{}\".", anotherSuffix, aSuffix); temp = aSuffix; } else { len = Math.min(aSuffix.length(), anotherSuffix.length()); int j = 1; while (j <= len && aSuffix.regionMatches(0, anotherSuffix, 0, j)) { LOGGER.debug("Comparing \"{}\" and \"{}\".", aSuffix.substring(0, j), anotherSuffix.substring(0, j)); ++j; } temp = aSuffix.substring(0, --j); } lrs = temp.length() > lrs.length() ? temp : lrs; } return lrs; } static String longestRepeatedSubstring(String str); static final Logger LOGGER; }### Answer:
@Test public void testLongestRepeatedSubstring() { Assert.assertEquals("ana", longestRepeatedSubstring("banana")); Assert.assertEquals( " can do for you", longestRepeatedSubstring("Ask not what your country can do for you, ask what you can do for your country")); } |
### Question:
ReservationSystem { public static boolean cancelReservation(final String customerName, final Date date) { boolean cancelledReservation = false; final String formattedDate = format(date); synchronized (ReservationSystem.class) { final List<Reservation> allReservationsForADay = allReservations.get(formattedDate); if (allReservationsForADay != null) { final Reservation r = lookUpReservation(customerName, date); if (r != null) { final StringBuilder message = new StringBuilder(); message.append("Cancelled reservation for ").append(customerName).append(" for date ") .append(formattedDate).append("."); LOGGER.info(message.toString()); allReservationsForADay.remove(r); cancelledReservation = true; } } } return cancelledReservation; } static int makeReservation(final String customerName, final int seating, final Date date,
final SpecialFeature... specialFeatures); static boolean cancelReservation(final String customerName, final Date date); }### Answer:
@Test public void testCancelReservation() { final Date now = new Date(); ReservationSystem.makeReservation("Abhijit Sarkar", 2, now); int reservationId = ReservationSystem.makeReservation("Abhijit Sarkar", 2, now, WINDOW_SIDE); boolean reservationCancelled = ReservationSystem.cancelReservation("Abhijit Sarkar", now); Assert.assertTrue(reservationCancelled); Reservation r = ReservationSystem.lookUpReservation("Abhijit Sarkar", now); Assert.assertEquals(reservationId, r.reservationNumber()); } |
### Question:
TableManager { public static Table reserveTable(final int seating, final SpecialFeature... specialFeatures) { List<SpecialFeature> tableFeatures = null; Table table = null; outer: for (int availableTableId : availableTableIds) { table = findTableById(availableTableId); if (table.seatingCapacity() == seating) { tableFeatures = table.specialFeatures(); for (SpecialFeature requestedFeature : specialFeatures) { if (!tableFeatures.contains(requestedFeature)) { continue outer; } } availableTableIds.remove(availableTableId); break; } table = null; } return table; } static void setAllTables(Set<Table> allTables); static Table reserveTable(final int seating, final SpecialFeature... specialFeatures); }### Answer:
@Test public void testReserveTable() { Table table = TableManager.reserveTable(2); Assert.assertEquals(blahTable, table); table = TableManager.reserveTable(2, WINDOW_SIDE); Assert.assertEquals(windowSideTable, table); }
@Test public void testReserveTableWhenNoneMatches() { Assert.assertNull(TableManager.reserveTable(4)); }
@Test public void testReserveMoreTablesThanAvailable() { Table table = TableManager.reserveTable(2); Assert.assertEquals(blahTable, table); table = TableManager.reserveTable(2, WINDOW_SIDE); Assert.assertEquals(windowSideTable, table); Assert.assertNull(TableManager.reserveTable(2)); } |
### Question:
ReduceSideJoinReducer extends Reducer<TaggedKey, Text, IntWritable, Text> { @Override protected void reduce(TaggedKey key, Iterable<Text> values, Context ctx) throws IOException, InterruptedException { StringBuilder value = new StringBuilder(); LOGGER.debug("Entering reduce"); for (Text v : values) { LOGGER.debug("Loop - Key: {}, Value: {}.", key, value); value.append(v.toString()).append("|"); } value.delete(value.length() - 1, value.length()); LOGGER.debug("Key: {}, Value: {}.", key.getJoinKey(), value); ctx.write(key.getJoinKey(), new Text(value.toString())); } static final Logger LOGGER; }### Answer:
@Test public void testReduce() { TaggedKey key = new TaggedKey(1, 1); List<Text> values = new ArrayList<Text>(); values.add(new Text("Stephanie Leung,555-555-5555,123 No Such St,Fantasyland,CA 99999")); values.add(new Text("A,99.99,01/01/2013")); Text expectedValue = new Text( "Stephanie Leung,555-555-5555,123 No Such St,Fantasyland,CA 99999|A,99.99,01/01/2013"); reduceDriver.withReducer(reducer).withInput(key, values).withOutput(new IntWritable(1), expectedValue) .runTest(); } |
### Question:
Assignment { public long stringToLong(final String s) { final int asciiDecimalStart = 48; final AtomicInteger index = new AtomicInteger(0); final AtomicLong number = new AtomicLong(0); final int len = s.length(); if (s == null || s.isEmpty()) { throw new IllegalArgumentException(s + " can't be converted to a long."); } s.chars().map(i -> (i - asciiDecimalStart)).forEach(i -> { if (i < 0 || i > 9) { throw new IllegalArgumentException(s + " can't be converted to a long."); } number.set((long) (number.get() + i * Math.pow(10, len - index.addAndGet(1)))); }); return number.get(); } long stringToLong(final String s); }### Answer:
@Test public void testStringToLongSuccess() { Assert.assertEquals(123l, assignment.stringToLong("123")); }
@Test(expected = IllegalArgumentException.class) public void testStringToLongFailure() { assignment.stringToLong("12a"); } |
### Question:
Assignment { public String getLongestString(int n, List<String> inputs) { int[] lengths = new int[inputs.size()]; MultiValueMap<Integer, Integer> lengthToIndicesMap = new MultiValueMap<>(); int len = -1; for (int i = 0; i < inputs.size(); i++) { len = inputs.get(i).length(); lengths[i] = len; lengthToIndicesMap.put(len, i); } int maxLen = quickselect(lengths, 0, inputs.size() - 1, n - 1); return inputs.get(lengthToIndicesMap.getCollection(maxLen).iterator().next()); } String getLongestString(int n, List<String> inputs); boolean isPermutationOfEachOther(String s, String t); }### Answer:
@Test public void testGetLongestString() { String[] input = new String[] { "Yuri", "Interview", "Nordstrom", "Cat", "Dog", "Telephone", "AVeryLongString", "This code puzzle is easy" }; Assert.assertEquals("This code puzzle is easy", assignment.getLongestString(1, Arrays.asList(input))); } |
### Question:
Assignment { public boolean isPermutationOfEachOther(String s, String t) { if (s.length() != t.length()) { return false; } return sort(s).equals(sort(t)); } String getLongestString(int n, List<String> inputs); boolean isPermutationOfEachOther(String s, String t); }### Answer:
@Test public void testIsPermutationOfEachOther() { Assert.assertTrue(assignment.isPermutationOfEachOther("abcd", "cdab")); Assert.assertFalse(assignment.isPermutationOfEachOther("abcd", "123")); } |
### Question:
ParkingGarage { public Attendant getAttendant() { return attendant; } ParkingGarage(); Attendant getAttendant(); }### Answer:
@Test public void testParkingOneCompact() { Car compact = new Car(COMPACT, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(compact); assertNotNull(ticket.getId()); assertEquals(COMPACT, ticket.getTypeOfCar()); assertEquals("1", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); }
@Test public void testParkingOneHybrid() { Car hybrid = new Car(HYBRID, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); assertNotNull(ticket.getId()); assertEquals(HYBRID, ticket.getTypeOfCar()); assertEquals("1", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); }
@Test(expected = NoParkingSpaceAvailable.class) public void testParkingOneCompactAndHybrid() { Car compact = new Car(COMPACT, "abc123"); parkingGarage.getAttendant().generateTicketAndOpenGate(compact); Car hybrid = new Car(HYBRID, "abc123"); parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); }
@Test public void testParkingOneSUV() { Car hybrid = new Car(SUV, "abc123"); Ticket ticket = parkingGarage.getAttendant().generateTicketAndOpenGate(hybrid); assertNotNull(ticket.getId()); assertEquals(SUV, ticket.getTypeOfCar()); assertEquals("3", ticket.getLevelId()); Receipt receipt = parkingGarage.getAttendant().acceptPaymentAndOpenGate(ticket, null); verifyReceipt(receipt, ticket); } |
### Question:
MovieServiceImpl implements MovieService { private boolean isParentNotASeries(String parent) { return (parent == null) ? false : parent.trim().matches( ".*(?:\\((\\d{4})\\))$"); } MovieServiceImpl(); @Override SortedSet<Movie> getMovieSet(String path); String getMovieDirectory(); @Override Set<Movie> filterMovieSetByGenre(Set<Movie> movieSet, String genre); @Override Map<String, Set<Movie>> groupMovieSetByGenre(Set<Movie> movieSet); @Override Summary getSummary(Map<String, Set<Movie>> movieSetGroupedByGenre); @SuppressWarnings("unused") @Override GenreSummary getSummaryByGenre(Set<Movie> movieSetFilteredByGenre,
String genre); }### Answer:
@Test public void testIsParentNotASeries() { assertFalse("Testing \"Criminal Minds\"", this.isParentNotASeries("Criminal Minds")); assertFalse("Testing \"\"", this.isParentNotASeries("")); assertFalse("Testing \" \"", this.isParentNotASeries(" ")); assertFalse("Testing null", this.isParentNotASeries(null)); assertTrue("Testing \"Tesis (1996)\"", this.isParentNotASeries("Tesis (1996)")); } |
### Question:
JSONParser { public static Map<String, Employee> employees(String file) throws JsonParseException, JsonMappingException, IOException { final TypeReference<Map<String, Employee>> employeeMapType = new TypeReference<Map<String, Employee>>() { }; return new ObjectMapper().readValue(JSONParser.class.getResource(file), employeeMapType); } static Map<String, Employee> employees(String file); }### Answer:
@Test public void testEmployees() throws JsonParseException, JsonMappingException, IOException { Map<String, Employee> employeeMap = JSONParser.employees("/employees.json"); Assert.assertNotNull(employeeMap); Assert.assertEquals(2, employeeMap.size()); Employee employee123 = employeeMap.get("123"); Assert.assertNotNull(employee123); Assert.assertEquals("Abhijit", employee123.getName()); Assert.assertEquals("Software", employee123.getDepartment()); Employee employee456 = employeeMap.get("456"); Assert.assertNotNull(employee456); Assert.assertEquals("Sarkar", employee456.getName()); Assert.assertEquals("IT", employee456.getDepartment()); } |
### Question:
MovieManager { public static void validateFile(File... files) throws FileNotFoundException { FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter( "Microsoft Excel", "xls", "xlsx"); for (File file : files) { if (file == null) { logger.error("File not found."); throw new FileNotFoundException("File not found."); } else if (!file.isDirectory() && !extensionFilter.accept(file)) { logger.error("File extension is not acceptable: " + file.getAbsolutePath()); throw new IllegalArgumentException( "File extension is not acceptable."); } else if (file.isDirectory() && (!file.canRead() || !file.canExecute())) { logger.error("Directory not found or is not readable: " + file.getAbsolutePath()); throw new IllegalArgumentException( "Directory not found or is not readable."); } } } MovieManager(); MovieManager(File inputDir, File outputFile); static void validateFile(File... files); static GenreSummary getSummaryByGenre(String genre); static Summary getSummary(); static Map<String, Set<Movie>> getMovieSetGroupedByGenre(); static void createSummarySheet(Summary summary); static void createGenreSheet(Set<Movie> filteredMovieSetByGenre,
String genre); static Summary getSummary(
Map<String, Set<Movie>> movieSetGroupedByGenre); static final String EMPTY; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testValidateUnreadableDirectory() throws FileNotFoundException { MovieManager.validateFile(new File("src/test/resources/unreadable")); }
@Test(expected = IllegalArgumentException.class) public void testValidateUnacceptableFileExtension() throws FileNotFoundException { MovieManager.validateFile(new File( "src/test/resources/invalid_extension.txt")); }
@Test public void testValidateGood() { try { MovieManager.validateFile(new File("src/test/resources")); MovieManager.validateFile(new File( "src/test/resources/valid_extension.xlsx")); } catch (Exception ex) { fail("Should not have been here."); } } |
### Question:
Movie implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((name == null) ? 0 : name.hashCode()); result = 37 * result + c; c = (int) year; result = 37 * result + c; c = ((genre == null) ? 0 : genre.hashCode()); result = 37 * result + c; return result; } Movie(); Movie(String name, short year, String fileExtension); Movie(String name, short year, String genre, long filesize,
String fileExtension); String getName(); void setName(String name); short getYear(); void setYear(short year); String getGenre(); void setGenre(String genre); long getFilesize(); void setFilesize(long filesize); String getFileExtension(); void setFileExtension(String fileExtension); String getParent(); void setParent(String parent); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); static final short UNKNOWN_RELEASE_YEAR; static final String UNKNOWN_GENRE; }### Answer:
@Test public void testHashCode() { assertEquals(movie1.hashCode(), movie1.hashCode()); assertEquals(movie1.hashCode(), movie7.hashCode()); assertTrue(movie1.hashCode() != "abc".hashCode()); assertTrue(movie1.hashCode() != movie2.hashCode()); assertTrue(movie1.hashCode() != movie3.hashCode()); assertTrue(movie1.hashCode() != movie4.hashCode()); assertTrue(movie1.hashCode() != movie5.hashCode()); assertTrue(movie1.hashCode() != movie6.hashCode()); } |
### Question:
KeyStoreManager { public static KeyPair getKeyPair(String keystore, String storePassword, String keyPassword, String alias) throws Exception { KeyStore ks = loadKeyStore(keystore, storePassword); Key key = getKey(keystore, storePassword, keyPassword, alias); PublicKey publicKey = null; PrivateKey privateKey = null; key = ks.getKey(alias, keyPassword.toCharArray()); if (key instanceof PrivateKey) { Certificate cert = ks.getCertificate(alias); publicKey = cert.getPublicKey(); privateKey = (PrivateKey) key; return new KeyPair(publicKey, privateKey); } throw new NoSuchKeyException("Alias '" + alias + "' does not exist in keystore '" + keystore + "'."); } static KeyPair getKeyPair(String keystore, String storePassword,
String keyPassword, String alias); static SecretKey getSecKey(String keystore, String storePassword,
String keyPassword, String alias); static KeyInfo createKeyInfo(final XMLSignatureFactory fac,
final String certificateFile); static Certificate getCertificate(final String certificateFile); }### Answer:
@Test public void testPublicKey() { try { KeyPair keyPair = KeyStoreManager.getKeyPair( KeyStoreManagerTest.class.getResource("/" + KEYSTORE) .getPath(), STORE_PASSWORD, KEY_PASSWORD, ALIAS); Assert.assertNotNull("Public Key must not be null", keyPair.getPublic()); Assert.assertNotNull("Private Key must not be null", keyPair.getPrivate()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Shouldn't be here."); } } |
### Question:
GenreSummary implements Serializable { @Override public boolean equals(Object obj) { GenreSummary gs = null; boolean result = false; if (obj == this) { return true; } if (!(obj instanceof GenreSummary)) { return false; } gs = (GenreSummary) obj; result = (genre != null && genre.equals(gs.genre)); result &= (movieTitleCount == gs.movieTitleCount); result &= (soapTitleCount == gs.soapTitleCount); return result; } String getGenre(); void setGenre(String genre); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitlesInThisGenre(); void setSumOfSizeOfAllTitlesInThisGenre(
long sumOfSizeOfAllTitlesInThisGenre); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { assertEquals(genreSummary1, genreSummary1); assertEquals(genreSummary1, genreSummary2); assertFalse(genreSummary1.equals("abc")); assertFalse(genreSummary1.equals(genreSummary3)); assertFalse(genreSummary1.equals(genreSummary4)); assertFalse(genreSummary1.equals(genreSummary5)); assertFalse(genreSummary1.equals(genreSummary6)); } |
### Question:
GenreSummary implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((genre == null) ? 0 : genre.hashCode()); result = 37 * result + c; c = (int) (movieTitleCount); result = 37 * result + c; c = (int) (soapTitleCount); result = 37 * result + c; return result; } String getGenre(); void setGenre(String genre); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitlesInThisGenre(); void setSumOfSizeOfAllTitlesInThisGenre(
long sumOfSizeOfAllTitlesInThisGenre); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { assertEquals(genreSummary1.hashCode(), genreSummary1.hashCode()); assertEquals(genreSummary1.hashCode(), genreSummary2.hashCode()); assertTrue(genreSummary1.hashCode() != "abc".hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary3.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary4.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary5.hashCode()); assertTrue(genreSummary1.hashCode() != genreSummary6.hashCode()); } |
### Question:
Summary implements Serializable { @Override public boolean equals(Object obj) { Summary s = null; if (obj == this) { return true; } if (!(obj instanceof Summary)) { return false; } s = (Summary) obj; return ((genreSummary == s.genreSummary) || (genreSummary != null && genreSummary .equals(s.genreSummary))); } List<GenreSummary> getGenreSummary(); void setGenreSummary(List<GenreSummary> genreSummary); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitles(); void setSumOfSizeOfAllTitles(long sumOfSizeOfAllTitles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { assertEquals(summary1, summary1); assertEquals(summary2, summary2); assertEquals(summary2, summary3); assertFalse(summary2.equals("abc")); assertFalse(summary2.equals(summary4)); assertFalse(summary2.equals(summary5)); assertFalse(summary2.equals(summary6)); assertFalse(summary2.equals(summary7)); } |
### Question:
Summary implements Serializable { @Override public int hashCode() { int result = 17; int c = 0; c = ((genreSummary == null) ? 0 : genreSummary.hashCode()); result = 37 * result + c; return result; } List<GenreSummary> getGenreSummary(); void setGenreSummary(List<GenreSummary> genreSummary); int getMovieTitleCount(); void setMovieTitleCount(int movieTitleCount); int getSoapTitleCount(); void setSoapTitleCount(int soapTitleCount); long getSumOfSizeOfAllTitles(); void setSumOfSizeOfAllTitles(long sumOfSizeOfAllTitles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { assertEquals(summary1.hashCode(), summary1.hashCode()); assertEquals(summary2.hashCode(), summary2.hashCode()); assertEquals(summary2.hashCode(), summary3.hashCode()); assertTrue(summary2.hashCode() != "abc".hashCode()); assertTrue(summary2.hashCode() != summary4.hashCode()); assertTrue(summary2.hashCode() != summary5.hashCode()); assertTrue(summary2.hashCode() != summary6.hashCode()); assertTrue(summary2.hashCode() != summary7.hashCode()); } |
### Question:
XMLEncryptor { public void encrypt(String inputFile, String outputFile) throws Exception { File ipFile = new File(inputFile); File opFile = new File(outputFile); SecurityUtil.print(ipFile); encMgr.encrypt(ipFile, opFile); SecurityUtil.print(opFile); } void encrypt(String inputFile, String outputFile); void decrypt(String inputFile); }### Answer:
@Test public void testEncrypt() throws Exception { String inputFile = XMLEncryptorTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; XMLEncryptor.encrypt(inputFile, outputFile); } |
### Question:
Validator { public static void validate(final String romanNumber) { if (romanNumber == null || romanNumber.trim().length() == 0) { throw new IllegalArgumentException(romanNumber + " is not a valid Roman number."); } final int len = romanNumber.length(); char currentChar = '\u0000'; for (int index = 0; index < len; index++) { currentChar = Character.toUpperCase(romanNumber.charAt(index)); if (romanNumber.toUpperCase().matches( Character.toUpperCase(currentChar) + "{" + (repeatMap.get(currentChar) + 1) + ",}")) { throw new IllegalArgumentException(currentChar + " can not be repeated more than " + repeatMap.get(currentChar) + " times in succession."); } } } static void validate(final String romanNumber); static final Map<Character, Integer> repeatMap; }### Answer:
@Test public void testValidNumber1() { Validator.validate("III"); }
@Test public void testValidNumber2() { Validator.validate("XXX"); }
@Test public void testValidNumber3() { Validator.validate("IIIX"); }
@Test public void testValidNumber4() { Validator.validate("XXXIX"); }
@Test public void testValidNumber5() { Validator.validate("IV"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber1() { Validator.validate("IIII"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber2() { Validator.validate("MMMM"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidNumber3() { Validator.validate("DD"); } |
### Question:
XMLEncryptor { public void decrypt(String inputFile) throws Exception { File ipFile = new File(inputFile); SecurityUtil.print(ipFile); encMgr.decrypt(ipFile); } void encrypt(String inputFile, String outputFile); void decrypt(String inputFile); }### Answer:
@Test public void testDecrypt() throws Exception { String inputFile = XMLEncryptorTest.class.getResource("/" + INPUT_FILE) .getPath(); String outputFile = new File(inputFile).getParent() + File.separator + OUTPUT_FILE; XMLEncryptor.decrypt(outputFile); } |
### Question:
Strings { public static String camelToUnderscore(final String input) { String result = input; if (input instanceof String) { result = input.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase(); } return result; } static String camelToUnderscore(final String input); static String join(final String delim, final String... strings); static String canonicalize(final String name); }### Answer:
@Test public void testCamelToUnderscore() { String input = "myCamelCaseTest"; String expected = "my_camel_case_test"; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); }
@Test public void testCamelToUnderscoreSucceedsOnEmptyString() throws Exception { String input = ""; String expected = ""; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); }
@Test public void testCamelToUnderscorePassesThroughNull() throws Exception { String input = null; String output = Strings.camelToUnderscore(input); assertEquals(input, output); }
@Test public void testCamelToUnderscoreConvertsConsecutiveCapitalsToLowercase() throws Exception { String input = "mySQLTest"; String expected = "my_sqltest"; String actual = Strings.camelToUnderscore(input); assertEquals(expected, actual); } |
### Question:
StringValidations { public static boolean isAlphanumeric(final String textWithDigits) { if (textWithDigits != null) { return textWithDigits.matches("^[a-zA-Z\\d]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsAlphaNumericReturnsTrueForAlphanumericInput() { assertTrue(StringValidations.isAlphanumeric("T3st")); }
@Test public void testIsAlphaNumericReturnsTrueForAlphabeticInput() { assertTrue(StringValidations.isAlphanumeric("Test")); }
@Test public void testIsAlphaNumericReturnsFalseForSpecialChar() { assertFalse(StringValidations.isAlphanumeric("@#3st!")); } |
### Question:
StringValidations { public static boolean isEmptyString(final String text) { if (text != null) { return text.matches(""); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsEmptyStringReturnsTrueForEmptyString() { assertTrue(StringValidations.isEmptyString("")); }
@Test public void testIsEmptyStringReturnsFalseForNonEmptyString() { assertFalse(StringValidations.isEmptyString("asdWsonciw aski")); }
@Test public void testIsEmptyStringReturnsFalseForSpecialChar() { assertFalse(StringValidations.isEmptyString("@#3st!")); } |
### Question:
StringValidations { public static boolean isPunctuatedText(final String text) { if (text != null) { return text.matches("^[a-zA-Z/\\d\\s._?!,;':\"~`$%&()+=\\[\\]-]*$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsPunctuatedTextReturnsTrueForAlphabeticOnly() { assertTrue(StringValidations.isPunctuatedText("This is a test")); }
@Test public void testIsPunctuatedTextReturnsTrueForTextWithPunctuation() { assertTrue(StringValidations.isPunctuatedText(",./?;':\"~`!$%&()-_+=[]")); }
@Test public void testIsPunctuatedTextReturnsTrueForTextWithSingleQuote() { assertTrue(StringValidations.isPunctuatedText("Quote's test")); }
@Test public void testIsPunctuatedTextReturnsFalseForGreaterThanOrLessThan() { assertFalse(StringValidations.isPunctuatedText("BAD<Name>")); } |
### Question:
StringValidations { public static boolean isDigit(final String digit) { if (digit != null) { return digit.matches("^\\d$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsDigitReturnsTrueForSingleDigit() { assertTrue(StringValidations.isDigit("4")); }
@Test public void testIsDigitReturnsFalseForMultipleDigit() { assertFalse(StringValidations.isDigit("43")); }
@Test public void testIsDigitReturnsFalseForNumberWithDecimalPoint() { assertFalse(StringValidations.isDigit("4.0")); }
@Test public void testIsDigitReturnsFalseForInputWithAlphabeticAndSpecial() { assertFalse(StringValidations.isDigit("ia*")); } |
### Question:
StringValidations { public static boolean isEmailAddress(final String email) { if (email != null) { return email.matches("^" + EMAIL_REGEX + "$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsEmailAddressReturnsTrueForValidEmail() { assertTrue(StringValidations.isEmailAddress("[email protected]")); }
@Test public void testIsEmailAddressReturnsTrueForValidEmailUppercase() { assertTrue(StringValidations.isEmailAddress("[email protected]")); }
@Test public void testIsEmailAddressReturnsFalseForInvalidEmail() { assertFalse(StringValidations.isEmailAddress("..com")); }
@Test public void testIsEmailAddressReturnsTrueForValidEmail2() { assertTrue(StringValidations.isEmailAddress("[email protected]")); } |
### Question:
StringValidations { public static boolean isZipCode(final String zipCode) { if (zipCode != null) { return zipCode.matches("\\d{5}((-| +)\\d{4})?$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsZipCodeReturnsTrueForShortZip() { assertTrue(StringValidations.isZipCode("28212")); }
@Test public void testIsZipCodeReturnsTrueForLongZip() { assertTrue(StringValidations.isZipCode("78415 0158")); }
@Test public void testIsZipCodeReturnsFalseForBadZip() { assertFalse(StringValidations.isZipCode("75126=0465")); }
@Test public void testIsZipCodeReturnsFalseForBadZipAlphabetic() { assertFalse(StringValidations.isZipCode("7pe26=0A65")); } |
### Question:
StringValidations { public static boolean isPhoneNumber(final String phoneNumber) { if (phoneNumber != null) { return phoneNumber.matches("^(?:\\([2-9]\\d{2}\\)\\ ?|[2-9]\\d{2}(?:\\-?|\\ ?))[2-9]\\d{2}[- ]?\\d{4}$"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsPhoneNumberReturnsTruePhoneNumberWithSpecialChars() { assertTrue(StringValidations.isPhoneNumber("(704)546-7542")); }
@Test public void testIsPhoneNumberReturnsTrueWithoutSpecialChars() { assertTrue(StringValidations.isPhoneNumber("5038751238")); }
@Test public void testIsPhoneNumberReturnsFalseInvalidInputShortLenght() { assertFalse(StringValidations.isPhoneNumber("555555")); }
@Test public void testIsPhoneNumberReturnsFalseInvalidInput() { assertFalse(StringValidations.isPhoneNumber("(8e074d/874")); } |
### Question:
Strings { public static String canonicalize(final String name) { String result = null; if (name != null) { result = name.toLowerCase().replace(' ', '-').replaceAll("[^a-z0-9-]*", "").replaceAll("-+", "-"); } return result; } static String camelToUnderscore(final String input); static String join(final String delim, final String... strings); static String canonicalize(final String name); }### Answer:
@Test public void testCanonicalize() { String input = "Project#$% Name"; String expected = "project-name"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); }
@Test public void testCanonicalizeStripsExtraDashes() { String input = "Project#$%--- Name"; String expected = "project-name"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); }
@Test public void testCanonicalizeLeavesDigits() { String input = "Project#$%--- Name99"; String expected = "project-name99"; String actual = Strings.canonicalize(input); assertEquals(expected, actual); } |
### Question:
StringValidations { public static boolean hasData(final String value) { return (value != null) && (value.length() > 0) && value.matches(".*\\S.*"); } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testHasDataReturnsTrueWithData() throws Exception { assertTrue(StringValidations.hasData("Yes")); }
@Test public void testHasDataReturnsFalseWithNullValue() throws Exception { assertFalse(StringValidations.hasData(null)); }
@Test public void testHasDataReturnsFalseWithEmptyString() throws Exception { assertFalse(StringValidations.hasData("")); } |
### Question:
StringValidations { public static boolean isWholeNumber(final String number) { if (number != null) { return number.matches("[0-9]+"); } return false; } static boolean isAlphabetic(final String text); static boolean isAlphanumeric(final String textWithDigits); static boolean isAlphanumericDash(String text); static boolean isAlphanumericSpaceUnderscore(final String textWithDigits); static boolean isEmptyString(final String text); static boolean isPunctuatedText(final String text); static boolean isPunctuatedTextWithoutSpace(final String text); static boolean isDecimal(final String number); static boolean isWholeNumber(final String number); static boolean isDigit(final String digit); static boolean isEmailAddress(final String email); static boolean isState(final String state); static boolean isZipCode(final String zipCode); static boolean isPhoneNumber(final String phoneNumber); static boolean isPassword(final String password); static boolean isStrictPassword(final String password); static boolean hasData(final String value); static boolean length(final int length, final String value); static boolean minLength(final int length, final String value); static boolean maxLength(final int length, final String value); static final String EMAIL_REGEX; }### Answer:
@Test public void testIsWholeNumberReturnsTrueForValidInput() throws Exception { assertTrue(StringValidations.isWholeNumber("5")); }
@Test public void testIsWholeNumberReturnsFalseForAlphabeticInput() throws Exception { assertFalse(StringValidations.isWholeNumber("as")); }
@Test public void testIsWholeNumberReturnsFalseForNoInput() throws Exception { assertFalse(StringValidations.isWholeNumber("")); }
@Test public void testIsWholeNumberReturnsFalseForDecimalInput() throws Exception { assertFalse(StringValidations.isWholeNumber("12.1234")); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.