Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualDARSC0D3

Posted 11 October 2012 - 04:33 AM

This version is slightly more elegant:

import java.util.Random;

public class flip {
		static Random random_generator;
		
		static void flip_coin(int repeat) {
				if ( repeat > 0) {
					double random_number = random_generator.nextDouble();
					System.out.println(random_number);
					
					if (random_number < 0.5)
						System.out.println("head");
					else
						System.out.println("tail");

					flip_coin(repeat-1); // <-- This is the only change
				}
		}
		
		public static void main (String[] args) {
				random_generator = new Random();
				flip_coin(10);
		}
}


From a performance point of view a function call is more expensive than a comprising.
This piece of code will cause every run to have an additional function call to flip_coin with no result.
As why there is a guard condition on top this is only because if you would be silly enough to provide any value less than 1 it would just skip the function.

Less LOC's (Lines Of Code) doesn't mean it is more elegant just remember that.

#1DARSC0D3

Posted 11 October 2012 - 04:33 AM

This version is slightly more elegant:

import java.util.Random;

public class flip {
		static Random random_generator;
		
		static void flip_coin(int repeat) {
				if ( repeat > 0) {
					double random_number = random_generator.nextDouble();
					System.out.println(random_number);
					
					if (random_number < 0.5)
						System.out.println("head");
					else
						System.out.println("tail");

					flip_coin(repeat-1); // <-- This is the only change
				}
		}
		
		public static void main (String[] args) {
				random_generator = new Random();
				flip_coin(10);
		}
}


From a performance point of view a function call is more expensive than a comprising.
This piece of code will cause every run to have an additional function call to flip_coin with no result.
As why there is a guard condition on top is only because if you would be silly enough to provide any value less than 1 it would just skip the function.

Less LOC's (Lines Of Code) doesn't mean it is more elegant just remember that.

PARTNERS