I have this matrix :
So 2 line and 2 columns.
1 2
3 4
I have the reading function
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
How can I make a border to a matrix? I've seen that in java there is no index -1.
I want a border with a number. For example :
0 0 0 0
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
How should I make that border function?
So, you need a (m+2) x (n+2) matrix:
// initialize m and n
...
// initialize the matrix with 0s
int a[][] = new int[m+2][n+2];
Then ignore the first elements (i and j should skip 0) and the last elements (i should skip m+1, j should skip n+1):
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
try {
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
}
First you need to create the matrix with extra rows and columns, for example in your case a 4x4 matrix. and them put 0 on the borders
when i==0 or i==n-1, j==0 or j==n-1,
int a[][] = new int[4][4];
int n,m;
n=4;
m=4;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0 || j==0 || i==m-1 || j==n-1){
//a[i][j] = 0;
a[i][j] = 1;
}
System.out.print(a[i][j]+" ");
}
System.out.println();
}
then
for (int i = 1; i < m-1; i++) {
for (int j = 1; j < n-1; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
Elaborating on my comment:
If you first put in words what creating a border means, then translating it from English to Java is a simple task.
Let's take a look at the the two matrices that you have given:
Original one:
1 2
3 4
With border:
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
We see that when creating a border, we increase the width and height of the matrix by 2 respectively (to have an empty row of 0s on the top-bottom, and left-right), so instead of a 2x2 matrix we now have 4x4, and the indices of the elements are incremented by 1 (every element is pushed one step to the right, and one step downwards).
Putting this is in code:
int[][] createBorder(int[][] matrix) {
//this is our 4x4 matrix
int[][] borderedMatrix = new int[matrix.length+2][matrix[0].length+2];
//fill the 4x4 matrix with 0's
for(int i = 0; i < borderedMatrix.length; i++) {
for(int j = 0; j < borderedMatrix[0].length; j++) {
borderedMatrix[i][j] = 0;
}
}
//copy the values of the 2x2 into the 4x4 matrix, but push them one step to the right, and one step downwards
for(int k = 0; k < matrix.length; k++) {
for(int l = 0; l < matrix[0].length; l++) {
borderedMatrix[k+1][l+1] = matrix[k][k];
}
}
return borderedMatrix;
}
The simplest way would be to create a matrix of n+1xm+1, populate the border with 0 then fill in the remainder with the original nxm matrix.
So if I had your example matrix
int[][] original = {{1, 2},
{3, 4}};
int borderWidth = original[0].length + 2;
int borderHeight = original.length + 2;
int borderArray = new int[borderHeight][borderWidth];
for (int i = 0; i < borderWidth; i++) { //border
borderArray[0][i] = 0; //populate top row
borderArray[borderHeight - 1][i] = 0; //populate bottom row
if (i == 0 || i == borderWidth - 1) { //populate left and right columns
for (j = 1; j < borderHeight - 1; j++) {
borderArray[j][i] = 0;
}
}
}
for (int i = 0; i < original.length; i++) { //populate middle with original
System.arraycopy(original[i], 0, borderArray[i+1], 1, original[].length);
}
Related
This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}
Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0
This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}
Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.
user input n number of rows in 2d array
Elements are stored in an array of size [n][4].
Input Format:
First line of the input is an integer “n” that denotes the number of rows.
Next n lines contain the elements of the row
Output Format:
if 2 rows match then separate it by hyphen
If no rows is same, print "None".
If the array size is negative, print "Invalid Input" and terminate the program.
Sample Input 1:
5
3 1 2 4
2 4 5 1
3 1 2 4
2 4 5 1
3 1 2 4
Sample Output 1:
1-3
1-5
2-4
3-5
Sample Input 2:
3
3 1 2 4
2 4 5 1
3 4 2 5
Sample Output 2:
None
Sample Input 3:
-5
Sample Output 3:
Invalid Input
i have tried the following code but it didnt work
import java.util.Arrays;
import java.util.Scanner;
import java.lang.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n <= 0)
{
System.out.println("Invalid Input");
}
else
{
int[][] data = new int[n][4];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 4; j++)
{
data[i][j] = sc.nextInt();
}
}
Object[] array = new Object[4];
Object[] array1 = new Object[4];
int idx = 0;
int idx1 = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 4; j++)
{
array[idx] = data[i][j];
array1[idx1] = data[i + 1][j];
idx++;
idx1++;
if (Arrays.deepEquals(array, array1))
{
System.out.println(i + "-" + j);
}
else
System.out.println("None");
}
}
} int[][] data = new int[n][4];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 4; j++)
{
data[i][j] = sc.nextInt();
}
}
Object[] array = new Object[4];
Object[] array1 = new Object[4];
int idx = 0;
int idx1 = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 4; j++)
{
array[idx] = data[i][j];
array1[idx1] = data[i + 1][j];
idx++;
idx1++;
if (Arrays.deepEquals(array, array1))
{
System.out.println(i + "-" + j);
}
else
System.out.println("None");
}
}
}}}
you are taking only the 1st elements in array and array1 in each step not the entire row.
what you need to do is you have to take entire 1 row and compare with the other rows more 'for' loops
I have game of life exercise, I wrote the whole game only remains for me to write the function that checks the cell and decides whether he lives or dies.
the code:
public class lifeGame1 {
public static void main(String[]args){
gameOfLife(4, 5, 0.3);
}
public static void gameOfLife(int n, int m, double p){
int[][] matrix = new int[n][n];
// Random each matrix[i][j]
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(Math.random() < p)
matrix[i][j] = 1;
else
matrix[i][j] = 0;
} // for j
} // for i
System.out.println("The board is: ");
printMatrix(matrix);
int steps = 0;
while(steps < m){
int[][] newMatrix = new int[n][n];
for(int i = 0; i < newMatrix.length; i++){
for(int j = 0; j < newMatrix[i].length; j++){
newMatrix[i][j] = checkTheNewValueOfCell(matrix, i, j);
}
}
matrix = newMatrix;
System.out.println("The new board: ");
printMatrix(matrix);
steps++;
} // while
}
public static void printMatrix(int[][] matrix){
// Random each matrix[i][j]
for(int i = 0; i < matrix.length; i++){ // for each row
for(int j = 0; j < matrix[i].length; j++){ // print one row
System.out.print(matrix[i][j] + " ");
} // for j
System.out.println();
} // for i
}
}
Cell can make the dead or make a life according to the following rules:
1. Live cell can become dead as a result of:
A. If it has a density of more than three live neighbors.
B. Solitude if it has fewer than two live neighbors.
Hence the cell life continues to be my life if and only if it has two or three live neighbors.
2 dead cell can turn the cheek if it has exactly three live neighbors.
While the volume chamber has five neighbors) if Angular three (but also for work the same rules.
Code that checks the cell:
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0;
for(int k = i-1; k <= i+1; k++){
for(int m = j-1; m <= j+1; m++){
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
} // for m
} // for k
if(matrix[i][j] == 1){ // pail
if(countActiveNeighbors == 2 || countActiveNeighbors == 3)
return 1;
else
return 0;
}else{ // savil
if(countActiveNeighbors == 3)
return 1;
else
return 0;
}
}
I was helped by a lecturer who register their function and indeed work, but I did not realize it until the end and it's really important for me to understand it.
I do not understand the loop Four run from i-1 to i + 1 and the loop Four which run from j-1 to j + 1.
If I am in the first cell so I should get an error that the i-1 is equal to -1 and it is beyond the scope of the array does not it?
Can help writing a simple function so we can understand it better?
thank's
You get an ArrayIndexOutOfBoundsException only when you try to ACCESS an non-valid array index. But in the nested for loops, you have the following if statements:
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום
if(k != i || m != j)
if(matrix[k][m] == 1)
countActiveNeighbors++;
} // if
the top if tests that k and m are within the matrix (they are both positive and less than the length/width of the matrix). The bottom if then actually accesses the array at index k,m. Since you check for valid indices before you access, you won't get an Exception
I've commented the function to try and make it clearer. Paired with my comment hopefully it helps you understand!
private static int checkTheNewValueOfCell(int[][] matrix, int i, int j) {
// check how much active neighbors
int countActiveNeighbors = 0; // Neighbor count starts at 0
for(int k = i-1; k <= i+1; k++){ // Loop from 1 before the cell to 1 after the cell
for(int m = j-1; m <= j+1; m++){ // Loop from 1 above the cell to 1 below it
if(k >= 0 && k < matrix.length && m >= 0 && m < matrix[0].length){ // אם בתחום // This if statement skips out of bounds in case we are on an edge cell
if(k != i || m != j) // This if statement skips the current cell we are looking at
if(matrix[k][m] == 1)
countActiveNeighbors++; // Finally we increment if we find a neighbor cell
} // if
} // for m
} // for k
I need a simple java program that can generate me the custom sets for a set,say for {'1','2','3','4'}. The result should be:
{'1','2'},{'2','3'},{'3','4'},{'1','2','3'},{'2','3','4'}.
I have tried codes for powerset,but the output isn't desirable. It would be appreciable if the code could be something like:
for(j=2;j<set.size()-1;j++)
{
for(i=0;i<set.size()-1;i++)
{
//a[i],a[i+1] when j=2
//a[i],a[i+1],a[i+2] when j=3
}
}
I know .size() is for ArrayList and a[i] is for simple array and i've written both as any approach will do!! Thanks In Advance!! :)
This code should print the values you want:
final int[] values = {1, 2, 3, 4};
for (int size = 2; size < values.length; size++) {
for (int i = 0; i + size <= values.length; i++) {
for (int j = 0; j <= size - 1; j++) {
System.out.print(values[i + j]);
}
System.out.println();
}
}
From the example, we see that you want to print sets of values whose length is greater than 1 and smaller than the total set, so that 's what the following line does:
for (int size = 2; size < values.length; size++) {
After that we compute the starting index of the subset, watching not to run into a IndexArrayOutOfBounds exception (see the line below)
for (int i = 0; i + size <= values.length; i++) {
From there we just print the values starting at i index and with the subset length of size
for (int j = 0; j <= size - 1; j++)
This is the sample code which is generating the desired result:
int[] array = { 1, 2, 3, 4 };
int size = 2;
for (int j = 0; j < array.length; j++) {
for (int i = 0; i <= array.length - size; i++) {
int[] temp = Arrays.copyOfRange(array, i, i + size);
for (int x : temp) {
System.out.print(x + ",");
}
System.out.println();
}
size++;
if (size == array.length) {
break;
}
}
Output:
1,2,
2,3,
3,4,
1,2,3,
2,3,4,
Above is the image of my application.i am build an application to do the alignment of two string.the two string will be compared and a 2d array will be populated.the values of the 2d array will be the values of the matrix.All works perfectly fine the only prob i ma having is that i want when it print the values of the matrix it prints it in a matrix format as it the example below instead of having an output of "0000000011011000002100013" i want it to display as this
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 1 0 2 1
0 1 0 1 3
When print out it has to see if the number of character printed is equal to my row size and then move to next line and continues to print until all matrix values has been displayed.Below are my pieces of my codes.thank you in advance
Code for my Compute matrix button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
match_reward = Integer.parseInt (match_tf.getText());
mismatch_penalty =Integer.parseInt (mismatch_tf.getText());
gap_cost=Integer.parseInt(gap_tf.getText());
build_matrix();
collumn_tf.setText(String.valueOf(max_col));
row_tf.setText(String.valueOf(max_row));
highest_score_tf.setText(String.valueOf(max_score));
StringBuilder sb = new StringBuilder();
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
}
matrix_tf.setText(sb.toString());
}
Code to build my matrix
private void build_matrix() {
String seq1 = sequence1_tf.getText();
String seq2 = sequence2_tf.getText();
int r, c, ins, sub, del;
rows = seq1.length();
cols = seq2.length();
matrix = new int [rows][cols];
// initiate first row
for (c = 0; c < cols; c++)
matrix[0][c] = 0;
// keep track of the maximum score
max_row = max_col = max_score = 0;
// calculates the similarity matrix (row-wise)
for (r = 1; r < rows; r++)
{
// initiate first column
matrix[r][0] = 0;
for (c = 1; c < cols; c++)
{
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));
// choose the greatest
matrix[r][c] = max (ins, sub, del, 0);
if (matrix[r][c] > max_score)
{
// keep track of the maximum score
max_score = matrix[r][c];
max_row = r; max_col = c;
}
}
}
}
Just append a \n newline after the inner loop:
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
sb.append('\n');
}