Golomb Sequence | Set 2 | Java program to find the first N terms of Golomb Sequence ; Function to print the Golomb Sequence ; Initialise the array ; Initialise the cnt to 0 ; First and second element of Golomb Sequence is 0 , 1 ; Map to store the count of current element in Golomb Sequence ; Store the count of 2 ; Iterate over 2 to N ; If cnt is equals to 0 then we have new number for Golomb Sequence 1 2 2 3 3 4 4 4 5 5 5 which is 1 + previous element ; Else the current element is the previous element in this Sequence ; Map the current index to current value in arr [ ] ; Print the Golomb Sequence ; Driver Code
import java . util . * ; class GFG { static int MAX = 1000 ; static void printGolombSequence ( int N ) { int [ ] arr = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) arr [ i ] = 0 ; int cnt = 0 ; arr [ 0 ] = 0 ; arr [ 1 ] = 1 ; Map < Integer , Integer > M = new HashMap < Integer , Integer > ( ) ; M . put ( 2 , 2 ) ; for ( int i = 2 ; i <= N ; i ++ ) { if ( cnt == 0 ) { arr [ i ] = 1 + arr [ i - 1 ] ; cnt = M . get ( arr [ i ] ) ; cnt -- ; } else { arr [ i ] = arr [ i - 1 ] ; cnt -- ; } M . put ( i , arr [ i ] ) ; } for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int N = 11 ; printGolombSequence ( N ) ; } }