Popular Posts

Monday, October 03, 2011

Java: Triangular Array (varying sized rows array)


Can we achieve varied-size rows in a two dimensional array in Java language like in PHP and other languages?

Absolutely!
When a double dimensional array is instantiated like this
int[][] array = new int[n][m] 

then all rows are of the same size m

Consider for example int[][] array = new int[10][5]
All rows in this double dimensional array would be of equal size 5.

But this is not what we need...we wanted varying-size rows in double dimensional array, right?

Here is the technique to produce varying-size row.
int[][] array = new int[10][];  

Don't instantiate the column part of the array in order to be able to get varied size columns of the array later on.

like this...
array[0] = new int[1]; //row0 of size 1
array[1] = new int[2]; //row1 of size 2
array[2] = new int[3]; //row2 of size 3
.....

Take a look at below code which produces Triangular array


 0
 0 0
 0 0 0
 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0


public static void TriangularArray(int maxRow){
		
		int[][] triangle;

		// instantiating only row part of the array (total number of rows)
		triangle = new int[maxRow][];
		
		// Now instantiate individual columns separately with different sizes and assign them to rows  
		for (int r=0; r < triangle.length; r++) {
		    triangle[r] = new int[r+1]; 
		}

		// Print the triangular array
		for (int r=0; r<triangle.length; r++) {
		    for (int c=0; c<triangle[r].length; c++) {
		        System.out.print(" " + triangle[r][c]);
		    }
		    System.out.println("");
		}
	}




Wednesday, September 21, 2011

Java Puzzles: advanced puzzlers


public class PoisonParen {

    /*
     * Add a declaration that initializes a field to some expression and
     * compile the program. It must compile without error. Now add a pair
     * of parentheses around a subexpression that serves merely to reinforce
     * the order of evaluation that was performed before you inserted the
     * parentheses.  Recompile the program. If it no longer compiles, then
     * you've solved the puzzle!
     */
}

public class Reflexive {
    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a primitive type and value
         * that causes this program to print "false", then
         * you have proven that the == operator is not reflexive.
         */
        <typeX> x = <valueX>;

        System.out.println(x == x);
    }
}


public class Symmetric {
    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a set of primitive types and values
         * that causes this program to print "true false", then
         * you have proven that the == operator is not symmetric.
         */
        <typeX> x = <valueX>;
        <typeY> y = <valueY>;

        System.out.print ((x == y) + " ");
        System.out.println(y == x);
    }
} 

public class Transitive {

    public static void main(String[] args) throws Exception {
        /*
         * If you can come up with a set of primitive types and values
         * that causes this program to print "true true false", then
         * you have proven that the == operator is not transitive.
         */

        <typeX> x = <valueX>;
        <typeY> y = <valueY>;
        <typeZ> z = <valueZ>;

        System.out.print ((x == y) + " ");
        System.out.print ((y == z) + " ");
        System.out.println(x == z);
    }
}


import java.util.*;

public class Pair<T> {
    private final T first;
    private final T second;

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T first() {
        return first;
    }
    public T second() {
        return second;
    }

    public List<String> stringList() {
        return Arrays.asList(String.valueOf(first),
                             String.valueOf(second));
    }


    public static void main(String[] args) {
        Pair p = new Pair<Object>(23, "skidoo");
        System.out.println(p.first() + " " + p.second());
        for (String s : p.stringList())
            System.out.print(s + " ");
    }
}


public class LinkedList<E> {
    private Node<E> head = null;
    private class Node<E> {

        E value;
        Node<E> next;

        // Node constructor links the node as a new head
        Node(E value) {
            this.value = value;
            this.next = head;
            head = this;
        }
    }


    public void add(E e) {
       new Node<E>(e);
        // Link node as new head
    }


    public void dump() {
        for (Node<E> n = head; n != null; n = n.next)
            System.out.println(n.value + " ");
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("world");
        list.add("Hello");
        list.dump();
    }
}


public class Outer {
    class Inner1 extends Outer {}
    class Inner2 extends Inner1 {}
}


import java.util.*;
import java.io.*;

public class SerialKiller {
    public static void main(String[] args) {
        Sub sub = new Sub(666); 
        sub.checkInvariant();

        Sub copy = (Sub) deepCopy(sub);
        copy.checkInvariant();
    }

    // Copies its argument via serialization (See Puzzle 80)
    static public Object deepCopy(Object obj) {
        try {
           ByteArrayOutputStream bos = 
                new ByteArrayOutputStream();
            new ObjectOutputStream(bos).writeObject(obj);
            ByteArrayInputStream bin =
                new ByteArrayInputStream(bos.toByteArray());
            return new ObjectInputStream(bin).readObject(); 
        } catch(Exception e) {
            throw new IllegalArgumentException(e); 
        }
    }
}

class Super implements Serializable {
    final Set<Super> set = new HashSet<Super>();
} 

final class Sub extends Super {
    private int id;
    public Sub(int id) {
        this.id = id;
        set.add(this); // Establish invariant
    }

    public void checkInvariant() {
        if (!set.contains(this))
           throw new AssertionError("invariant violated");
    }

    public int hashCode() {
        return id;
    }

    public boolean equals(Object o) {
        return (o instanceof Sub) && (id == ((Sub)o).id);
    }
}


public class Twisted {
    private final String name;
    Twisted(String name) {
        this.name = name;
    }
    private String name() {
        return name;
    }
    private void reproduce() {
        new Twisted("reproduce") {
            void printName() {
                System.out.println(name());
            }
        }.printName();
    }
    public static void main(String[] args) {
        new Twisted("main").reproduce();
    }
}


public class PrintWords {
    public static void main(String[] args) {
        System.out.println(Words.FIRST  + " " + 
                           Words.SECOND + " " +
                           Words.THIRD);
    }
}
public class Words {
    private Words() { };  // Uninstantiable

    public static final String FIRST  = "the";
    public static final String SECOND = null;
    public static final String THIRD  = "set";
} 

// The second version of the Words class appears below (commented out)
//
// public class Words {
//     private Words() { };  // Uninstantiable
//
//     public static final String FIRST  = "physics";
//     public static final String SECOND = "chemistry";
//     public static final String THIRD  = "biology";
// }


import java.util.Random; 

public class Shuffle {
    private static Random rnd = new Random();
    public static void shuffle(Object[] a) {
        for (int i = 0; i < a.length; i++)
            swap(a, i, rnd.nextInt(a.length));
    }

    private static void swap(Object[] a, int i, int j) {
       Object tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}


public class ApplePie {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 0; i < 100; i++); {
            count++;
        }
        System.out.println(count);
    }
}

import java.util.*;

public class BananaBread {
    public static void main(String[] args) {
        Integer[] array = { 3, 1, 4, 1, 5, 9 };
        Arrays.sort(array, new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return i1 < i2 ? -1 : (i2 > i1 ? 1 : 0);
            }
        });
        System.out.println(Arrays.toString(array));
    }
}

public class ChocolateCake {
    public static void main(String[] args) {
        System.out.println(true?false:true == true?false:true);
    }
}

Java Puzzles: library puzzlers


public class PingPong {
    public static synchronized void main(String[] a) {
        Thread t = new Thread() {
            public void run() { pong(); }
        };
        t.run();
        System.out.print("Ping");
    }

    static synchronized void pong() {
        System.out.print("Pong");
    }
}


import java.util.*;

public class Worker extends Thread {
    private volatile boolean quittingTime = false;
    public void run() {
        while (!quittingTime)
            pretendToWork();
        System.out.println("Beer is good");
    }
    private void pretendToWork() {
        try {
            Thread.sleep(300); // Sleeping on the job?
        } catch (InterruptedException ex) { }
    }

    // It's quitting time, wait for worker - Called by good boss
    synchronized void quit() throws InterruptedException {
        quittingTime = true;
        join();
    }
    // Rescind quitting time - Called by evil boss
    synchronized void keepWorking() {
        quittingTime = false;
    }

    public static void main(String[] args)
            throws InterruptedException {
        final Worker worker = new Worker();
        worker.start();

        Timer t = new Timer(true); // Daemon thread
        t.schedule(new TimerTask() {
            public void run() { worker.keepWorking(); }
        }, 500);

        Thread.sleep(400);
        worker.quit();
    }
}


import java.util.*; import java.lang.reflect.*;

public class Reflector {
    public static void main(String[] args) throws Exception {
        Set s = new HashSet();
        s.add("foo");
        Iterator it = s.iterator();
        Method m = it.getClass().getMethod("hasNext");
        System.out.println(m.invoke(it));
    }
}


public class Pet {
    public final String name;
    public final String food;
    public final String sound;

    public Pet(String name, String food, String sound) {
        this.name = name;
        this.food = food;
        this.sound = sound;
    }

    public void eat() {
        System.out.println(name + ": Mmmmm, " + food);
    }
    public void play() {
        System.out.println(name + ": " + sound + " " + sound);
    }
    public void sleep() {
        System.out.println(name + ": Zzzzzzz...");
    }

    public void live() {
        new Thread() {
            public void run() {
                while (true) {
                    eat();
                    play();
                    sleep();
                }
            }
        }.start();
    }

    public static void main(String[] args) {
        new Pet("Fido", "beef", "Woof").live();
    }
}


public class Outer {
    public static void main(String[] args) throws Exception {
        new Outer().greetWorld();
    }

    private void greetWorld() throws Exception {
        System.out.println(Inner.class.newInstance());
    }

    public class Inner {
        public String toString() {
            return "Hello world";
        }
    }
}


public class Greeter {
    public static void main (String[] args) {
        String greeting = "Hello world";
        for (int i = 0; i < greeting.length(); i++)
            System.out.write(greeting.charAt(i));
    }
}


public class BeerBlast {
    static final String COMMAND = "java BeerBlast slave";

    public static void main(String[] args) throws Exception {
        if (args.length == 1 && args[0].equals("slave")) {
            for (int i = 99; i > 0; i--) {
                System.out.println(i + " bottles of beer on the wall");
                System.out.println(i + " bottles of beer");
                System.out.println("You take one down, pass it around,");
                System.out.println((i-1) + " bottles of beer on the wall");
                System.out.println();
            }
        } else {
            // Master
            Process process = Runtime.getRuntime().exec(COMMAND);
            int exitValue = process.waitFor();
            System.out.println("exit value = " + exitValue);
        }
    }
}


public class CopyDog {
    public static void main(String[] args) {
        Dog newDog = ??? ; // You figure out what to put here

        // This line should print false
        System.out.println(newDog == Dog.INSTANCE);

        // This line should print "Woof"
        System.out.println(newDog);
    }
}

public class Dog extends Exception {
    public static final Dog INSTANCE = new Dog();
    private Dog() { }

    public String toString() {
        return "Woof";
    }
}


public class SelfInterruption {
    public static void main(String[] args) {
        Thread.currentThread().interrupt();

        if (Thread.interrupted()) {
            System.out.println("Interrupted: " + Thread.interrupted());
        } else {
            System.out.println("Not interrupted: " + Thread.interrupted());
        }
    }
}


public class Lazy {
    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                initialized = true;
            }
        });
        t.start();
        try {
            t.join();
        } catch(InterruptedException e) {
            throw new AssertionError(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}