It is necessary to find the maximum element of the second row of the table and replace it with the sum of the elements of the second column, a cycle is written to find a larger element, how to make the second row, and replace it with the sum.
I will be grateful for any answer.
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Gravity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Number of rows in the table
private final int rows = 4;
// Number of columns in the table
private final int columns = 5;
// Array for working with table data
int[][] arr = new int[rows][columns];
// Declaring a table
TableLayout table;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
table = findViewById(R.id.tableLayout1);
// Filling the array with zeros
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = 0;
}
}
// Table layout options
table.setLayoutParams(new TableLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
table.setStretchAllColumns(true);
// Create a table
createTable(rows, columns, arr);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Save data on screen rotation
outState.putIntArray("matrix5x0", arr[0]);
outState.putIntArray("matrix5x1", arr[1]);
outState.putIntArray("matrix5x2", arr[2]);
outState.putIntArray("matrix5x3", arr[3]);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Returning data to an array
arr[0] = savedInstanceState.getIntArray("matrix5x0");
arr[1] = savedInstanceState.getIntArray("matrix5x1");
arr[2] = savedInstanceState.getIntArray("matrix5x2");
arr[3] = savedInstanceState.getIntArray("matrix5x3");
// Recreate the table
createTable(rows, columns, arr);
}
// Table creation method. Input values: number of rows, number of columns, two-dimensional array with data.
public void createTable(int rows, int columns, int[][] arr) {
// Delete previous entries when recreating
table.removeAllViews();
for (int i = 0; i < rows; i++) {
// String declaration
TableRow tableRow = new TableRow(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tableRow.setLayoutParams(params);
TableRow.LayoutParams param = new TableRow.LayoutParams();
for (int j = 0; j < columns; j++) {
// String object declaration
int randvalue = arr[i][j];
EditText value = new EditText(this);
// Set text to an object
value.setText(String.valueOf(randvalue));
value.setLayoutParams(param);
// Font size
value.setTextSize(18);
// Centered
value.setGravity(Gravity.CENTER);
// "table frame"
value.setBackgroundResource(R.drawable.back);
// Indentation
value.setPadding(5, 5, 5, 5);
// Adding an object to a string
tableRow.addView(value, j);
}
table.addView(tableRow, i);
}
}
public void fillRand(View v) {
// We fill the array with numbers from 0 to 100
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = (int) Math.round(Math.random() * 100);
}
}
// Recreating a table
createTable(rows, columns, arr);
}
public void solveArr(View v) {
// Write the values of the table to the array
for (int i = 0; i < table.getChildCount(); i++) {
TableRow row = (TableRow) table.getChildAt(i);
for (int j = 0; j < row.getChildCount(); j++) {
EditText value = (EditText) row.getChildAt(j);
try {
arr[i][j] = Integer.parseInt(value.getText().toString());
} catch (Exception e) {
// Output message on exception
Toast toast = Toast.makeText(getApplicationContext(), "Неправильно введенны данные!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
// Finding the maximum element of the table
int max, maxi = 0;
max = arr[0][0];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int cl = arr[i][j];
if (cl > max) {
max = cl;
maxi = i;
}
}
}
// If you maximize the element of the first column at the end, then increase all the elements of the column by 2 times
if (maxi == 3) {
for (int i = 0; i < rows; i++) {
arr[i][0] *= 2;
}
}
// recreate the table
createTable(rows, columns, arr);
}
}
Made the array sort only by rows
// Finding the maximum element of the table
//Made the array sort only by rows
int max, maxi = 0;
max = arr[0][0];
for (int i = 0; i < rows; i++) {
int cl = arr[i];
if (cl > max) {
max = cl;
maxi = i;
}
}
Related
I am trying to create an application class MatrixApplication, in which the user first enters the number of rows and columns of the matrix.
This will be used to create an array object.
Then the elements of the Matrix are called up row by row and column by column. When all elements have been read in, they are assigned to the matrix object.
Next, the array is transposed and finally the transposed array is displayed.
How do I assign the elements to the Matrix object?
How do I display a transposed array?
package domain;
public class Matrix {
private int[][] numbers;
public Matrix(int rows, int columns) {
setNumbers(numbers);
if (rows < 1)
rows = 1;
else
rows = rows;
if (columns < 1)
columns = 1;
else
columns = columns;
numbers = new int[rows][columns];
}
public final void setNumbers(int[][] numbers) {
this.numbers = numbers;
}
public int[][] getNumbers() {
return numbers;
}
public int[][] transpose() {
int[][] transpose = new int[numbers[0].length][numbers.length];
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < numbers[0].length; ++j) {
transpose[j][i] = numbers[i][j];
}
}
return transpose;
}
}
package ui;
import java.util.Scanner;
import domain.Matrix;
public class MatrixApplication {
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows of the matrix:");
int rows = input.nextInt();
System.out.print("nter the number of columns of the matrix:");
int colums = input.nextInt();
Matrix matrix = new Matrix(rows, colums);
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
}
System.out.printf("The transposed matrix: %d",matrix.transpose());
}
}
And if I want this form of transposed matrix:
example of a 4x2 array to a 2x4 array
Simply read the numbers into a two-dimensional array and call matrix.setNumbers.
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
matrix.setNumbers(numbers);
System.out.printf("The transposed matrix: %s", Arrays.deepToString(matrix.transpose()));
I have this array here that takes strings values this is my Puzzle Board View,
Right now everything works but the array is hard coded and i need the strings to be generated randomly from 0-4.
I have tried to get a random char and put it is as a string but this didn't work. Any tips would be nice.
Random rand = new Random();
char c = (char)(rand.nextInt(5) + '0');
StringBuilder sb = new StringBuilder();
sb.append(c);
String[] debug_board_state = new String[7];
debug_board_state[0] = "0,3,0,0,3,0,2";
debug_board_state[1] = "1,0,2,0,0,1,2";
debug_board_state[2] = "0,2,0,0,0,0,0";
debug_board_state[3] = "0,0,3,0,3,0,4";
debug_board_state[4] = "2,0,0,0,0,1,0";
debug_board_state[5] = "0,1,0,0,1,0,2";
debug_board_state[6] = "2,0,3,0,0,2,0";
UPDATE.
Thanks to user Answer i was able to get the random matrix, although i ran into another problem, I need do more stuff to the matrix so i don't want to print it out. here is the code
static private final int WIDTH_EASY = 7;
protected void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
};
for (int i = 0; i < WIDTH_EASY; ++i) {
StringTokenizer tokenizer = new StringTokenizer (debug_board_state[i][i], ",");
int column = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
getCurrentState().board_elements[i][column] = new BoardElement();
getCurrentState().board_elements[i][column].max_connecting_bridges = Integer.parseInt(token);
getCurrentState().board_elements[i][column].row = i;
getCurrentState().board_elements[i][column].col = column;
if (getCurrentState().board_elements[i][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[i][column].is_island = true;
}
++column;
}
}
}
The string Tokenizer works with 1d array but not with 2d, i need something that will do the same thing as StringTokenizer and apply it to the matrix. I am getting the following error
java.lang.NullPointerException: Attempt to read from field Island_and_Bridges.Hashi.BoardElement[][] Island_and_Bridges.Hashi.BoardState$State.board_elements on a null object reference
Although I think int[][] is a better idea, here is the String[][] solution. You can use String.valueOf(rand.nextInt(5)) to generate element in the matrix:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String[][] matrix = new String[7][7];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Update:
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
Something like this?
Pseudo-code:
String[][] debug_board_state = new String[7][7];
for (int x = 0; x < debug_board_state.size(); x++) {
for (int y = 0; y < debug_board_state[x].size(); y++) {
debug_board_state[x][y] = new_random_character();
}
}
0-4 lies from 49 to 52 on the ASCII scale:
Random rand = new Random();
char c = (char)(rand.nextInt(4)+49);
StringBuilder sb = new StringBuilder();
sb.append(c+'0');
Maybe, you want something like this:
public void initBoard() {
Random random = new Random();
String[][] board = new String[7][7];
for (int i=0; i < board.size(); i++) {
for (int j=0; j < board[].size(); j++) {
board[i][j] = String.valueOf(random.nextInt() % 5);
}
}
}
It will initialize your board with random number of String.
I want to swap Columns and Rows in a 2D array.
My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.
Id like to know how I can save the Variable oldField independent
public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
// a Field
int[][] oldField = pField.clone();
int[][] newField = pField.clone();
for (int i = 0; i < newField.length; i++) {
for (int j = (newField.length - 1); j >= 0; j--) {
newField[i][(newField.length - 1) - j] = oldField[j][i];
}
}
return newField;
}
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
this code solves your problem:
public class SwapRowsAndColumns {
public static void main(String[] args) {
int[][] someMatrix = new int[2][3];
someMatrix[0][0] = 1;
someMatrix[0][1] = 2;
someMatrix[0][2] = 3;
someMatrix[1][0] = 4;
someMatrix[1][1] = 5;
someMatrix[1][2] = 6;
printMatrix(someMatrix);
int[][] invertedMatrix = swapMatrix(someMatrix);
printMatrix(invertedMatrix);
}
private static int[][] swapMatrix(int[][] pField) {
int originalTotalRows = pField.length;
int originalTotalColumns = pField[0].length;
int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];
for(int i=0; i< originalTotalRows; i++){
for(int j=0; j < originalTotalColumns; j++){
newMatrix[j][i] = pField[i][j];
}
}
return newMatrix;
}
private static void printMatrix(int[][] matrix){
int totalRows = matrix.length;
int totalColumns = matrix[0].length;
for(int i=0; i< totalRows; i++){
for(int j=0; j< totalColumns; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
}
i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem.
Testmatrix.java
public class TestMatrix{
int rows;
int cols;
double data[][] = new double[4][4];
public TestMatrix() {
super();
rows=1; cols=1;
for(int i=0; i<=rows;i++)
{
for(int j=0; j<=cols;j++)
{
data[i][j] = 0.0;
}
}
}
public void print(){
for (int i = 0; i <data.length ; i++) {
for (int j = 0; j <data[0].length ; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
Here is the main class
Main.java
public class Main {
public static void main(String[] args){
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's)
Thanks in advance **
When you create an array, you set the size, for example new double[4][4] then that's already the size of this array, even tho you didn't insert anything in there. My point is that no matter if you insert 1 element, 2 elements, or 8 elements, that doesn't matter, inserting to array doesn't change it's size (property returned by length). Imagine a bag, you have a bag with a certain size, doesn't matter if you put items in there, size of a bag is gonna stay the same.
You declared your array as a 4x4 matrix. Line 4 should be double data[][] = new double[2][2]; in order to achieve what you seem to want.
Initializing array doesn't change the size of an array. If you want to print acording to new row and column size, change your print() method to:
public void print() {
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
Again, constructor name should be same as class name. But the constructor of TestMatrix is Matrix.
Note: Another important thing, you don't need to initialize the double array to 0.0. This array is by default initialized to 0.0 as this is an instance field of the class. According to Oracle:
Each class variable, instance variable, or array component is
initialized with a default value when it is created.
For type double, the default value is positive zero, that is, 0.0d.
Also, change your TestMatrix(int rows, int cols, double[] data) constructor to:
// declare with a large size
double data[][] = new double[80][80];
public TestMatrix(int rows, int cols, double[] data) {
super();
this.rows = rows;
this.cols = cols;
for (int i = 0, k = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[k++];
}
}
}
Better practice would be making the fields private and write getter and setter methods for those fields.
Either declare matrix to 2*2 as said by Chris
or change
for (int i = 0; i < data.length ; i++) {
for (int j = 0; j < data.length ; j++) {
to
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
If you want any size of matrix upto 4*4 use second solution.
You probably want something like this;
public class Matrix {
public final double[][] values;
public final int rows;
public final int cols;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols]; // Automatically 0.0.
}
public void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.printf(" %6f", values[i][j]);
}
System.out.println();
}
}
}
Matrix m = new Matrix(2, 2);
...
rows and cols are redundant, as you already used values.length, and values[0].length.
A few notes:
Use an IDE, your code did not even compile, this is the minimum
effort you should put into any problem.
Declaring the array as double data[][] = new double[4][4]; makes an array that is 4 "boxes" wide and 4 "boxes" tall. each box will hold a data of the type specified, in your case a double which you are setting to 0.0
public class TestMatrix
{
int rows;
int cols;
double data[][] = new double[2][2];
public TestMatrix()
{
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j <= cols; j++)
{
data[i][j] = 0.0;
}
}
}
public void print()
{
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[0].length; j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
In Addition to above answers
i'm getting 4x4 matrix( with all 0's)
If you wanna find difference replace the existing lines with below code
data[i][j] = 1.0;
System.out.print(data[i][j]+" ");
Hope you understand the reason for getting all the 0's
Your class should be like this:
public class Test {
int rows;
int cols;
double data[][] = new double[2][2];
public void print() {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
System.out.print(" "+data[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test m1 = new Test();
m1.print();
}
}
and this part you can delete. You do not need it. This is not an initialization.
public void matrix() {
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++) {
for (int j = 0; j <= cols; j++) {
data[i][j] = 0.0;
}
}
}
I am trying to make a 2D array that i can dynamically update. Lets say i have a 2D array with 10 rows and 3 columns. I want to add an int value to a specific row, thereby adding an extra column to that row (and only that row) so that it alone would have 4 columns. Here's what i have so far.
public class DynamicArray {
private int[][] array;
private int size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = 0;
}
public int get(int j) {
return array[0][j];
}
public int getSize() {
return size;
}
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else // need to create a bigger array
{
int[][] temp = new int[10][2 * size];
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
temp[i][j] = array[i][j];
temp[0][size] = N;
array = temp;
}
size = size + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2);
da.put(1);
da.put(3);
da.put(1);
da.put(4);
da.put(5);
for (int i = 0; i < da.getSize(); i++) {
for (int j = 0; j < 9; j++) {
System.out.print((da.get(i) + "\t"));
}
System.out.println("\n");
}
}
}
The problem is that with this code the program adds the new value to each row instead of only the one specified (in this case row 0).
How could I fix this?
Additionally, how could i make the program do the opposite as well -> remove a value from an individual row and shorten that row?
In case you just want to add the new element to the new array[0].
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size]; // Temporary create a new array with double size
// fill the empty array with array[0] existing elements
for (int i = 0; i < size; i++) {
temp[i] = array[0][i];
}
// Change the array[0] to point to the new array
array[0] = temp;
// Add the new element to the new array
array[0][size] = N;
}
size = size + 1;
}
In case you want to put to a specific row number and you should get that as an argument in the put method.
public void put(int N, int rowNum);
You should also change the size element to be a array which will track the size of each row.
int[] size = new int[10];
Accordingly change the size of the row only when that specific row that reached its limit.
Check the code below
public class DynamicArray {
private int[][] array;
private int[] size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = new int[10];
}
public int get(int rowNum, int colNum) {
return array[rowNum][colNum];
}
public int getSize(int rowNum) {
return size[rowNum];
}
public void put(int N, int rowNum) {
if (size[rowNum] < array[0].length)
array[rowNum][size[rowNum]] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size[rowNum]];
for (int i = 0; i < size[rowNum]; i++) {
temp[i] = array[rowNum][i];
}
array[0] = temp;
array[0][size[rowNum]] = N;
}
size[rowNum] = size[rowNum] + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2, 0);
da.put(1, 0);
da.put(3, 0);
da.put(1, 0);
da.put(4, 0);
da.put(5, 1);
da.put(2, 4);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < da.getSize(i); j++) {
System.out.print((da.get(i, j) + "\t"));
}
System.out.println("\n");
}
}
}