Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | Function generates the sequence ; Map to store the frequency of numbers ; Sum of all frequencies ; Try all possibilities for the starting element ; If the frequency of current element is non - zero ; vector to store the answer ; Copy of the map for every possible starting element ; Decrement the frequency ; Push the starting element to the vector ; The last element inserted is i ; Try to fill the rest of the positions if possible ; If the frequency of last - 1 is non - zero ; Decrement the frequency of last - 1 ; Insert it into the sequence ; Update last number added to sequence ; Break from the inner loop ; If the size of the sequence vector is equal to sum of total frequqncies ; Return sequence ; If no such sequence if found return empty sequence ; Function call to print the sequence ; The required sequence ; If the size of sequence if zero it means no such sequence was found ; Otherwise print the sequence ; Frequency of all elements from 0 to n - 1 ; Number of elements whose frequencies are given ; Function call
function generateSequence ( freq , n ) { let m = new Map ( ) ; let total = 0 ; for ( let i = 0 ; i < n ; i ++ ) { m . set ( i , freq [ i ] ) ; total += freq [ i ] ; } for ( let i = 0 ; i < n ; i ++ ) { if ( m . has ( i ) ) { let sequence = [ ] ; let mcopy = new Map ( ) ; for ( let [ key , value ] of m . entries ( ) ) { mcopy . set ( key , value ) ; } if ( mcopy . has ( i ) && mcopy . get ( i ) > 0 ) mcopy . set ( i , mcopy . get ( i ) - 1 ) ; sequence . push ( i ) ; let last = i ; for ( let i1 = 0 ; i1 < total - 1 ; i1 ++ ) { if ( mcopy . has ( last - 1 ) && mcopy . get ( last - 1 ) > 0 ) { mcopy . set ( last - 1 , mcopy . get ( last - 1 ) - 1 ) ; sequence . push ( last - 1 ) ; last -- ; } else if ( mcopy . has ( last + 1 ) ) { mcopy . set ( last + 1 , mcopy . get ( last + 1 ) - 1 ) ; sequence . push ( last + 1 ) ; last ++ ; } else break ; } if ( sequence . length == total ) { return sequence ; } } } let empty = [ ] ; return empty ; } function PrintSequence ( freq , n ) { let sequence = generateSequence ( freq , n ) ; if ( sequence . length == 0 ) { document . write ( " " ) ; } else { for ( let i = 0 ; i < sequence . length ; i ++ ) { document . write ( sequence [ i ] + " " ) ; } } } let freq = [ 2 , 2 , 2 , 3 , 1 ] ; let N = 5 ; PrintSequence ( freq , N ) ;