Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | C # program for the above approach ; 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 ; Driver Code ; Frequency of all elements from 0 to n - 1 ; Number of elements whose frequencies are given ; Function call
using System ; using System . Collections . Generic ; class GFG { static List < int > generateSequence ( int [ ] freq , int n ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; int total = 0 ; for ( int i = 0 ; i < n ; i ++ ) { m . Add ( i , freq [ i ] ) ; total += freq [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( i ) ) { List < int > sequence = new List < int > ( ) ; Dictionary < int , int > mcopy = new Dictionary < int , int > ( m ) ; if ( mcopy . ContainsKey ( i ) && mcopy [ i ] > 0 ) mcopy [ i ] = mcopy [ i ] - 1 ; sequence . Add ( i ) ; int last = i ; for ( int i1 = 0 ; i1 < total - 1 ; i1 ++ ) { if ( mcopy . ContainsKey ( last - 1 ) && mcopy [ last - 1 ] > 0 ) { mcopy [ last - 1 ] = mcopy [ last - 1 ] - 1 ; sequence . Add ( last - 1 ) ; last -- ; } else if ( mcopy . ContainsKey ( last + 1 ) ) { mcopy [ last + 1 ] = mcopy [ last + 1 ] - 1 ; sequence . Add ( last + 1 ) ; last ++ ; } else break ; } if ( sequence . Count == total ) { return sequence ; } } } List < int > empty = new List < int > ( ) ; return empty ; } static void PrintSequence ( int [ ] freq , int n ) { List < int > sequence = generateSequence ( freq , n ) ; if ( sequence . Count == 0 ) { Console . Write ( " - 1" ) ; } else { for ( int i = 0 ; i < sequence . Count ; i ++ ) { Console . Write ( sequence [ i ] + " ▁ " ) ; } } } public static void Main ( String [ ] args ) { int [ ] freq = { 2 , 2 , 2 , 3 , 1 } ; int N = 5 ; PrintSequence ( freq , N ) ; } }