package com.tutego.insel.solutions.lang;

class CollatzFolge
{
  public static void main( String args[] )
  {
    simpleCollatz1( 7 );
    simpleCollatz2( 7 );

    collatzMax( 100, 200 );

    collatzGreater( 100 );

    collatzMinDist( 100 );
  }

  static void simpleCollatz1( int n )
  {
    System.out.print( n + " -> " );

    while ( n > 1 )
    {
      if ( n % 2 == 0 )
        n /= 2;
      else
        n = 3*n+1;

      System.out.print( n + " -> " );
    }
    System.out.println();
  }

  static void simpleCollatz2( int n )
  {
    int max = 0, it = 0;

    while ( n > 1 )
    {
      max = Math.max( max, n = (n % 2 == 0 ) ? n/2 : 3*n+1 );
      it++;
    }

    System.out.println( "Größte zwischendurch erreichte Zahl: " + max );
    System.out.println( "Anzahl der Iterationen: "+ it );
  }

  static long iterate( int n )
  {
    long max = 0;

    while ( n > 1 )
      max = Math.max( max, n = (n % 2 == 0 ) ? n/2 : 3*n+1 );

    return max;
  }

  static void collatzMax( int start, int end )
  {
    long max = 0;

    for ( int i = start; i <= end; i++ )
      max = Math.max( max, iterate(i) );

    System.out.println( "Größte zwischendurch erreichte Zahl von n=100...200: " + max );
  }

  static void collatzGreater( int end )
  {
    long max;

    for ( int cnt = 0, found = 0; found <= end; cnt++ )
      if ( (max=iterate(cnt)) > cnt )
      {
        System.out.println( "Max in Folge " + max + " ist echt größer als " + cnt );
        found++;
      }
  }

  static void collatzMinDist( int end )
  {
    long max, max2=0, maxElement=0;

    for ( int n = 0, found = 0; found <= end; n++ )
      if ( (max=iterate(n)) > n )
      {
        if ( max2 < max-n )
        {
          max2 = max - n;
          maxElement = n;
        }
        found++;
      }

    System.out.println( maxElement + " liefert größten Abstand " + max2 );
  }
}
