Wednesday, June 3, 2009

Puzzle 29 – Solution.

The trick here is to control a for loop using multiple variables. Thus a single for loop can be used as multiple for loop.
The code expalins this principle –

package com.twister;
import java.util.Scanner;
class Matrix{

public static void main(String a[])
int r,c;
int i,j,k=0;
int matrix[][] = new int[10][10];
= 2; c= 2;

/*Variable k is used to determine whether the for Loop
is currently scanning elements or printing them
k = 0 Loop is in scan mode
k = 1 Loop is in print mode
for(j=0,i=0;i<r && j<c && k!=2;j++){
if(k==0) //Scan mode
matrix[i][j] = new Scanner(;

if(k==1) //Print Mode
System.out.print(matrix[i][j]+ " ");

if(i==r-1 && j==c-1){ //Swap from scan mode to print mode

""); //Prints a Blank line

My personal favorite solution for this puzzle is the one by Kannan - Short, concise and gets the Job done!

Leaders board to be update with the next post!

No comments:

Post a Comment

Solution for this question?