Tuesday, February 28, 2017

Java Programming: Different ways to reverse a String


When I was still looking for a job, I noticed that most job programming exams will have at least one or two questions about string manipulation in Java. Reversing a string is one of the most common questions I encountered about string manipulation. You might think, “Oh, it’s just easy! I’ll just use the Java’s built-in API for string reversion”. Unfortunately, you will be asked to reverse a string without using the built-in API, either using iteration or recursive method. I suggest that you get familiar with either of those methods if you want to show your future employer that if there’s no API available, then you can always write your own implementation.

Without further ado, here are the different ways to reverse a string in Java.


public class StringReverseDemo {

     public static void main(String[] args){
         // Original string
         String origStr = "What a wonderful day today";
         System.out.println("Original string: " + origStr);
         
         String reversedStr;
         
         // Reverse a string using StringBuilder
         reversedStr = new StringBuilder(origStr).reverse().toString();
         System.out.println("Reverse a string using StringBuilder: " + reversedStr);
         
         // Reverse a string using iteration method
         reversedStr = reverseUsingIteration(origStr);
         System.out.println("Reverse a string using iteration method: " + reversedStr);
         
         // Reverse a string using recursive method
         reversedStr = reverseStringRecursively(origStr);
         System.out.println("Reverse a string using recursive method: " + reversedStr);
     }
     
     public static String reverseUsingIteration(String str) {
         StringBuilder builder = new StringBuilder();
         char[] strChars = str.toCharArray();
         
         for (int i = strChars.length - 1; i >= 0; i--) {
             builder.append(strChars[i]);
         }
         
         return builder.toString();
     }
     
     public static String reverseStringRecursively(String str) {
         // This condition handles one character string and empty string
         if (str.length() < 2) {
             return str;
         }
         
         return reverseStringRecursively(str.substring(1)) + str.charAt(0);
     }
}

Output

Original string: What a wonderful day today                                                          
Reverse a string using StringBuilder: yadot yad lufrednow a tahW                                     
Reverse a string using iteration method: yadot yad lufrednow a tahW                                  
Reverse a string using recursive method: yadot yad lufrednow a tahW

Monday, February 20, 2017

Java Programming: Generating random numbers using Math.random()


If you’re working on a program or a game that relies on generating random numbers (e.g. throwing dice can have possible values of 1 to 6), then you can use Java’s built-in function Math.random(). This method returns a pseudorandom positive double number greater than or equal to 0.0 and less than 1.0 (inclusive of 0 but exclusive of 1).

The following example will show the different usage of Math.random().

Example
public class MathRandomDemo {

     public static void main(String[] args){
         
         // Generate random double number between 0.0 (inclusive) and 1.0 (exclusive)
         double x = Math.random();
         System.out.println("Random double number between 0.0 (inclusive) and 1.0 (exclusive): " + x);
         
         // Generate random double number between 0.0 (inclusive) and 10.0 (exclusive)
         double y = Math.random() * 10.0;
         System.out.println("Random double number between 0.0 (inclusive) and 10.0 (exclusive): " + y);
         
         // Generate random integer number between 1 (inclusive) and 6 (inclusive)
         int z = (int) (Math.random() * 6) + 1;
         System.out.println("Random integer number between 1 (inclusive) and 6 (inclusive): " + z);
     }
}

Output

Random double number between 0.0 (inclusive) and 1.0 (exclusive): 0.340407647793009
Random double number between 0.0 (inclusive) and 10.0 (exclusive): 9.048673266441012
Random integer number between 1 (inclusive) and 6 (inclusive): 3

In the example above, if you want to generate a double value greater than or equal to 0.0 but less than 10.0, then you just need to multiply the result of Math.random() with 10.0. This will return random numbers from 0.0 to 9.99. If you want to include 10.0 on the results, then you need to multiply Math.random() with 11.0 instead.

Let’s say you want to specify a minimum and maximum range to the generated random number, then all you have to do is to multiply Math.random() with the maximum value and add the minimum value to its result. In the example above, the minimum value is 1 and maximum value is 6, so we simply do (Math.random() * 6) + 1 to generate numbers from 1 to 6.

Since Math.random() returns a double value, you can cast its result to int if you want to return integer values.