I'm trying to erase every X in a .txt file. When a coordinate is chosen, if it is an X is should be replaced with a 0 then also every X that is touching it (except diagonally) should be replaced until there are no more X's that can be touched. I'm not getting these results with my current code.
I'm getting this error java.lang.ArrayIndexOutOfBoundsException: 9 when I input in 0 for getCoord(grid.length, "row") and 2 for getCoord(grid[0].length, "column") in main().
thank you for your help.
image1.txt
00X000000
0XXXXXXX0
0X00000XX
0X0X000XX
0X00000X0
0XXXXXXX0
XXXX00XX0
000XX0000
eraseImage.java
import java.io.*;
import java.util.StringTokenizer;
/**
* eraseImage.java
*
* Your Name Goes Here!
*
* will dimension and load a 2-dimensional array of Strings
* from a text file. The first line of the file will contain
* the dimensions of the grid. Each additional line will have
* String made up of 'X's and '0's (that's zeros) to represent
* part of an image (X) or a non-image cell(0).
*/
public class eraseImage
{
public static void main(String[] args) throws IOException
{
String[][] grid = load();
display(grid);
do
{
int targetRow = getCoord(grid.length, "row");
int targetCol = getCoord(grid[0].length, "column");
rubOut(grid, targetRow, targetCol);
display(grid);
}
while(again());
}
/**
* Please provide documentation here
*/
public static String[][] load() throws IOException
{
BufferedReader innie = new BufferedReader(new FileReader("/Users/laxgoalie1996/Desktop/image1.txt"));
String str = innie.readLine();
StringTokenizer tokens = new StringTokenizer(str);
int rows = Integer.parseInt(tokens.nextToken());
int cols = Integer.parseInt(tokens.nextToken());
String[][] image = new String[rows][cols];
for(int row = 0; row < rows; row++)
{
str = innie.readLine();
for(int col = 0; col < str.length(); col++)
image[row][col] = str.substring(col, col+1);
System.out.println(str);
}
return image;
}
/**
* Please provide documentation here
*/
public static void display(String[][] g)
{
System.out.println("\nHere is the current image...\n");
for (int row = 0; row < g.length; row++) {
for (int column = 0; column < g[row].length; column++) {
System.out.print(g[row][column] + " ");}
System.out.println();}
System.out.println();
}
/**
* Please provide documentation here
*/
public static void rubOut(String[][] g, int tRow, int tCol)
{
String str = g[tRow][tCol];
System.out.println(str);
if(str.equals("0"))
return;
g[tRow][tCol] = "0";
rubOut(g, tRow, tCol + 1);
rubOut(g, tRow, tCol - 1);
rubOut(g, tRow + 1, tCol);
rubOut(g, tRow - 1, tCol);
return;
}
/**
* Please provide documentation here
*/
public static int getCoord(int max, String prompt)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.print("Enter the " + prompt + " number (0 to " + (max-1) + ") -> ");
int coord = scan.nextInt();
while(coord < 0 || coord >= max)
{
System.out.print("HEY! The " + prompt + " number needs to be between 0 and " + (max-1) + " -> ");
coord = scan.nextInt();
}
return coord;
}
/**
* Please provide documentation here
*/
public static boolean again()
{
return false;
}
}
You need to add bounds checks to your rubOut function:
public static void rubOut(String[][] g, int tRow, int tCol)
{
if((tRow < 0) || (tRow >= g.length))
return;
if((tCol < 0) || (tCol >= g[tRow].length))
return;
...
}
Even though your initial indices of row = 0 and column = 2 are within bounds, you are going to go out of bounds when you call rubOut(g, tRow - 1, tCol); because tRow will then be -1.
Use this for loop for replace X over 0
public static void main(String [] args){
String[][] str ={{"0","0","X","0","0","0","0","0","0"},
{"0","X","X","X","X","X","X","X","0"},{"0","X","0","0","0","0","0","X","X"},
{"0","X","0","X","0","0","0","X","X"},{"0","X","0","0","0","0","0","X","0"},};
for (int i=0; i<str.length; i++) {
for(int j=0; j<str[i].length; j++){
System.out.print(str[i][j]);
}
System.out.println();
}
System.out.println();
for (int i=0; i<str.length; i++) {
for(int j=0; j<str[0].length; j++){
if(i==j){
str[i][j]="0";
}
System.out.print(str[i][j]);
}
System.out.println();
}
}
This will replace X over 0
Related
First post here, thanks in advance for any help.
I have made a 10*10 grid in Java and am trying to get the row numbers to appear on the left side of the grid, after many attempts at different print formats and options I am now here for a little help. Any pointers will be greatly appreciated.
public class ArrayTest {
public final static int SIZE =10;
final static char[][] GRID = new char[SIZE][SIZE];
public static void main(String[] args){
setGrid();
printGrid();
}
public static void setGrid(){
for( int row = 0; row< SIZE;row++){
for(int column = 0; column<SIZE; column++){
GRID[row][column]= ' ';
}
}
}
public static void printGrid(){
System.out.println(" 10 x 10 Grid");
System.out.println(" 0 1 2 3 4 5 6 7 8 9");
System.out.println(" +---+---+---+---+---+---+---+---+---+---+");
for(int row = 0; row< SIZE; row++){
for(int column = 0; column<SIZE; column++){
System.out.print(" |" + GRID[row][column] + "");
}
System.out.println(" | " + row );
System.out.println(" +---+---+---+---+---+---+---+---+---+---+");
}
}
}
for(int row = 0; row< SIZE; row++){
System.out.print( " " + row + " | ");
for ( int column = 0; column<SIZE; column++){
... <print column values for this row here>
}
System.out.println("");
}
Don't forget to add extra spaces when you print out the column numbers at the top, to account for the space used up by the row number indicators.
Your algorithm is a good point to start. Anyway I would like to broaden your perspective on extended use-cases and the usage of existing (reliable and customizable) text-based tabular-formatting libraries.
Use this extended solution and optimize
It is based on your approach. I added following features:
customizable grid-size (width, height as parameters)
utility functions: padRight, padLeft, repeatChar
You can further optimize that, for example:
left or right alignment of headers/data
calculation of the maximum cell-space need (max length of grid-data)
Source (minimal Java 8 streaming used)
Find source below or online where you can test & download on Ideone.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class GridDataToTextTable {
public static final int WIDTH = 10;
public static final int HEIGHT = 10;
public static void main(String[] args) {
System.out.printf("%d x %d Grid%n", WIDTH, HEIGHT);
String[][] generateGrid = generateGrid(WIDTH, HEIGHT);
printGrid(WIDTH, HEIGHT, generateGrid);
}
public static String[][] generateGrid(int width, int height) {
String[][] gridData = new String[height][width];
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
gridData[row][column] = " ";
}
}
return gridData;
}
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
public static String repeatChar(char c, int n) {
return IntStream.range(0, n).mapToObj(i -> String.valueOf(c)).collect(Collectors.joining(""));
}
public static void printGrid(int width, int height, String[][] gridData) {
int lengthOfMaxRowNum = String.valueOf(height - 1).length();
// TODO: can be calculated as max length over Strings in gridData
int maxCellWidth = 4;
System.out.print(padRight(" ", lengthOfMaxRowNum));
for (int column = 0; column < width; column++) {
System.out.print(padLeft(String.valueOf(column), maxCellWidth + 1));
}
System.out.println();
printHorizontalLine(width, lengthOfMaxRowNum, maxCellWidth);
System.out.println();
for (int row = 0; row < height; row++) {
// TODO: alignment of headers (col-numbers) could be customizable
System.out.print(padLeft(String.valueOf(row), lengthOfMaxRowNum));
for (int column = 0; column < width; column++) {
// TODO: alignment of cell-data could be customizable
System.out.print("|" + padLeft(gridData[row][column], maxCellWidth));
}
System.out.println("|");
printHorizontalLine(width, lengthOfMaxRowNum, maxCellWidth);
System.out.println();
}
}
private static void printHorizontalLine(int width, int lengthOfMaxRowNum, int maxCellWidth) {
String line = repeatChar('-', maxCellWidth);
System.out.print(padLeft(" ", lengthOfMaxRowNum));
for (int column = 0; column < width; column++) {
System.out.printf("+" + line);
}
System.out.printf("+");
}
}
Use Text-Formatting libraries
To print out data text-based in tabular or grid format see this answer.
Maybe you can use one of following libraries:
Java Text Tables library from iNamik's GitHub project
WAGU data-in-table-view library from thedathoudarya's GitHub project
I have this assignment for my university https://cs1331.gitlab.io/fall2018/hw2/hw2-source-model.html. I wrote the code but when I run the program I get this message at the console :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 2
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3107)
at java.base/java.lang.String.substring(String.java:1873)
at homework1.SourceModel.main(SourceModel.java:127)
Here is my code for this assignment with comments :
package homework1;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SourceModel {
//initialize variables so they can be accessed everywhere
private String modelName;
private int[][] characterCount;
private double[] rowCount;
private double[][] probability;
/**
*
* #param name takes the name of the corpus
* #param fileName takes the filesName of corpus
*/
public SourceModel(String name, String fileName) {
modelName = name;
characterCount = new int[26][26];
rowCount = new double[26];
probability = new double[26][26];
System.out.println("Training " + name + "model...");
try {
Scanner scan = new Scanner(new File(fileName));
String temp = "";
//append all of the text
while (scan.hasNext()) {
temp += scan.next();
}
//only keeps the letters and makes them lowercase
temp = temp.replaceAll("[^A-Za-z]+", "").toLowerCase();
System.out.println(temp);
//iterates trough each letter then puts the letters
//sequence to the respective row and column
for (int i = 0; i < (temp.length() - 1); i++) {
char firstLetter = temp.charAt(i);
char secondLetter = temp.charAt(i + 1);
//index based on ASCII values
characterCount[(int) firstLetter - 97][(int) secondLetter - 97]++;
rowCount[(int) firstLetter - 97]++;
}
//calculates the probability by dividing the count
//by the total counts in each row
for (int i = 0; i < probability.length; i++) {
for (int j = 0; j < probability[i].length; j++) {
if (rowCount[i] == 0) {
rowCount[i] = 0.01;
}
probability[i][j] = (((double) characterCount[i][j]) / rowCount[i]);
if (probability[i][j] == 0) {
probability[i][j] = 0.01;
}
}
}
System.out.println("done");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
*
* #return a string which contains the name
*/
public String getName() {
return modelName;
}
/**
* #return a string with the matrix
*/
public String toString() {
String matrix = "";
matrix += "";
for (int i = 97; i < 123; i++) {
matrix += " ";
matrix += (char) i;
}
matrix += ("\n");
for (int i = 0; i < probability.length; i++) {
matrix += ((char) (i + 97) + " ");
for (int j = 0; j < probability[i].length; j++) {
matrix += String.format("%.2f", probability[i][j]);
matrix += ("");
}
matrix += "\n";
}
return matrix;
}
/**
*
* #param test a set of letters to test
* #return the probability for the word
*/
public double probability(String test) {
test = test.replaceAll("[^A-Za-z]+", "").toLowerCase();
double stringProbability = 1.0;
for (int i = 0; i < test.length() - 1; i++) {
int firstIndex = (int) (test.charAt(i)) - 97;
int secondIndex = (int) (test.charAt(i + 1)) - 97;
stringProbability *= probability[firstIndex][secondIndex];
}
return stringProbability;
}
/**
*
* #param args the command line arguments
*/
public static void main(String[] args) {
SourceModel[] models = new SourceModel[args.length - 1];
for (int i = 0; i < args.length - 1; i++) {
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
}
System.out.println("Analyzing: " + args[args.length - 1]);
double[] normalizedProbability = new double[args.length - 1];
double sumProbability = 0;
for (int i = 0; i < args.length - 1; i++) {
sumProbability += models[i].probability(args[args.length - 1]);
}
//normalize the probability in respect to the values given
for (int i = 0; i < normalizedProbability.length; i++) {
normalizedProbability[i] = models[i].probability(args[args.length - 1]) / sumProbability;
}
int highestIndex = 0;
for (int i = 0; i < args.length - 1; i++) {
System.out.print("Probability that test string is");
System.out.printf("%9s: ", models[i].getName());
System.out.printf("%.2f", normalizedProbability[i]);
System.out.println("");
if (normalizedProbability[i] > normalizedProbability[highestIndex]) {
highestIndex = i;
}
}
System.out.println("Test string is most likely " + models[highestIndex].getName() + ".");
}
}
Others have already pointed this out, but for this line:
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
the substring method is apparently causing the problem because indexOf returns -1 if the . isn't found.
In this case, though, the code actually isn't the problem, since the assignment states that you can assume that the file names are of the form <source-name>.corpus. That being said, really, all of the command line parameters should have a . in them, so this shouldn't be happening.
I'd check to see what command line parameters you're passing. One guess I have is that you might have a file name with a space in it or something. For example, if you passed English GB.corpus, then this would show up as 2 separate arguments (one of which doesn't have a .).
Edit: As #Pshemo pointed out in the comments, if you have a file name that has a space in it, you can just put it in quotes so that it'll be interpreted as a single command line parameter - for example, instead of English GB.corpus, write "English GB.corpus". That'll prevent the exception.
In your main method, you have:
args[i].indexOf(".")
The dot (.) is not found so it returns -1.
You try to create a substring:
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
But since args[i].indexOf(".") is invalid, it throws an exception.
What you can do is check if the dot (.) exists, if yes continue:
if(args[i].contains(".")){
models[i] = new SourceModel(args[i].substring(0, args[i].indexOf(".")), args[i]);
}
I need to fill a 2D Array with numbers between 2 and 6, given by the user (is just part of a bigger proyect) but when I give the number I only get another request for a number.
public static int[][] crearTablero(int tamaño)
{
int[][] tablero = new int[tamaño][tamaño];
return tablero;
}
public static void imprimeTablero(int[][] tablero)
{
for(int i = 0; i<tablero.length; i++)
{
for(int j = 0; j<tablero[i].length; j++)
{
System.out.print(tablero[i][j] + " ");
}
System.out.println();
}
}
public static void swap(int[][] tablero, int x1, int y1, int x2, int y2)
{
int temp = tablero[x1][y1];
tablero[x1][y1] = tablero[x2][y2];
tablero[x2][y2] = temp;
}
public static void rellenarTablero(int[][] tablero) {
for (int x = 0; x < tablero.length; x++) {
for (int y = 0; y < tablero[x].length; y++) {
tablero[x][y] = aleatorio(numeroColores());
}
}
}
public static void shuffleBoard(int[][] tablero)
{
Random rnd = new Random();
int randX = 0;
for(int x = 0; x<tablero.length; x++)
{
randX = rnd.nextInt(tablero.length);
int[] temp = tablero[x];
tablero[x] = tablero[randX];
tablero[randX] = temp;
}
}
public static int numeroColores(){
int colores = 0;
System.out.print("Numero de colores (entre 2 y 6): ");
Scanner scn = new Scanner(System.in);
colores = scn.nextInt();
while(colores < 2 || colores > 6)
{
System.out.println("Invalid matrix size. Re-enter ");
}
return colores;
}
public static int aleatorio(int colores) {
int l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
return l;
}
I would really appreciate some help because I don't know how to continue, Thanks.
You call numeroColores() in a for-loop in a for-loop, so you are of course asked multiple times for it.
Btw. you have an endless loop if you type in 1 or smaller or 7 or bigger with constantly getting the same line printed out and not asking for new input
Try this code to generate the random value between 2 and 6
public static int aleatorio(int colores) {
int l = 0;
while(l < 2 || l > 6) {
l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
}
return l;
}
I am currently looking for a way of scanning a 2D matrix in Java for a number. Precisely, if in my matrix, there are numbers from 0 to 9, how do I "locate" the 0? This is intended for creating a Minesweeper game.
Here is what I have written so far. It is not complete. All I want is a clue on how to complete it.
class DemineurStackOverflow {
public static void minesweeper () {
int champDeMine[][];
boolean résultat[][];
int mine;
char réponse;
champDeMine = new int[longueur][largeur]; //Differenf from the matrix "champDeMines" from the second method
Arrays.asList(champDeMine).contains(0);
mine = (int) Math.floor(Math.random()*nbMines + 1);
System.out.println("Ajustement du nombre de mines en cours...");
if (mine < nbMines) {
for (mine = (int) Math.floor(Math.random()*nbMines + 1); mine < nbMines; mine++);
} else {
for (mine = (int) Math.floor(Math.random()*nbMines + 1); mine > nbMines; mine--);
}
if (mine == nbMines){
System.out.println("Chargement des mines OK.");
}
}
public static int [][] calculeProximité ( boolean [][] champDeMines ){
int row; //row index for prescence of 0, same value as longueur
int col; //column index for presence of 0, same value as largeur
int mine;
champDeMines = new boolean[row][col];
if (champDeMines = 0) {
champDeMines = mine;
}
//Here I am trying to figure a way of finding the 0s in this champDeMines matrix.
return (new int[champDeMines.length][champDeMines[0].length]);
}
}
The first method consists in generating an array from variables "longueur" and "largeur". The number of "mines" is supposed to represent the number 0 (which is why I want to scan for a 0), at random places. The second method consists in finding the "mines" in the array created. That is what I have trouble doing. Do you have any clues for completing the second method? I am simply looking for clues because I am learning to program in Java!
Thank you very much, your help is most certainly appreciated!
This is how minesweeper field population could look from the code provided. I hope you get the clue from the comments and do not hesitate to ask if anything is unclear.
import java.util.Random;
public class Demineur
{
// Here come CONSTANTS
public static final int MAX_MINES = 30;
public static final boolean MINE = true;
// Let's have a field 12x12 size
public static final int LONGEUR = 12;
public static final int LARGEUR = 12;
// each field contains number of mines it has access to
public static int champDeMine[][] = new int[LONGEUR][LARGEUR];
// each field can contain mine or be empty
public static boolean champDeMines[][] = new boolean[LONGEUR][LARGEUR];
public static void minesweeper()
{
Random random = new Random();
int mine ;
System.out.println("Ajustement du nombre de mines en cours...");
int nbMines = random.nextInt(MAX_MINES);
/**
* Let's plant mines. :-E
* Unoptimal but will suffice for demonstration purpose.
*/
int minesLeftToPlant = nbMines;
int skip = 0;
boolean planted = false;
while (minesLeftToPlant > 0)
{
skip = random.nextInt(LONGEUR*LARGEUR);
planted = false;
while (!planted && minesLeftToPlant > 0 && skip > 0)
{
for (int y = 0; !planted && minesLeftToPlant > 0 && y < LONGEUR; y++)
{
for (int x = 0; !planted && minesLeftToPlant > 0 && x < LARGEUR; x++)
{
if ( !MINE == champDeMines[y][x]
&& 0 == skip)
{
champDeMines[y][x] = MINE;
minesLeftToPlant--;
planted = true;
}
else
{
skip--;
}
}
}
}
}
System.out.println("Chargement des "+ nbMines +" mines OK.");
}
public static void calculeProximite()
{
int row ; //row index for prescence of 0, same value as longueur
int col ; //column index for presence of 0, same value as largeur
int mine;
//Check for each field it's neighbors and calculate which of them are mines
for (row = 0; row < LONGEUR; row++)
{
for (col = 0; col < LARGEUR; col++)
{
champDeMine[row][col] = numberOfMines(row,col);
}
}
}
public static void printChampDeMine()
{
for (int row = 0; row < LONGEUR; row++)
{
for (int col = 0; col < LARGEUR; col++)
{
System.out.print("'" + champDeMine[row][col] + "' ");
}
System.out.println();
}
}
public static void printChampDemines()
{
for (int row = 0; row < LONGEUR; row++)
{
for (int col = 0; col < LARGEUR; col++)
{
System.out.print("'" + (champDeMines[row][col] ? "m" : "e") + "' ");
}
System.out.println();
}
}
public static int numberOfMines(int row, int col)
{
return add(hasMine(row , col + 1))
+ add(hasMine(row - 1, col + 1))
+ add(hasMine(row - 1, col ))
+ add(hasMine(row - 1, col - 1))
+ add(hasMine(row , col - 1))
+ add(hasMine(row + 1, col - 1))
+ add(hasMine(row + 1, col ))
+ add(hasMine(row + 1, col + 1));
}
public static boolean hasMine(int row, int col)
{
return row >= 0 && col >= 0 && row < LONGEUR && col < LARGEUR
&& isMine(champDeMines[row][col]);
}
public static boolean isMine(boolean x)
{
return MINE == x;
}
public static int add(boolean c)
{
return c ? 1 : 0;
}
public static void main(String[] args)
{
minesweeper();
System.out.println("Champ de mines");
printChampDemines();
System.out.println("Champ de mine");
calculeProximite();
printChampDeMine();
}
}
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}
This is what am producing so far:
6
3 5
9 7 1
4 6 8 4
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
Any help would be appreciated!
Here, just change with your solve()
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
#Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
Try
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
Simple-Solution:
1.Add the static list as here:
private static List maxRowVal=new ArrayList();
2.Replace your generateTriangle() function with this:
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
Simple indeed!!
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
Output:
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.