I have three run arguments that are min width, max width and the text file name. The text files are filled with one long string of random characters. I want to put each character into a grid spot. But all I get back is the string itself from the file. How do I make the grid?
class GridCipher{
static int minGridWidth;
static int maxGridWidth;
static File inputFile;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args))
processInput();
}
static final String usage = "Usage: GridWriter min_width max_width input_file_name";
static boolean handleArguments(String[] args) {
// Check for correct number of arguments
if (args.length != 3) {
System.out.println("Wrong number of command line arguments.");
System.out.println(usage);
return false;
}
try {
minGridWidth = Integer.parseInt(args[0]);
maxGridWidth = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.out.println("min_width and max_width must be integers.");
System.out.println(usage);
return false;
}
inputFile = new File(args[2]);
if (!inputFile.canRead()) {
System.out.println("The file " + args[2] + " cannot be opened for input.");
return false;
}
return true;
}
static void processInput() throws FileNotFoundException {
Scanner input = new Scanner(inputFile);
String line = input.nextLine();
int length = line.length(); // number of characters.
// Try each width in the appropriate range
for (int width = minGridWidth; width <= maxGridWidth; width++) {
// Determine heigth of grid
int height = line.length() / width;
// Add one to height if there's a partial last row
if (line.length() % width != 0)
height += 1;
loadUnloadGrid(line, width, height);
}
}
static void loadUnloadGrid(String line, int width, int height) {
char grid[][] = new char[height][width];
// Determine number long columns
int longColumn = line.length() % width;
if (longColumn == 0)
longColumn = width;
//Load the input data into the grid by column
int charCount = 0;
for (int c = 0; c < width; c++) {
for (int r = 0; r < height; r++) {
if (r < height - 1 || c < longColumn) {
grid[r][c] = line.charAt(charCount);
charCount += 1;
}
}
}
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
// Special handling for last row
for (int c = 0; c < longColumn; c++) {
System.out.print(grid[height - 1][c]);
}
System.out.println("\"");
}
}
If the text file has ABCDE, I just get back ABCDE. I would like the characters in a grid determined by my min and max width.
If I understand you correctly you want ABCDEFG into
A B C
D E F
G
but in the fragment writing it on screen you miss new line character
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
should be
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
System.out.println();
}
Printing grid is not correct in your program.
Change below to
// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
this code
for(char[] arr : grid) {
System.out.println(Arrays.toString(arr));
}
Related
I have to create a Java program for Conway's Game Of Life in procedural manner and I'm only one step away from finishing - all I have left to do is figure out how to make the output change itself(something like a GIF). Instead, my program outputs all the results one by one. I'm figuring it should be some kind of a loop, but I'm not sure. Here's the code:
import java.util.Random;
import java.util.Scanner;
class gameOfLife {
public static void main(String[] args) {
//User input
Scanner in = new Scanner(System.in);
System.out.println("How many rows?");
int rows = in.nextInt();
System.out.println("How many columns?");
int cols = in.nextInt();
//Declaring variables and grids
int[][] grid = new int[rows][cols];
int[][] nextGrid = new int[rows][cols];
int[][] temp = new int [rows][cols];
//Initializing first generation
initiateGrid(grid);
printGameBoard(grid);
//Looping through 10 generations
for (int x = 0; x < 20; x++) {
applyTheRules(grid, rows, cols, nextGrid);
temp = nextGrid;
nextGrid = grid;
grid = temp;
printGameBoard(grid);
}
}
//Initiating first generation grid randomly
static void initiateGrid(int[][] grid) {
Random r = new Random();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = r.nextInt(2);
}
}
}
//Printing out the game board
static void printGameBoard(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 0)
System.out.print(" . ");
else
System.out.print(" ■ ");
}
System.out.println();
}
System.out.println();
}
//Applying the rules of the game
static void applyTheRules(int [][] grid, int rows, int cols, int [][] nextGrid) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int count = 0;
if(i-1>=0 && i+1<grid.length && j-1>=0 && j+1<grid[i].length) {
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += grid[i + x][j + y];
}
}
count -= grid[i][j];
} else{
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += 0;
}
}
}
//Alive cell becomes dead, if there are more than
//3 or less than 2 neighbouring cells
if((grid[i][j]==1)&&(count<2)||(count>3))
nextGrid[i][j]=0;
//Dead cell becomes alive if there are exactly 3 neighbouring cells
else if((grid[i][j]==0)&&(count==3))
nextGrid[i][j]=1;
//State stays the same
else
nextGrid[i][j]=grid[i][j];
}
}
}
}
On my program for java programming is not running right. My professor had us download a console.java to help use make a console to display our outputs of the program. I think the program is getting stuck when I am calling the update method and checkCells. My professor said that calling matrix.length for both rows and columns is incorrect but I'm stumped on how to call columns if I am not using matrix.length.
Any input is appreciated
import java.util.*;
public class Life {
private int birthLow = 0;
private int birthHigh = 0;
private int liveLow = 0;
private int liveHigh = 0;
private boolean[][] matrix;
public Life(long seed, int rows, int cols, int birthLow2, int birthHigh2, int liveLow2, int liveHigh2) {
boolean initalMatrix[][] = new boolean[rows][cols];
seedArray(initalMatrix, rows, cols, seed);
birthLow = birthLow2;
birthHigh = birthHigh2;
liveLow = liveLow2;
liveHigh = liveHigh2;
matrix = initalMatrix;
if ((rows < 1) && (cols < 1)) {
throw new IllegalArgumentException("Rows must be positive, not " + rows);
}
if ((rows > 9) && (cols < 9)) {
throw new IllegalArgumentException("Rows and cols cant go over 9, not " + rows + cols);
}
if (birthLow < 1 || (birthHigh > 9) || (liveLow < 1) || (liveHigh > 9)) {
throw new IllegalArgumentException("birth rates can not be below 1 or above 9 " + birthLow + birthHigh);
}
}
public boolean[][] world() {
boolean[][] matrixClone = matrix.clone();
for (int row = 0; row < matrix.length; row++) {
matrixClone[row] = matrix[row].clone();
}
return matrixClone;
}
public void update() {
matrix = checkCells(matrix, matrix.length, matrix.length, birthLow, birthHigh, liveLow, liveHigh);
}
public static void seedArray(boolean[][] matrix, int rows, int cols, long seed) {
// generates a random seed to fill the matrix
Random s = new Random(seed);
for (int r = 1; r < rows - 1; r++) {
for (int c = 1; c < cols - 1; c++) {
boolean x = s.nextBoolean();
matrix[r][c] = x;
}
}
}
public static void printBoard(boolean[][] matrix, int rows, int cols) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matrix[r][c] == false && c == 0) {
System.out.print("- ");
} else if (matrix[r][c] == false && c > 0) {
System.out.print("- ");
} else if (matrix[r][c] == true) {
System.out.print("# ");
}
}
System.out.println();
}
System.out.println();
}
public static boolean[][] checkCells(boolean[][] matrix, int rows, int cols, int birthLow, int birthHigh,
int liveLow, int liveHigh) {
// clones matrix board
boolean[][] matrixClone = matrix.clone();
for (int row = 0; row < matrix.length; row++) {
matrixClone[row] = matrix[row].clone();
}
// determines if the living cell is going to live or die
for (int r = 1; r < rows; r++) {
for (int c = 1; c < cols; c++) {
if (neighbors(matrixClone, r, c) < liveLow || neighbors(matrixClone, r, c) > liveHigh || c == 0
|| r == 0 || c == cols - 1 || r == rows - 1) {
matrix[r][c] = false;
} else if (neighbors(matrixClone, r, c) >= birthLow && neighbors(matrixClone, r, c) <= birthHigh) {
matrix[r][c] = true;
}
}
}
return matrixClone;
}
public static int neighbors(boolean[][] matrixClone, int r, int c) {
int neighbors = 0;
// checks all neighbors for life or death
for (int rn = (r - 1); rn <= (r + 1); rn++) {
for (int cn = (c - 1); cn <= (c + 1); cn++) {
try {
if (matrixClone[rn][cn] == true) {
neighbors++;
}
// catches the array if it checks out the perimeter
} catch (ArrayIndexOutOfBoundsException f) {
continue;
}
}
}
return neighbors;
}
}
Don't use matrix.length for columns. You already know that. The reason is that it gives you the number of rows. Instead, just save the values of row and col and use them.
One way to do that is to make them fields, and initialize them in your constructor.
Do not initialize a random boolean[][] called initialMatrix. Instead, initialize the boolean[][] matrix that you have in the fields up above (matrix = new boolean[rows][cols]). Then for seedArray, call seedArray(matrix, rows, cols, seed).
Finally, in the update() method, do not use matrix.length, but rather rows and cols.
I am new to programming and have programmed a java program that calculates the voronoi diagram for random points and draws it on a picture - 1080 x 1920 pixels. Here you can see the result
The problem is that it takes nearly four minutes to compile the code. Please help me with code optimization. Below you can find the code:
class Voronoi {
private static Random r;
private static KDTree<Integer> kd;
private static double[][] keys;
private static int counter;
private static int x;
public static void main(String[] args) throws IOException,
KeySizeException, KeyDuplicateException {
BufferedImage img = null;
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
// input an image
img = ImageIO.read(new File("input.jpg"));
// get image Height and Width
int w = img.getWidth();
int h = img.getHeight();
// make array with equal size like the image and populate it with the 0
// make an empty array and populate it
int[][] empty = new int[h][w];
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
empty[row][col] = 0;
}
}
// make a D-dimensional KD-tree
keys = new double[x][2];
kd = new KDTree<Integer>(2);
ArrayList<Color> b = new ArrayList<Color>();
int[] totalBlue = new int[x];
int[] totalGreen = new int[x];
int[] totalRed = new int[x];
int[] counter_sec = new int[x];
// Generate random centers and populate them with 1
for (int i = 0; i < x; i++) {
generateCentre(empty, h, w);
// b.add(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
double[] array = new double[2];
array[0] = i;
array[1] = j;
Color c = new Color(img.getRGB(j, i));
totalBlue[kd.nearest(array)] = totalBlue[kd.nearest(array)]
+ c.getBlue();
totalRed[kd.nearest(array)] = totalRed[kd.nearest(array)]
+ c.getRed();
totalGreen[kd.nearest(array)] = totalGreen[kd.nearest(array)]
+ c.getGreen();
// img.setRGB(j, i, b.get(kd.nearest(array)).getRGB());
counter_sec[kd.nearest(array)] = counter_sec[kd.nearest(array)] + 1;
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
double[] array = new double[2];
array[0] = i;
array[1] = j;
Color c = new Color(img.getRGB(j, i));
// img.setRGB(j, i, b.get(kd.nearest(array)).getRGB());
Color color = new Color(totalRed[kd.nearest(array)]/counter_sec[kd.nearest(array)], totalGreen[kd.nearest(array)]/counter_sec[kd.nearest(array)],totalBlue[kd.nearest(array)]/counter_sec[kd.nearest(array)]);
img.setRGB(j, i, color.getRGB());
}
}
File outputfile = new File("image.jpg");
ImageIO.write(img, "jpg", outputfile);
System.out.println(totalRed[0]/counter_sec[0]+" "+totalGreen[0]/counter_sec[0]+" "+totalBlue[0]/counter_sec[0]);
}
public static void generateCentre(int[][] empty, int h, int w)
throws KeySizeException, KeyDuplicateException {
r = new Random();
int height = r.nextInt(h);
int width = r.nextInt(w);
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if (row == height && col == width && empty[height][width] == 0) {
empty[height][width] = 1;
keys[counter][0] = row;
keys[counter][2] = col;
kd.insert(keys[counter], counter);
}/*else if (row == height && col == width
&& empty[height][width] != 0) {
generateCentre(empty, h, w);
}*/
}
}
System.out.println(kd.search(keys[counter]));
if (counter < x) {
counter++;
}
}
}
Although I don't claim a full understanding of your code, I see one potentially large cause of slowdown:
totalBlue[kd.nearest(array)] = totalBlue[kd.nearest(array)]
+ c.getBlue();
totalRed[kd.nearest(array)] = totalRed[kd.nearest(array)]
+ c.getRed();
totalGreen[kd.nearest(array)] = totalGreen[kd.nearest(array)]
+ c.getGreen();
// img.setRGB(j, i, b.get(kd.nearest(array)).getRGB());
counter_sec[kd.nearest(array)] = counter_sec[kd.nearest(array)] + 1;
You seem to be repeatedly calling kd.nearest(array), which is probably not a very cheap operation. You should call that once and store it in a local variable. I would rewrite your key loop as follows:
double[] coords = new double[2];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
coords[0] = i;
coords[1] = j;
final int nearest = kd.nearest(coords);
final Color c = new Color(img.getRGB(j, i));
totalBlue[nearest] += c.getBlue();
totalRed[nearest] += c.getRed();
totalGreen[nearest] += c.getGreen();
counter_sec[nearest]++;
}
}
Here I have utilized the += and ++ operators to make things shorter and more readable. I have also hoisted your coordinates array outside the loop because it can be safely reused at each iteration. This reduces GC time, but more importantly it helps CPU caches.
Apply the same changes to your second loop, where you generate the output image.
So this program needs to do a few things with the image. I started writing method called replicate and what it needs to do is to take in num1 and num2, and then duplicate the image left-right num1 times, and then replicate the picture num2 times top to bottom. So like the same a small image would act as desktop wallpaper, it's repeat itself. I am not allowed to use image buffer. thank you
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class ImageTool {
// THIS METHOD MAY BE CALLED, BUT MUST NOT BE MODIFIED!
//
public static int[][] readGrayscaleImage(String filename) {
int [][] result = null;
try {
File imageFile = new File(filename);
BufferedImage image = ImageIO.read(imageFile);
int height = image.getHeight();
int width = image.getWidth();
result = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = image.getRGB(x, y);
result[y][x] = rgb & 0xff;
}
}
}
catch (IOException ioe) {
System.err.println("Problems reading file named " + filename);
System.exit(1);
}
return result;
}
// THIS METHOD MAY BE CALLED, BUT MUST NOT BE MODIFIED!
//
public static void writeGrayscaleImage(String filename, int[][] array) {
int width = array[0].length;
int height = array.length;
try {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = array[y][x];
rgb |= rgb << 8;
rgb |= rgb << 16;
image.setRGB(x, y, rgb);
}
}
File imageFile = new File(filename);
ImageIO.write(image, "jpg", imageFile);
}
catch (IOException ioe) {
System.err.println("Problems writing file named " + filename);
System.exit(1);
}
}
public static void main (String [] args) {
if (args.length < 1) {
System.out.println("Invalid program execution");
System.out.println("Please provide command");
System.exit(-1);
}
if (args[0].equals("--dump")){
String fileName = args[1];
int [][] image = readGrayscaleImage(fileName);
print2dArray(image);
} else if (args[0].equals("--reflectV")){
String fileName = args[1];
int [][] image = readGrayscaleImage(fileName);
int [][] reflected = reflectV(image);
String outputFilename = args[2];
writeGrayscaleImage(outputFilename, reflected);
} else if (args[0].equals("--reflectH")){
String fileName = args[1];
int [][] image = readGrayscaleImage(fileName);
int [][] reflected = reflectH(image);
String outputFilename = args[2];
writeGrayscaleImage(outputFilename, reflected);
} else if (args[0].equals("--ascii")){
String fileName=args[1];
int [][] image = readGrayscaleImage(fileName);
ascii(image);
} else if (args[0].equals("--replicate")) {
String fileName = args[2];
int [][] image = readGrayscaleImage(fileName);
double factor = args[0];
String outputFilename = args[3];
writeGrayscaleImage(outputFilename, reflected);
}
}
public static void replicate(double num1, double num2, int[][]arr) {
double length = num1 * arr.length;
double height = num2 * arr[0].length;
int[][]newArr = new int[length][height];
for(int i = 0; i <= newArr.length; i++){
for(int j = 0; j <= arr.length; j++){
newArr[i][j]=arr[i][j];
}
}
}
public static void ascii (int[][]arr) {
int rows = arr.length;
int cols = arr[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(arr[i][j] >= 0 && arr[i][j] <= 25){
System.out.print("M");
} else if(arr[i][j]>=26 && arr[i][j] <=50){
System.out.print("$");
} else if(arr[i][j]>=51 && arr[i][j] <= 76){
System.out.print("0");
} else if(arr[i][j]>=77 && arr[i][j] <=102){
System.out.print("|");
} else if(arr[i][j]>=103 && arr[i][j]<=127){
System.out.print("*");
} else if (arr[i][j]>=128 && arr[i][j]<=152){
System.out.print(":");
} else if (arr[i][j]>=153 && arr[i][j]<=178){
System.out.print("=");
} else if (arr[i][j]>=179 && arr[i][j]<=204){
System.out.print("\'");
} else if (arr[i][j]>=205 && arr[i][j]<=230){
System.out.print(".");
} else if (arr[i][j]>=231 && arr[i][j]<=255){
System.out.print(" ");
}
}
System.out.println();
}
}
public static void print2dArray(int[][] arr) {
for (int i = 0; i <arr.length; i++){
//System.out.println(Arrays.toString(arr[i]));
for (int j = 0; j< arr[i].length; j++){
System.out.format("%3d, " , arr[i][j]);
}
System.out.println();
}
}
public static int [][] reflectV (int [][] arr) {
int rows = arr.length;
int cols = arr[0].length;
int [][] reflected = new int[rows][cols];
for (int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++) {
reflected [i][j] = arr[i][cols-j-1];
}
}
//go through arr and reverse values in each row
return reflected;
}
public static int [][] reflectH (int [][] arr) {
int rows = arr.length;
int cols = arr[0].length;
int [][] reflected = new int[rows][cols];
for (int i = 0; i < cols; i++){
for(int j = 0; j < rows; j++) {
reflected [j][i] = arr[cols-j-1][i];
}
}
//go through arr and reverse values in each row
return reflected;
}
}
This should be the solution:
public static int[][] replicate(double num1, double num2, int[][]arr) {
double length = num1 * arr.length;
double height = num2 * arr[0].length;
int[][]newArr = new int[(int) length][(int) height];
for(int i = 0; i < newArr.length; i++){
for(int j = 0; j < newArr[i].length; j++){
newArr[i][j]=arr[i % arr.length][j % arr[0].length];
}
}
return newArr;
}
Test input:
1 2 3
4 5 6
7 8 9
The method calculates the output array as follows (num1=1.8d and num2=1.8d):
1 2 3 1 2
4 5 6 4 5
7 8 9 7 8
1 2 3 1 2
4 5 6 4 5
Please note that I have changed the signature of the method. It now returns the resulting array.
I have this example matrix:
[4,1,3]
[2,1,3]
[4,-1,6]
and i want to solve exuotions:
4x1+1x2+3x3=v
2x1+1x2+2x3=v
4x1-1x2+6x3=v
x1+x2+x3=1
it will be: 4x1+1x2+3x3 = 2x1+1x2+2x3 = 4x1-1x2+6x3
-2x1+x2-5x3 =0
and I use the code:
import java.util.*;
public class GaussianElimination {
// This is the problem we solved in class
private static double[][] problem1 = {
// x = 1, y = 2, z = 3
{ 1, 2, 3, 14 }, // 1x + 2y + 3z = 14
{ 1, -1, 1, 2 }, // 1x - 1y + 1z = 2
{ 4, -2, 1, 3 } // 4x - 2y + 1z = 3
};
public static void solve(double[][] c, int row) {
int rows = c.length;
int cols = rows + 1;
// 1. set c[row][row] equal to 1
double factor = c[row][row];
for (int col=0; col<cols; col++)
c[row][col] /= factor;
// 2. set c[row][row2] equal to 0
for (int row2=0; row2<rows; row2++)
if (row2 != row) {
factor = -c[row2][row];
for (int col=0; col<cols; col++)
c[row2][col] += factor * c[row][col];
}
}
public static void solve(double[][] c) {
int rows = c.length;
for (int row=0; row<rows; row++)
solve(c,row);
}
public static void print(double[][] c) {
int rows = c.length;
int cols = rows + 1;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++)
System.out.printf("%5.1f ",c[row][col]);
System.out.println();
}
System.out.println();
}
public static void printSolution(double[][] c) {
int rows = c.length, cols = rows + 1;
char variable = (char)((rows > 3) ? ('z' - (rows-1)) : 'x');
System.out.println("Solution:\n");
for (int row=0; row<rows; row++)
System.out.printf(" %c = %1.1f\n",(char)variable++,c[row][cols-1]);
System.out.println();
}
public static void doProblem(double[][] problem, String description) {
System.out.printf("******* %s ********\n",description);
System.out.println("Original Equations:");
print(problem);
solve(problem);
System.out.println("Solved (reduced row echelon form):");
print(problem);
printSolution(problem);
}
public static void main(String[] args) {
doProblem(problem1,"Problem 1 (from class)");
}
}
How do I set the matrix in private static double[][] problem1 so that I get x1,x2,x3?
I don't really understand your question or problem. However I see some bugs in the row reduction echelon form solving method. I recently wrote this method as well. Mine works. Since I don't suspect this to be a Java homework assignment but rather an interest in programming mathematical algorithms, I will just throw in my code. I recommend taking a look at how the rref method is actually defined in the world of maths.
The bug I spotted is that the factor you use is wrong. Take a look at my code (note that it doesn't put zero rows to the bottom of the matrix):
public static double[][] rref(double[][] mat)
{
double[][] rref = new double[mat.length][mat[0].length];
/* Copy matrix */
for (int r = 0; r < rref.length; ++r)
{
for (int c = 0; c < rref[r].length; ++c)
{
rref[r][c] = mat[r][c];
}
}
for (int p = 0; p < rref.length; ++p)
{
/* Make this pivot 1 */
double pv = rref[p][p];
if (pv != 0)
{
double pvInv = 1.0 / pv;
for (int i = 0; i < rref[p].length; ++i)
{
rref[p][i] *= pvInv;
}
}
/* Make other rows zero */
for (int r = 0; r < rref.length; ++r)
{
if (r != p)
{
double f = rref[r][p];
for (int i = 0; i < rref[r].length; ++i)
{
rref[r][i] -= f * rref[p][i];
}
}
}
}
return rref;
}
The following code adapted from Rosettacode.org takes into account moving rows up/down as well:
static public void rref(double [][] m)
{
int lead = 0;
int rowCount = m.length;
int colCount = m[0].length;
int i;
boolean quit = false;
for(int row = 0; row < rowCount && !quit; row++)
{
print(m);
println();
if(colCount <= lead)
{
quit = true;
break;
}
i=row;
while(!quit && m[i][lead] == 0)
{
i++;
if(rowCount == i)
{
i=row;
lead++;
if(colCount == lead)
{
quit = true;
break;
}
}
}
if(!quit)
{
swapRows(m, i, row);
if(m[row][lead] != 0)
multiplyRow(m, row, 1.0f / m[row][lead]);
for(i = 0; i < rowCount; i++)
{
if(i != row)
subtractRows(m, m[i][lead], row, i);
}
}
}
}
// swaps two rows
static void swapRows(double [][] m, int row1, int row2)
{
double [] swap = new double[m[0].length];
for(int c1 = 0; c1 < m[0].length; c1++)
swap[c1] = m[row1][c1];
for(int c1 = 0; c1 < m[0].length; c1++)
{
m[row1][c1] = m[row2][c1];
m[row2][c1] = swap[c1];
}
}
static void multiplyRow(double [][] m, int row, double scalar)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[row][c1] *= scalar;
}
static void subtractRows(double [][] m, double scalar, int subtract_scalar_times_this_row, int from_this_row)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[from_this_row][c1] -= scalar * m[subtract_scalar_times_this_row][c1];
}
static public void print(double [][] matrix)
{
for(int c1 = 0; c1 < matrix.length; c1++)
{
System.out.print("[ ");
for(int c2 = 0; c2 < matrix[0].length-1; c2++)
System.out.print(matrix[c1][c2] + ", ");
System.out.println(matrix[c1][matrix[c1].length-1] + " ]");
}
}
static public void println()
{
System.out.println();
}