Monday, May 2, 2016

Simplest way to print array content in Java

The simplest way to print array contents in Java is using the methods from the utility class Arrays. Methods below are available since Java 5 (1.5).
int[] prim = { 0, 1, 2, 3, 4 };

System.out.println(Arrays.toString(prim));

Sunday, April 3, 2016

Replace command line inputs backspace with \b, tab with \t, and \ with \\. C and Java

"C Programming" K &s; R Book has a question:

Read command line inputs and replace tab with "\t", backspace with "\b", and backslash with "\\". But the shell interpreter consumes the backspace before it can be sent to the C program.

You can use following ways to get around this.

1, use echo to redirect.
echo "test\t\b\" | c-program

will produce

test\\t\\b\\

on a windows machine. This method may work on linux system.



2, use _getch() from conio.h. Use curses.h or ncurses.h for linux.

#include <stdio.h>
#include <conio.h>

int main() {
	int c;
	while ((c = _getch()) != 'y') {
		if (c == '\t') printf("%s", "\\t");
		if (c == '\b') printf("%s", "\\b");
		if (c == '\\') printf("%s", "\\\\");
		else putchar(c);
	}
}


3, change input mode of console. Use termios.h for linux.

#include <stdio.h>
#include <Windows.h>

int main() {
	int c;

	HANDLE hConsoleStdin = GetStdHandle(STD_INPUT_HANDLE);
	DWORD flags;
	if (GetConsoleMode(hConsoleStdin, &flags))
	{
	    // Now `flags` contain the current flags
	    // Remove the flags we don't want there
	    // flags &= ~(ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);
	    flags &= ~ ENABLE_LINE_INPUT;

	    // And finally set the new flags
	    SetConsoleMode(hConsoleStdin, flags);
	}

	while ((c = getchar()) != EOF) {
		if (c == '\t') printf("\\t");
		if (c == '\b') printf("\\b");
		if (c == '\\') printf("\\\\");
		else printf("%c",c);
	}
}


In Java, System.in.read() can be used to read one character at a time. But I have not found functions to change the input mode of the command line or directly read characters from console, System.in, or Scanner.

Tuesday, March 29, 2016

Java, how to onvert primitive array type to Boxed type, convert int array to Integer array

With Java 8's functional interfaces, one could be more concise and use shorter codes to convert a primitive array to the corresponding boxed type. Below we will use int array and Integer array as an example.

Prior to Java 8, we could use a few ways below to copy from the primitive array to a new array of the same length but of the boxed type:


int[] old = {1,2,3,4,5};
Integer[] newArray = new Integer[old.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

// or Arrays.copyOf()

System.arraycopy(old, 0, newArray, 0, old.length);


With java 8, we could use the stream interface and lambda expressions as below.

int[] old = {1,2,3,4,5};
Integer[] newArray = IntStream.of(old).boxed()
                     .toArray(Integer[]::new);

// or

newArray = Arrays.stream(old).boxed()
                 .toArray(Integer[]::new);

Alternatively, for ease of printing the array out, one could also collect it to a list after the stream operations.

int[] old = {1,2,3,4,5};

List<integer> newArrayList = IntStream.of(old).boxed()
                        .collect(Collectors.toList());
System.out.println(newArrayList);

The output will be:

[1, 2, 3, 4, 5]

Sunday, March 27, 2016

String Search Algorithm - Brute Force

Denote that the goal is to find the first index of String needle with a length of M in String haystack with a length of N. Typically, M << N.

The brute force algorithm is to align needle at index i of haystack and compare the two, if not match, move up index i till i = N - M. Return - 1 if not found. The algorithm has a worst case running time of M*N, in practice typical time is ~ 1.1 N.

A java implementation is below:




public int strStrBF(String haystack, String needle) {
	for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
		int j = 0;
		for (; j < needle.length(); j++) {
			if (haystack.charAt(i + j) != needle.charAt(j)) break;
		}
		if (j == needle.length()) return i;
	}
	return -1;
}

Sunday, March 20, 2016

Eclispe Source Hover Background

After using the dark theme in eclipse and switched back, one background did not change back to white/grey color. That is when mouse over / hovering on the folded source code, the background is still black. To change this, use Window - Preferences - Java - Editor - Source Hover Background, change it to system default, or pick a color you like, or restore defaults.


Friday, March 18, 2016

Syntax Highlighting on blogger.com blogspot.com

To add syntax highlighting feature for your blogger.com blog, you can use Alex Gorbatchev's javascripts.

Go to your blog dashboard, settings, template, edit html. Add the html codes below inside the head section of the template.



    
    

You can switch to a different theme or add more programming languages supported. To use the feature, wrap your code with <pre class="brush:java"> </pre>  or <script class="brush:java"> </script> tags. See Alex's website for pros and cons of each method.

Thursday, March 17, 2016

Using Java's Reflection for Testing

Repeatedly writing for loops for testing is not fun.

We can use Java reflection API (java.lang.reflect package) to maximize code reuse and help testing.

private final static String SUCCESS = "Congrats! All tests passed.";

public static <T, R> void assertEqual(String className, String methodName,
  T[] inputs, R[] expected) {
  // make sure they have same length
  validateLengths(inputs, expected);
  
  try {
    // use reflection to get type of class indicated by "className"
    Class<?> c = Class.forName(className);
    Class<T> inputType = (Class<T>) inputs[0].getClass();
    Method m = c.getMethod(methodName, inputType);

    // static methods will ignore this instance
    Object o = c.newInstance();

    for (int i = 0; i < inputs.length; i++) {
      R e = expected[i];
      R output = (R) m.invoke(o, inputs[i]);

      // has to test deep equal for array type
      if (e.getClass().isArray()) {
        int n = Array.getLength(e);
        for (int j = 0; j < n; j++) {
          if (!Array.get(e, j).equals(Array.get(output, j))) {
            System.out.println("test failed for "
              + Arrays.asList(inputs[i]) + " expected "
              + Arrays.asList(e) + ", output "
              + Arrays.asList(output));
            System.exit(-1);
          }
        }
      } else if (!e.equals(output)) {
        System.out.println("test:\n " + inputs[i] + "failed, "
          + " expected " + expected + ", output " + output);
        System.exit(-1);
      }

    }
    
    // all tests passed
    System.out.println(SUCCESS);
  
  } catch (ClassNotFoundException | IllegalAccessException
    | IllegalArgumentException | InvocationTargetException
    | NoSuchMethodException | SecurityException
    | InstantiationException e) {
    //handle your exceptions here
    e.printStackTrace();
  }
}




To use the method, call:

assertEqual("my.pkg.className","methodName",inputArray,
         expectedResultsArray);



Don't forget to include the package name.