New Year Chaos

  • + 0 comments

    My answer with Typescript, idea & explain includes.

    function minimumBribes(q: number[]): void {
        /**
         * Idea: Reverse thinking, complete the numbers behind first, count the number 
         * of permutations of the argument.
         */
    
        // 0. fn that swap number in array
        const swap = (s: number[], i: number) => { [s[i], s[i + 1]] = [s[i + 1], s[i]] }
    
        // 1. create fresh new array to be start, a hash to couting swaped
        let s = Array(q.length).fill(0).map((_, i) => i + 1)
        let swap_count = new Map<number, number>()
    
        // 2. loop [q], find and swap to complete right side to left side, counting too.
        mainloop: for (let qi = q.length - 1; qi >= 0; qi--) {
            while (true) {
                let si = s.indexOf(q[qi])
                if (si < qi) {
                    let swap_num = s[si + 1]
    
                    swap(s, si)
                    swap_count.set(swap_num, (swap_count.get(swap_num) || 0) + 1)
                    continue
                }
                break;
            }
        }
    
        // 3. calc swaping is chaos or not
        let counts = Array.from(swap_count.values())
        let chaos = counts.some(e => e > 2)
        let sum = counts.reduce((p, v) => p + v, 0)
    
        if (chaos) console.log('Too chaotic')
        else console.log(sum)
    }