Given 1 ' s , ▁ 2' s , 3 ' s ▁ . . . . . . k ' s print them in zig zag way . | function that prints given number of 1 ' s , ▁ ▁ 2' s , 3 ' s ▁ . . . . k ' s in zig - zag way . ; two - dimensional array to store numbers . ; for even row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index ; for odd row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index . ; printing the stored elements . ; Driver Code
function ZigZag ( rows , columns , numbers ) { let k = 0 ; let arr = new Array ( rows ) ; for ( let i = 0 ; i < rows ; i ++ ) { arr [ i ] = new Array ( rows ) ; for ( let j = 0 ; j < columns ; j ++ ) { arr [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < rows ; i ++ ) { if ( i % 2 == 0 ) { for ( let j = 0 ; j < columns && numbers [ k ] > 0 ; j ++ ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } else { for ( let j = columns - 1 ; j >= 0 && numbers [ k ] > 0 ; j -- ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } } for ( let i = 0 ; i < rows ; i ++ ) { for ( let j = 0 ; j < columns ; j ++ ) document . write ( arr [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } let rows = 4 ; let columns = 5 ; let Numbers = [ 3 , 4 , 2 , 2 , 3 , 1 , 5 ] ; ZigZag ( rows , columns , Numbers ) ;