Iterate through a matrix with openJML - java

I have a class with a matrix initialized with all 0 and 1 in a specific position:
public class MatrixTest {
/*# spec_public #*/ int[][] griglia;
//#requires true;
//#ensures griglia[2][3] == 1;
public MatrixTest() {
griglia = new int[6][6];
for (int i=0; i < 6; i++) {
for (int j=0; j < 6; j++){
griglia[i][j] = 0;
}
}
griglia[2][3] = 1;
}
}
I would like to add an invariant to check that i always have only one 1 cell with a value of 1 and 35 cells with a value of 0. I tried doing that:
//# public invariant (\num_of int i, j; i >= 0 && i < 6 && j >= 0 && j < 6; griglia[i][j] == 1) == 1;
But it gives me invariant error just after the constructor. How can i iterate through a matrix to check a property?

After a lot of research, it seems like you can only do it with \forall, other commands didn't work for me.
\forall int i; i >= 0 && i < matrix.length; (\forall int j; j >= 0 && j < matrix[i].length; /* your check here */)
So, just don't use openJML if you are working with multi-dimensional arrays

Related

for loop that cycles between 0 and 1 in a 2D Array

I am currently making a chessboard and I need to assign every other cell with 1 or 0 with a double for loop.
My code looks like this:
(Processing / Java)
int[][] board = new int [8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = ?;
println(board[i][j]);
}
}
int[][] board = new int[8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = (j+i) % 2;
System.out.println(board[i][j]);
}
}
Looks like you're trying to assign color to a chessBoard.
0 - Black
1 - White
what you can do is,
if((i + j) % 2 == 0)
arr[i][j] = 0;
else
arr[i][j] = 1;

How can i validate the surroundings of a ship in Battleship game?

This is supposed to prevent ship edges from touching other ships, but for some reason it doesn't work. Specially for my T shaped ship.
I think this has to do with the condition in the for loops, probably the boat.getLength()+1 is not enough there, but i don't know what else to try.
My mainBoard length is 10x10 and the line and col parameters are supposed to be what we get from the user scanner. My board in its natural state is initialized with character '~'. Each boat when its positioned successfully it changes the '~' with the character appointed to that specific boat.
public boolean validateSurrounding(Boat boat, int line, int col) {
int i = line;
int j = col;
for (i = i - 1; i < boat.getLength()+1; i++) {
for (j = j - 1; j < boat.getLength()+1; j++) {
if (i < 0 || i >= mainBoard.length || j < 0 || j >= mainBoard[0].length) {
continue;
}
if (mainBoard[i][j] != '~') {
return false;
}
}
}
return true;
}
You are damaging your inner loop starting condition.
int i = line;
int j = col;
for (i = i - 1; i < boat.getLength()+1; i++) {
for (j = j - 1; j < boat.getLength()+1; j++) {
The second iteration of the outer loop, j will start at boat.getLength()+1, which is the last value it had during the outer loop's first execution.
Instead, use:
int i;
int j;
for (i = line - 1; i < boat.getLength()+1; i++) {
for (j = col - 1; j < boat.getLength()+1; j++) {

Specific cell test understanding the game of life Function

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

Add to ListArray from Array

For an array, how can i take all the values at even indexes and add to nameArray and all the values at odd indexes and add to scoreArray? I got this code but it isn't working.
String[] inputArray = {"john", "10", "frank", "14"}
for (int j = 0; j == inputArray.length; j++) {
if ((j % 2) == 0) {
nameArr.add(inputArray[j]);
} else {
scoreArr.add(inputArray[j]);
}
}
You probably mean for (int j = 0; j < inputArray.length; j++)
j == inputArray.length is evaluated to false at the first iteration so your loop doesn't run.
However, you could get rid of the if statement (assuming that your inputArray always contains a name associated a score, i.e always contains pair values) :
for (int j = 0; j < inputArray.length; j+=2) {
nameArr.add(inputArray[j]);
scoreArr.add(inputArray[j+1]);
}
Or you could also use a Map<String, Integer> to associate each name with its corresponding score (assuming names are unique) :
for (int j = 0; j < inputArray.length; j+=2)
m.put(inputArray[j], Integer.parseInt(inputArray[j+1]));
You probably mean to have a < in your loop and not a == and also, try using inputArray and not split2[] like this:
for (int j = 0; j < inputArray.length; j++) {
if ((j % 2) == 0) {
nameArr.add(inputArray[j]);
} else {
scoreArr.add(inputArray[j]);
}
}
What you want to do is look through each element in the array, to do this you want to go through every element starting at 0 and ending at the lengthof the array -1 (because arrays are 0 indexed). Once you are in the loop you want to check if it is an even or odd number using the modulo operator.
for (int j = 0; j < inputArray.length; j++){
if ((j % 2) == 0) {
nameArr.add(inputArray[j];
} else {
scoreArr.add(inputArray[j];
}
}

Big O notation O(NM) or (N^2)

I've been told the below code is = O(MN) however, I come up with O(N^2). Which is the correct answer and why?
My thought process:
nested for loops plus if statements --> (O(N^2)+O(1)) + (O(N^2)+O(1)) = O(N^2)
Thank you
public static void zeroOut(int[][] matrix) {
int[] row = new int[matrix.length];
int[] column = new int[matrix[0].length];
// Store the row and column index with value 0
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length;j++) {
if (matrix[i][j] == 0)
{
row[i] = 1;
column[j] = 1;
}
}
}
// Set arr[i][j] to 0 if either row i or column j has a 0
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
if ((row[i] == 1 || column[j] == 1)){
matrix[i][j] = 0;
}
}
}
}
What does M and N refers to? My assumption is that it refers to "rows" and "columns" respectively. If it is so, then the equation is O(MN) because you loop through M number of N times.
O(N^2) will be correct IF rows and columns are equal.

Categories