Insert a String of numbers into a matrix - java

I'm kind of stuck in this algorithm. I have this function below that gets a String and a matrix[n][m].
The String has up to n*m digits, and I need to insert them by reverse from the last digit to the last cell of the matrix, respectively, until I reach the first cell;
For example: the String='3' will be like that {[0][0],[0][3]}; the String='123' will be like that {[0][1],[2][3]}; and the String='2222' will be like that {[2][2],[2][2]};
The issue is: For the String '123' I get a matrix {[1][1],[1][1]}. It seems like only the first digit insert into the matrix.
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col]=integerNum;
}

Try this:
stringToInteger(String correctBase, int [][] board)
{
int integerNum;
int row = board.length - 1;
int col = board[0].length - 1;
for(int i=correctBase.length()-1; i>=0; i--)
{
integerNum=correctBase.charAt(i)-'0';
board[row][col]=integerNum;
col--;
if(col < 0) {
col = board[0].length - 1;
row--;
}
}
...
}

Yes, or:
int i = correctBase.length();
for(int row=board.length-1; row>=0; row--)
for(int col=board[row].length-1; col>=0; col--)
board[row][col] = i > 0 ? correctBase.get(--i)-'0' : 0;

I would first check if the size of the string matches the size of the matrix. If it does not, then pad said string with zeroes. Then just parse the positions of the string and insert them into the matrix.
Try it like this.
public static void main(String[] args) {
//define size of matrix
int n = 2;
int m = 2;
String input = "3";
//if size of string is less than matrix size we append 0 to it
if (input.length() < n * m) {
int diff = n * m - input.length();
for (int i = 0; i < diff; i++)
input = "0" + input; //pad zeroes to the string
}
int board[][] = new int[n][m]; //declare matrix
//populate matrix
int stringPosition = 0; //position in the string starting from the left
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] =
Character.getNumericValue(input.charAt(stringPosition)); //transfrom char to int, then assign it to matrix
stringPosition++; //increment position
}
}
//display matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.println("board[" + i + "][" + j + "] = " + board[i][j]);
}
}
}
It produces the desired results
input="3"
board[0][0] = 0
board[0][1] = 0
board[1][0] = 0
board[1][1] = 3
input="123"
board[0][0] = 0
board[0][1] = 1
board[1][0] = 2
board[1][1] = 3
input="2222"
board[0][0] = 2
board[0][1] = 2
board[1][0] = 2
board[1][1] = 2

Related

Is there a recursion that checks whether the matrix diagonally has a sequence of alphabetic letters

I got a homework assignment, I have to find a recursive function that gets a 2D matrix and the number of rows in a matrix and returns true / false If the diagonal of the matrix has a sequence of letters a b c,
Can not think of a solution
public static void main(String[] args) {
char[][] mat = new char[5][5];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++)
mat[i][j] = (char) (int) ((Math.random() * 26) + 'a');
}
for (int i=0 ; i <mat.length ; i++)
mat[i][i] = (char)('a' + i);
//mat[2][2] = 'b';
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println(isDiagonalLettersSequence(mat, mat.length));
}[Here are two examples that I hope will help me explain myself][1]
https://i.stack.imgur.com/Z6qmn.png
This is pretty simple. Just check on each iteration if the current value is equals to previous +1:
public static boolean isDiagonalHasSequence(char[][] matrix) {
return isDiagonalHasSequence(matrix, 0);
}
private static boolean isDiagonalHasSequence(char[][] matrix, int row) {
if (row > 0 && row < matrix.length) {
// check diagonal \
if (matrix[row][row] != matrix[row - 1][row - 1] + 1)
return false;
// check diagonal /
if (matrix[row][matrix.length - row - 1] != matrix[row - 1][matrix.length - row - 2] + 1)
return false;
}
return row == matrix.length || isDiagonalHasSequence(matrix, row + 1);
}
In the main function:
String[][] arr = { {"a","e","d"},
{"h","b","c"},
{"f","f","c"}};
if(diagonal(arr, 0).equals("abc"))
System.out.print("true");
And the global recursive function should be:
public static String diagonal(String[][] arr, int i) {
if(i == arr.length - 1)
return arr[i][i];
return arr[i][i] + diagonal(arr, i + 1);
}

Java - Select a number from every square in a 9x9 grid

I have a 9x9 sudoku grid and I need to get a random number from every 3x3 square in the grid.
The most awful code would be something like this:
if(square == 0) {
row = random.nextInt(3);
col = random.nextInt(3);
}
if(square == 1) {
row = random.nextInt(3);
col = random.nextInt(3) + 3;
}
if(square == 2) {
row = random.nextInt(3);
col = random.nextInt(3) + 6;
}
if(square == 3) {
row = random.nextInt(3) + 3;
col = random.nextInt(3);
}
if(square == 4) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 3;
}
if(square == 5) {
row = random.nextInt(3) + 3;
col = random.nextInt(3) + 6;
}
if(square == 6) {
row = random.nextInt(3) + 6;
col = random.nextInt(3);
}
if(square == 7) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 3;
}
if(square == 8) {
row = random.nextInt(3) + 6;
col = random.nextInt(3) + 6;
}
where square is the index of the square in the grid (square = 0,1,...,8)
I cannot figure out how to write it in a better way.
Some ideas? Thanks
This should work for any square size. In your case is 3x3, so size is 3.
int size = 3;
row = random.nextInt(size) + (square / size) * size;
col = random.nextInt(size) + (square % size) * size;
Something like this
int[] rowAdd = new int[] { 0, 0, 0, 3, 3, 3, 6, 6, 6 };
int[] colAdd = new int[] { 0, 3, 6, 0, 3, 6, 0, 3, 6 };
row = random.nextInt(3) + rowAdd[square];
col = random.nextInt(3) + colAdd[square];
Put in one array values which should be added to variable row, name it rowAdd. In second array colAdd put variable which should be added to col.
Finally, use square like the index to fetch correct value for addition.
Of course, arrays rowAdd and colAdd should be part of the method. (It is vast of time and memory to create new arrays every time when you call the method). These arrays should be class related, so they should be static.
This is the code for all things in once
public class Test {
public static void main(String[] args) {
//initializing arrays
int[][] grid = new int[9][9];
int[] numbers = new int[9];
//populating grid
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
grid[i][j] = (int)(Math.random()*10);
}
}
//printing grid
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
System.out.print(grid[i][j]);
}
System.out.println();
}
System.out.println();
int counter = 0;
//first and second loops counts for 0,3,6
for(int i = 0; i < 9; i += 3) {
for(int j = 0; j < 9; j += 3) {
//after taking i or j values(which must be either 0,3 or 6) goes for 3x3 parts and saving those numbers in number array
for(int t = i; t < i+3; t++) {
for(int k = j; k < j+3; k++) {
numbers[counter] = grid[t][k];
counter++;
}
}
//you can pick randomly from numbers array here
//showing which numbers picked
for(int t = 0; t < 9; t++) {
System.out.print(numbers[t]);
}
System.out.println();
System.out.println();
counter = 0;
}
}
}
}

Optimise the code to find max consecutive points in a straight line(row,column or diagonal) in a matrix

I need to find the maximum number of consecutive points in a straight line(row,column or diagonal) in a matrix .
For eg:- if it is a 4*4 matrix
input is (1#1,2#2,3#3,2#1) the answer should be 3 as the max consecutive points in diagonal is 3.
My code is successfully getting executed with expected results.But the code complexity is very high.
Can someone please suggest the best approach complexity wise.
Below is my code:
// Get the max number of Continuous points in a matrix row
private static int getMaxContinuousPointsInRow(boolean[][] matrix, int row){
int maxCount = 0;
int currCount = 0;
int pos = 0;
while(pos < matrix[row].length){
currCount = 0;
while(pos < matrix[row].length && !matrix[row][pos])
pos++;
if(pos >= matrix[row].length)
break;
while(pos < matrix[row].length && matrix[row][pos]){
currCount++;
pos++;
}
if(currCount > maxCount)
maxCount = currCount;
}
return maxCount;
}
// Get the max number of Continuous points in a matrix row
private static int getMaxContinuousPointsInCol(boolean[][] matrix, int col) {
int maxCount = 0;
int currCount = 0;
int pos = 0;
while (pos < matrix.length) {
currCount = 0;
while (pos < matrix.length && !matrix[pos][col])
pos++;
if(pos >= matrix.length)
break;
while (pos < matrix.length && matrix[pos][col]) {
currCount++;
pos++;
}
if (currCount > maxCount)
maxCount = currCount;
}
return maxCount;
}
// Get the max number of Continuous points in a matrix diagonal right starting from position (row,col)
private static int getMaxContinuousPointsInDiagonalRight(boolean[][] matrix, int row, int col) {
int maxCount = 0;
int currCount = 0;
int i = row, j = col;
while (i < matrix.length && j < matrix[row].length) {
currCount = 0;
while (i < matrix.length && j < matrix[row].length && !matrix[i][j]){
i++;
j++;
}
if(i >= matrix.length || j >= matrix[row].length)
break;
while (i < matrix.length && j < matrix[row].length && matrix[i][j]) {
currCount++;
i++;
j++;
}
if (currCount > maxCount)
maxCount = currCount;
}
return maxCount;
}
public static int function_called_by_main_method(int input1, int input2, String[] input3) {
// create a boolean matrix of size input1 x input2
// M[i][j] = true if input3 contains a point i#j, else M[i][j] = false
boolean M[][] = new boolean[input1 + 1][input2 + 1];
// initialize the matrix with all false values
for(int i=0; i <= input1; i++){
for(int j=0; j <= input2; j++){
M[i][j] = false;
}
}
// process each value in input3 and populate the matrix
for (String s : input3) {
// extract row, column value
String[] data = s.split("#");
int i = Integer.parseInt(data[0]);
int j = Integer.parseInt(data[1]);
M[i][j] = true;
}
// get max number of Continuous points among all matrix rows
int max = 0;
for(int row = 0; row <= input1; row++){
int rowMax = getMaxContinuousPointsInRow(M, row);
if(rowMax > max)
max = rowMax;
}
// get max number of Continuous points among all matrix rows and columns
for (int col = 0; col <= input2; col++) {
int colMax = getMaxContinuousPointsInCol(M, col);
if (colMax > max)
max = colMax;
}
// get max number of Continuous points among all matrix rows, columns and right diagonals
for(int col = input2 ; col >= 0; col--){
int diagMax = getMaxContinuousPointsInDiagonalRight(M, 0, col);
if(diagMax > max)
max = diagMax;
}
for(int row = 1 ; row <= input1; row++){
int diagMax = getMaxContinuousPointsInDiagonalRight(M, row, 0);
if(diagMax > max)
max = diagMax;
}
return max;
}
You could try parallelism with the java 8 streams, on a dumb brute force approach.
class Coord {
int i;
int j;
}
List<Coord[]> allLineCoords = calculateLinesForMatrix(rows, columns);
Comparator<Coord[]> comparator = (coords1, coords2) ->
length(matrix, coords1) - length(matrix, coords2);
Coord[] maxCoords = allLineCoords.parallelStream()
.max(comparator);
// or for just the max length:
int maxLength = (int) allLineCoords.parallelStream()
.mapToInt(coords -> length(matrix, coords))
.max();
Very unsatisfying is the missing intelligence. And the parallelism only scales to the number of cores of your computer.

Bubble-Sort 2D array

I need to build a code that bubble sort 2D array. The trick here is that I cannot use an one dimensional array helper, or move the items to another array.
The sorting need to be on the 2D array.
Now I built my function. But something is going wrong. This is my output
1 1 2 6 12 32
49 44 54 55 100 344
is to close to be done, and I cant think how to do it.
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}
Try
public static int [] [] sortMatrix(int[][]matrix){
// for loop of matrix rows: -
for(int x = 0 ; x < matrix.length; x++){
// for loop of matrix columens: -
for(int i =0; i < matrix[x].length; i++){
// for loop of comparison and swapping
for(int t = 0; t < matrix[x].length - i - 1; t++){
if(matrix[x][t] > matrix[x][t+1]){
// Swapping operation: -
int temp = matrix[x][t];
matrix[x][t] = matrix[x][t+1];
matrix[x][t+1] = temp;
}
}
}
}
return matrix;
}
instead of
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}
Below is the code for sorting 2D array, trick is that you have to think of the 2D array as one dimensional array and then derive the appropriate row, offset pairs for indices.
import java.util.Arrays;
public class Bubble2DSort {
public static void main(String[] args) {
System.out.println("Started");
int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};
sortMatrix(matrix);
System.out.println("Printing output ");
for(int[] rowArr : matrix) {
System.out.println(Arrays.toString(rowArr));
}
}
private static void sortMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int totalCount = row * col;
System.out.println("totalCount : " +totalCount);
boolean noSwaps = false;
for(int i = 0; !noSwaps; i++) {
noSwaps = true;
for(int j = 1; j < totalCount - i; j++) {
int currentRow = (j-1) / col;
int currentOffset = (j-1) % col;
int nextRow = j / col;
int nextOffset = j % col;
if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
//swapping
int temp = matrix[nextRow][nextOffset];
matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
matrix[currentRow][currentOffset] = temp;
noSwaps = false;
}
}
}
}
}
Output:
Started
totalCount : 12
Printing output
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]

Traversing a 2D array matrix diagonally from bottom left to upper right

I have a 3x4 matrix represented by a 2D array:
. 0 1 2 3
0 a c f i
1 b e h k
2 d g j l
and my approach to traverse the diagonal slice was to treat each slice as a sum, like this:
a = (0+0) = 0
b,c = (0+1),(1+0) = 1
d,e,f = (0+2),(1+1),(2+0) = 2
g,h,i = (1+2),(2+1),(3+0) = 3
j, k = (2+2),(3+1) = 4
l = (3+2) = 5
However, my code right now prints it in the opposite way that I want it to, which is from upper right to bottom left.
Current Output is:
acbfedihgkjl
Desired Output is:
abcdefghijkl
for (int sum = 0; sum <= numRows + numColumns - 2; sum++) {
for (int i = 0; i < numRows; i++) {
int j = sum - i;
if ((i >= 0 && i < numRows) && (j >= 0 && j < numColumns)) {
System.out.print(array[i][j]);
}
}
}
Can somebody point me in the right direction on how to fix my code to get the output that I want?
While it isn't very pretty, I think this will do it:
int i = 0;
int j = 0;
while (true) {
System.out.println("" + array[i][j]);
--i;
++j;
if (i < 0) {
if (j == numCols)
break;
i = Math.min(j, numRows - 1);
j = Math.max(j - numCols + 2, 0);
} else if (j >= numCols) {
if (i == numRows - 2)
break;
i = numRows - 1;
j = Math.max(j + 2 - numCols + i, 0);
}
}
int i = 0;
int j = 0;
int n = 0;
int x = 3;
int y = 4;
int newSize = Math.max(x,y) * Math.max(x,y);
while(n < newSize){
if(i <= x && j <= y)
System.out.println(array[i][j]);
n++;
if(i == 0) {
i = n:
j = 0;
} else {
--i;
++j;
}
}

Categories

Resources