Thread: Spiral Problem
View Single Post
Old Aug 27th, 2004, 11:33 AM   #1
D4Z
Newbie
 
Join Date: Aug 2004
Posts: 1
Rep Power: 0 D4Z is on a distinguished road
first of all, this is a school problem. It's not mandatory to solve, but it's driving me crazy. We're supposed to take an integer input from a file and display it in a matrix, with a 1 in the center, for example if the input was 3 we should have a matrix like this

9 8 7
2 1 6
3 4 5


I'm having trouble doing this. Here's the code I have.

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

public class Shootout
{
	public static void main(String[]args) throws Exception
	{
 Scanner keyboard = new Scanner(new File("pr92.dat"));
 int side = keyboard.nextInt();
 int matrix[][] = new int [side][side];
 int maxLength = side;
 int maxWidth = side;
 int direction = 0;
 int max = side^2;
 int current=0;
 
 
 for(int i=((side+1)-maxLength); i<maxLength; i++)
 {
 	
 	for(int j=((side+1)-maxWidth); j<maxWidth; j++)
 	{
  if(direction==0)
  {
  	for(int k = 0; k<side; k++)
  	{
   matrix[i][j] = max-j;
   current = max-k;
  	}
  	
  	direction = 2;
  	maxWidth--;
  }
  
  if(direction==1)
  {
  	for(int k = 0; k<side; k++)
  	{
   matrix[i][j] = current;
   current--;
  	}
  	
  	direction = 2;
  	maxWidth--;
  }
  
  if(direction==2)
  {
  	for(int k = 0; k<side; k++)
  	{
   matrix[j][i]=current;
   current--;
  	}
  }
  
  direction=1;
  maxWidth--;
  
 	//	maxWidth--;
 	}
 	
 	maxLength--;
 }
 
 for(int i = 0; i<side; i++)
 {
 	for(int j=0; j<side; j++)
 	{
  System.out.print(matrix[i][j] + "\t");
 	}
 	
 	System.out.println();
 }
	
	}

}


Please go easy on me.
D4Z is offline   Reply With Quote