Thứ Tư, 17 tháng 9, 2014

Programming Problem



You are given an unsorted array of n^2 arbitrary numbers, and we must output an n x n matrix of all the inputs such that all the rows and columns are sorted. For example, suppose n=3, n^2=9, and the 9 numbers are just the integers {1,2,...,9}
Possible ouput include:

1 4 7       


2 5 8      


3 6 9       


Am giving solution for this problem ...
Note:
to use this program in your machine you need to add my com.shashi.jcore package.you can download that by clicking link:download


program:

=============================================================

import java.util.Arrays;
 

import com.shashi.jcore.Matrix;
import com.shashi.jcore.SException;
public class ArrayClass {
 
 
public static void main(String []args) throws SException
 
{
int arr[]={2,1,4,3,6,5,8,7,9};
Arrays.sort(arr);
passArray(arr);
 
}
public static void passArray(int a[]) throws SException
 
{
int len=(int)Math.ceil(Math.sqrt(a.length));
int index=-1,row=0,col;
int arr[][]=new int[len][len];
for(;;)
 
{
for(col=0;col<len;col++)
 
{
arr[row][col]=a[++index];
 
}
row++;
if(row==len)
break;
 
}
//trnspose matrix now/*
Matrix m=new Matrix();
m.printMatTranspose(arr);
 
}
}
============================================
output:

1 4 7

2 5 8

3 6 9
 

Không có nhận xét nào:

Đăng nhận xét