Move History

Fork Selected
  • Description

    Given an array containing only 0s, 1s, and 2s; sort the array in ascending order.

    Code
    from __future__ import annotations
    from collections import Counter
    
    def sort_values(vals:list[int]) -> list[int]:
        #Given an array of size N containing only 0s, 1s, and 2s; 
        #sort the array in ascending order.
        assert set(vals) <= {0,1,2}
        return counting_sort(vals)
        # O(n+k) instead of n log(n)
    
    def counting_sort(vals:list[T]) -> list[T]:
        res = []
        c = Counter(vals)
        for k,amt in sorted(c.items()):
            res += [k]*amt
        return res
    Test Cases
    test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2]  )
    test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
    
    
  • Code
    • import java.util.Arrays;
    • public class Kata {
    • public static int[] sortValues(int[] my_array, int size) {
    • // Given an array of size N containing only 0s, 1s, and 2s;
    • // sort the array in ascending order.
    • Arrays.sort(my_array);
    • return my_array;
    • }
    • }
    • from __future__ import annotations
    • from collections import Counter
    • def sort_values(vals:list[int]) -> list[int]:
    • #Given an array of size N containing only 0s, 1s, and 2s;
    • #sort the array in ascending order.
    • assert set(vals) <= {0,1,2}
    • return counting_sort(vals)
    • # O(n+k) instead of n log(n)
    • def counting_sort(vals:list[T]) -> list[T]:
    • res = []
    • c = Counter(vals)
    • for k,amt in sorted(c.items()):
    • res += [k]*amt
    • return res
    Test Cases
    • import org.junit.jupiter.api.Test;
    • import static org.junit.jupiter.api.Assertions.assertArrayEquals;
    • test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2] )
    • test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
    • // TODO: Replace examples and use TDD by writing your own tests
    • class SolutionTest {
    • @Test
    • void testSomething() {
    • int[] inputArray = {0,0,2,0,1,1,2,0};
    • int[] expectedArray = {0,0,0,0,1,1,2,2};
    • assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));
    • }
    • @Test
    • void testSomethingElse() {
    • int[] inputArray = {2, 0, 1, 2};
    • int[] expectedArray = {0, 1, 2, 2};
    • assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));
    • }
    • }