Lily's Homework

  • + 0 comments

    Java 8 - used stream to create a set if index that are sorted.

    public static int lilysHomework(List<Integer> arr) {
            // The key to solving this problem is to create a sorted indexs
            // and count the number of the swaps it takes to get things
            // in the corrector order.
            List<Integer> indicesAssending = IntStream.range(0, arr.size())
                .boxed()
                .sorted(Comparator.comparingInt(i -> arr.get(i)))
                .collect(Collectors.toList()) ;
                
            List<Integer> indicesDesending = indicesAssending.stream()
                .collect(Collectors.toList());
            Collections.reverse(indicesDesending);
            
            int resultAssending = swapToOrder(indicesAssending);
            int resultDesending = swapToOrder(indicesDesending);
            
            return Math.min(resultAssending, resultDesending);
        }
        
        /** Swap each sorted indice into it proper location **/
        private static int swapToOrder(List<Integer> indices) {
            int result = 0 ;
            
            for (int i=0; i<indices.size();) {
                if (i != indices.get(i).intValue() ) {
                    ++result;
                    swap(indices, i, indices.get(i)) ;
                } else {
                    ++i;
                }            
            }
            return result;
        }
        
        /** Simple swaping of two indices values**/
        private static void swap(List<Integer> arr, int i1, int i2) {
            Integer v1 = arr.get(i1);
            arr.set(i1, arr.get(i2));
            arr.set(i2, v1); 
        }