Counting Characters and Permutations of Arrays

I just finished the “Basic” Java exercises at w3resource.com today and made the last two — #38 and #39 — a bit harder than they needed to be. #38 asks for you to “write a Java program to count the letters, spaces, numbers and other characters of an input string”. I interpreted this to mean each individual character, for instance, how many “h” or “L” or whatever. The solution suggests the use of Character.isLetter(), Character.isDigit(), and Character.isSpaceChar(), but I like my way better anyway:

import java.util.Scanner;

public class Exercise38 {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a line of text: ");
    String userLine = in.nextLine();

    char[] userChars = userLine.toCharArray();
    int len = userLine.length();
    int[] charFrequency = new int[len];

    boolean counted = false;

    for(int ii = 0; ii < len; ++ii){
      for(int jj = 0; jj < ii; ++jj){
        counted = false;
        if(userChars[ii]==userChars[jj]){
          charFrequency[jj]++;
          counted = true;
          break;
        }
      }
      if(!counted){
        charFrequency[ii]++;
      }
    }

    System.out.format("In your string: \n\t\"%s\"\nthere were...\n", userLine);

    for(int ii = 0; ii < len; ++ii){       if(charFrequency[ii] > 0){
        System.out.format("\t%d \'%c\' character(s)\n", charFrequency[ii], userChars[ii]);
      }
    }

    return;
  }
}

This above code will count each individual character in a user-inputted String. Below is some sample output:

15:14 |aww@airy Basic| javac Exercise38.java; java Exercise38
Enter a line of text:
This is a line of text
In your string:
	"This is a line of text"
there were...
	1 'T' character(s)
	1 'h' character(s)
	3 'i' character(s)
	2 's' character(s)
	5 ' ' character(s)
	1 'a' character(s)
	1 'l' character(s)
	1 'n' character(s)
	2 'e' character(s)
	1 'o' character(s)
	1 'f' character(s)
	2 't' character(s)
	1 'x' character(s)

The second Exercise with instructions which I misinterpreted was Exercise 39. This one asks you to “write a Java program to create and display unique three-digit number using 1, 2, 3, 4. Also count how many three-digit numbers are there.” I assumed that this wasn’t meant to be hard-coded. That any numbers should be able to be used. I also expanded the code to allow arrays of any length. In essence, what I wrote was a Java program which gives all of the permutations of an array of numbers:

public class Exercise39 {
  public static void main(String[] args){

    int[] testArray = { 7, 3, 2 };
    printArray(permuteIntegerArray(testArray));

    return;
  }

  public static void printArray(int[][] printMe){
    int nRows = printMe.length;
    int nCols = printMe[0].length;

    System.out.print("\n");
    for(int ii = 0; ii < nRows; ++ii){
      System.out.format("%d\t : ", ii+1);
      for(int jj = 0; jj < nCols; ++jj){
        System.out.print(printMe[ii][jj] + " ");
      }
      System.out.print("\n");
    }
  }

  public static int[][] permuteIntegerArray(int[] array){
    int n = array.length;
    int nFactorial = integerFactorial(n);
    int nMinus1Factorial = integerFactorial(n-1);
    int[][] permuted = new int[nFactorial][n];

    if(n==1){
      permuted[0][0] = array[0];
      return permuted;
    } else if(n==2){
      permuted[0][0] = array[0];
      permuted[0][1] = array[1];
      permuted[1][0] = array[1];
      permuted[1][1] = array[0];
      return permuted;
    } else {
      int[][] smallerPermuted = new int[nMinus1Factorial][n-1];
      int[]   smallerArray    = new int[n-1];
      int counter = 0;
      for(int ii = 0; ii < n; ++ii){
        for(int jj = ii*nMinus1Factorial; jj < (ii+1)*nMinus1Factorial; ++jj){
          permuted[jj][0] = array[ii];
        }
        counter = 0;
        for(int jj = 0; jj < n; ++jj){
          if(ii==jj) continue;
          smallerArray[counter] = array[jj];
          counter++;
        }
        smallerPermuted = permuteIntegerArray(smallerArray);

        for(int jj = 0; jj < nMinus1Factorial; ++jj){
          for(int kk = 0; kk < n-1; ++kk){             permuted[jj+ii*nMinus1Factorial][kk+1] = smallerPermuted[jj][kk];     } } } }     return permuted;   }   public static int integerFactorial(int base){     int returnValue = base;     while(base > 2){
      base--;
      returnValue *= base;
    }
    return returnValue;
  }
}

This is arguably much cooler than the example solution, though it is a bit long. I feel as though it can be shortened — any suggestions would be appreciated! Sample output below:

15:25 |aww@airy Basic| javac Exercise39.java; java Exercise39

1	 : 7 3 2
2	 : 7 2 3
3	 : 3 7 2
4	 : 3 2 7
5	 : 2 7 3
6	 : 2 3 7
Advertisements

Get a character from its Unicode index

I’ve been working my way through these Java exercises at w3resource.com, and at one point I wanted to be able to get a particular Unicode character from its index. For example, I wanted to turn the integer 65 (or 41 in hexadecimal) into the unicode character U+0041, or a capital letter “A”. This was for a program which would convert a given decimal number to its hexadecimal equivalent:

import java.util.Scanner;

public class decimalToHex {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);

    System.out.print("Insert a positive integer: ");
    int num = in.nextInt();
    String hex = "";
    int uni = 0;

    while(num != 0){
      uni = num % 16;
      if(uni > 9){ hex = Character.toString((char)(uni+55)) + hex; }
      else       { hex = Character.toString((char)(uni+48)) + hex; }
      num /= 16;
    }

    System.out.println(hex);

    return;
  }
}

As you can see in the code above, the way I accomplished this was to typecast the integer values (uni+55 or uni+48) to a char, then convert that char to a String. Another way to do this (as was done in the example solution) is to define a 16-character or a 16-String array of 0-9 and A-F, and just add the appropriate character to “hex” with:

String[] myarray = { "0", "1", "2" ... "D", "E", "F" }
...
hex = myarray[uni] + hex;

Java Potpourri I

I took a trip to Barnes & Noble today and found a really neat book, “Sams Teach Yourself Java in 24 Hours“. After working through the first few chapters, I found a few interesting odds and ends. Specifically (1) how to work with Strings, (2) switch statements, and (3) working with date and time. Strings are quite easy to work with in Java, and no imports are necessary:


public class Strings {

  public static void main(String args[]){

    String test = "test";
    String word = "word";

    System.out.println(test.equals(word));
    System.out.println(test + " has " + test.length() + " letters.");
    System.out.println(word.toUpperCase());

    String uppercase = "UPPERCASE";

    System.out.println(uppercase.toLowerCase());
    System.out.println("Does " + uppercase + " contain \"CASE\"?");
    System.out.println(uppercase.contains("CASE"));

    System.out.println("Okay, where is it?");
    System.out.println(uppercase.indexOf("CASE"));

    System.out.println("Does " + test + " contain \"CASE\"?");
    System.out.println(test.contains("CASE"));

  }

}

Several methods are used above, including equals(), which returns true if two Strings are the same, character-by-character; length(), which returns the length of a given String; toUpperCase() and toLowerCase() which convert all of the characters in a string to uppercase and lowercase, respectively; contains() which returns true if a String contains a given substring; and indexOf() which first checks if a String contains a given substring and then returns the index of the beginning of that substring if it is contained within the String of interest.

Additional String methods are described in the Oracle Java tutorials, including charAt(), which retrieves the character of a particular String at the desired index; concat(), which concatenates two Strings (though this can more easily be achieved with a +=); and format(), which allows a C-style construction of Strings from variables of different data types:

public class Format {

  public static void main(String args[]){

    int myInt = 4;
    double myDouble = 3.5;
    String myString = "myString";

    String myFormat = "";

    myFormat = String.format("myInt: %d\nmyDouble: %f\nmyString: %s",
      myInt, myDouble, myString);

    System.out.println(myFormat);

  }

}

Another small difference I found today between Java and C++ is that Java allows underscores “_” in integer values to help break up the powers of ten. For instance:


public class Underscores {

  public static void main(String args[]){

    int a = 17_000;
    int b = 17000;

    System.out.println("a = " + a);
    System.out.println("b = " + b);

  }

}

will print

15:28 |aww@airy Underscores| javac Underscores.java 

15:28 |aww@airy Underscores| java Underscores
a = 17000
b = 17000

while in C++, the following code returns an error

#include <iostream>
using namespace std;

int main(){

  cout << "This is a test." << endl;

  int a = 17_000;
  int b = 17000;

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  return 0;

}

Underscores are also allowed in Perl, but not, apparently, in C++. Another interesting thing I came across while reading this book is that, in Java, switch statements can take Strings as arguments:

public class Switch {

  public static void main(String args[]){

    String controller = "greeting";

    switch(controller){
      case "greeting":
        System.out.println("Hello!");
        break;
      case "farewell":
        System.out.println("Bye!");
        break;
      case "Hawaiian":
        System.out.println("Aloha!");
        break;
    }

  }

}

I thought I remembered that only integers could be used in switch statements in C++, so I wrote a bit of code to check:

#include <iostream>

using namespace std;

int main(){

  char a = 'a';
  char b = 'b';

  char controller = a;

  switch(controller){
    case 'a':
      cout << "controller = " << a << endl;
    break;
    case 'b':
      cout << "controller = " << b << endl;
    break;
  }

  return 0;

}

The C++ code runs fine, so I was mis-remembering. Finally, the book gives an example for working with dates and times in Java. Here’s my slightly edited version from what the book gives:

import java.time.*;
import java.time.temporal.*;

class Clock {

  public static void main(String[] args){

    // get current time and date
    LocalDateTime now = LocalDateTime.now();

    int hour   = now.get(ChronoField.HOUR_OF_DAY);
    int minute = now.get(ChronoField.MINUTE_OF_HOUR);
    int month  = now.get(ChronoField.MONTH_OF_YEAR);
    int day    = now.get(ChronoField.DAY_OF_MONTH);
    int year   = now.get(ChronoField.YEAR);

    // display greeting
    if(hour < 12){
      System.out.println("Good morning!");
    } else if(hour < 17){       System.out.println("Good afternoon!");     } else {       System.out.println("Good evening!");     }     // begin time message by showing the minutes     System.out.print("It's");     if(minute != 0){       System.out.print(" " + minute + " ");       System.out.print( (minute != 1) ? "minutes" : "minute");       System.out.print(" past");     }     // display the hour     System.out.print(" ");     System.out.print((hour > 12) ? (hour - 12) : hour);
    System.out.print((hour > 11) ? " pm" : " am");
    System.out.print(" on ");

    // display the name of the month
    switch(month){
      case 1:
        System.out.print("January");
        break;
      case 2:
        System.out.print("February");
        break;
      case 3:
        System.out.print("March");
        break;
      case 4:
        System.out.print("April");
        break;
      case 5:
        System.out.print("May");
        break;
      case 6:
        System.out.print("June");
        break;
      case 7:
        System.out.print("July");
        break;
      case 8:
        System.out.print("August");
        break;
      case 9:
        System.out.print("September");
        break;
      case 10:
        System.out.print("October");
        break;
      case 11:
        System.out.print("November");
        break;
      case 12:
        System.out.print("December");
        break;
    }

    // display the date and year
    System.out.print(" " + day + ", " + year + ".");

  }

}

Once the initial hurdle of understanding the syntax is overcome (now.get(ChronoField…)), dates and times seem to be pretty easy to work with in Java.

Reversing a number in Java

I have a lot of experience with C++. So while learning about if-else statements and loops is interesting, it’s essentially the same between C++ and Java. That being said, I think the best way to learn a programming language is to just write code in that language. So I’ve looked around for examples online and I found a few decent tutorial sites. The following code is taken from the second last site linked in the previous sentence, and the purpose of the code is to reverse a number (so 34 would become 43, 57 would become 75, etc.).

I don’t want to just copy the code from this example, but I did need to look up how to take user input. It seems like the easiest way is with java.util.Scanner, which can read in single variables or lines of text from the command line. Also, I wanted to look up how to construct Strings, because I wanted to avoid a case where “90” might be reversed to “9” instead of “09”. I want the output to be a String, not an integer.

import java.util.Scanner;

public class ReverseNumber {

  public static String reverseIt(int oldInt){

    String newInt = "";
    newInt += oldInt%10;
    newInt += (oldInt - (oldInt%10))/10;
    return newInt;

  }

  public static void main(String args[]){

    Scanner userInt = new Scanner(System.in);

    System.out.println("Enter any number between 10 and 99: ");
    int myInt = userInt.nextInt();

    System.out.println("You entered: " + myInt);
    System.out.println("Reversed, that is: " + reverseIt(myInt));

  }

}

…it works! Strings are pretty easy to work with in Java, too. And since they’re a basic data type, no extra packages need to be included. This is in stark contrast to C++, where strings are more complex and a bit more difficult to work with. Strings can also be constructed with a StringBuilder() object or using String.format() for a more C-style look.

What’s the difference between “final” and “const” in Java?

I’m following the Java tutorials at tutorialspoint.com/java and the author mentions the “final” keyword at some point in the text. This either wasn’t explained or I glossed over it, and I wondered, “what’s the difference between a ‘final’ variable and a ‘const’ (constant) variable in Java?”

After some Googling, I found the answer: “const” doesn’t do anything in Java. It’s a reserved keyword, but it serves no purpose. There was talk of adding it in later versions, but, apparently, making it backwards-compatible is impossible. Interestingly, C++ has also added (as of C++11) the “final” keyword, which acts the same as it does in Java.

Getting Started with Java

Although, technically, I’ve done some Java programming before (around 2008), I’m more or less starting from scratch here. I’m getting set up to write some Java code on my Ubuntu machine (“ooby”). Getting started with Java on a Linux-based system requires the Java SE Development Kit (currently JDK 8) and a text editor. I use nano because I’m a pleb. (I once coded a website entirely in notepad on Windows and made all of the graphics in paint. I’ve since become only slightly more sophisticated.) The JDK can be installed very easily on Ubuntu, with just an apt-get:

14:21 |andrew@ooby java_examples| sudo apt-get install default-jdk

Apparently, this is all that needs to be done. Then, a “Hello World” program can be written (saved as HelloWorldApp.java):

/**
 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorldApp {
  public static void main(String[] args) {
    System.out.println("Hello World!"); // display the string.
  }
}

This can be compiled and run with the following commands:

14:24 |andrew@ooby java_examples| javac HelloWorldApp.java 

14:24 |andrew@ooby java_examples| java HelloWorldApp
Hello World!

where the output is seen after the java command. That’s it! All set up to code some Java. Now, to set up the same thing on my MacBook Air (“airy”). I downloaded the JDK for Mac OS (“jdk-8uversion-macosx-x64.dmg”) from this page. You need to create an Oracle account to download this software. Installing the JDK *.dmg file allows the above code to run on Mac OS, as well.