Generating all the possible configurations of a matrix with some restrictions - java

I've been struggling on this for some time and I'm really confused on how to solve this problem.
I've found something that works with MatLab but it's not what I need.
Here's my scenario:
private int[][] c = {{1,1,1,1,1,1,1},
{0,0,0,0,0,0,0},
{0,0,0,0,0,0,0}
};
c is a matrix in which I can have only one value set to 1 in each column.
This means that a configuration like
private int[][] c = {{0,1,0,1,1,0,0},
{1,0,0,0,0,1,1},
{0,0,1,0,0,0,0}
};
is valid, while
private int[][] c = {{1,0,1,1,0,1,1},
{0,0,1,0,0,0,0},
{0,0,0,0,1,0,0}
};
is not.
What I need is to generate a Set containing all the valid combinations for this matrix, but I've no idea on how to start.
I don't know if it's just because it's late and I'm half asleep but I can't think of a good way to do this.
Do you have any ideas?

There are many possible ways of actually implementing this. But you basically have to count from 0 to 37, and create one matrix for each number.
Imagine each possible column of the matrix as one number:
1
0 = 0
0
0
1 = 1
0
0
0 = 2
1
Then, the matrices can be represented by numbers in 3-ary form. The number 0000000 will correspond to the matrix
1 1 1 1 1 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The number 0000001 will correspond to the matrix
1 1 1 1 1 1 0
0 0 0 0 0 0 1
0 0 0 0 0 0 0
and so on.
Then, you can compute the total number of matrices, count up from 0 to this number, convert each number into a string in 3-ary form, and fill the matrix based on this string.
The 895th matrix will have the number 1020011, which is one of your example matrices:
0 1 0 1 1 0 0
1 0 0 0 0 1 1
0 0 1 0 0 0 0
A simple implementation:
public class MatrixCombinations
{
public static void main(String[] args)
{
int cols = 7;
int rows = 3;
int count = (int)Math.pow(rows, cols);
for (int i=0; i<count; i++)
{
String s = String.format("%"+cols+"s",
Integer.toString(i, rows)).replaceAll(" ", "0");
int[][] matrix = createMatrix(rows, cols, s);
System.out.println("Matrix "+i+", string "+s);
printMatrix(matrix);
}
}
private static int[][] createMatrix(int rows, int cols, String s)
{
int result[][] = new int[rows][cols];
for (int c=0; c<cols; c++)
{
int r = s.charAt(c) - '0';
result[r][c] = 1;
}
return result;
}
private static void printMatrix(int matrix[][])
{
for (int r=0; r<matrix.length; r++)
{
for (int c=0; c<matrix[r].length; c++)
{
System.out.printf("%2d", matrix[r][c]);
}
System.out.println();
}
}
}

Related

Need help reading a text file

So far I have developed a program that uses an adjacency matrix to build a graph using linked implementation.
I'm stuck on how I can read a text file containing an adjacency matrix, and using that data instead of manually inputting the adjacency matrix.
For example, a text file containing the following:
4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1
6
0 1 0 1 1 0
1 0 0 1 1 0
0 0 1 0 0 1
0 0 0 0 1 0
1 0 0 0 0 0
0 0 1 0 0 1
3
0 1 1
1 0 1
1 1 0
You can use this method to read matrix data from file. This method returns a 2d array of bytes containing zeroes and ones.
public static void main(String[] args) throws IOException {
byte[][] matrix = getMatrixFromFile("matrix.txt");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + ((j + 1) == matrix[i].length ? "" : " "));
}
System.out.println();
}
}
public static byte[][] getMatrixFromFile(String filename) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filename));
int size = Byte.parseByte(lines.get(0));
byte[][] matrix = new byte[size][size];
for (int i = 1; i < lines.size(); i++) {
String[] nums = lines.get(i).split(" ");
for (int j = 0; j < nums.length; j++) {
matrix[i - 1][j] = Byte.parseByte(nums[j]);
}
}
return matrix;
}
Here I am assuming the file will contain data for one matrix, like following, but my code can easily be extended to read data for multiple matrices and return a list of 2d byte array.
4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1

Java - Adjacency Matrix and DFS

I've been working on a program to implement a DFS in Java (by taking an adjacency matrix as input from a file). Basically, assuming vertices are traveled in numerical order, I would like to print the order that vertices become dead ends, the number of connected components in the graph, the tree edges and the back edges. But I'm not completely there yet. When I run my program, I get the number "1" as output, and nothing more. I've tried debugging certain parts of the DFS class, but I still can't quite figure out where I'm going wrong. Here is my code:
A basic "Driver" class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("sample1.txt"));
scanner.useDelimiter("[\\s,]+");
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
scanner.close();
new DFS(adjMatrix);
}
}
DFS class:
import java.util.Stack;
public class DFS {
Stack<Integer> stack;
int first;
int[][] adjMatrix;
int[] visited = new int[7];
public DFS(int[][] Matrix) {
this.adjMatrix = Matrix;
stack = new Stack<Integer>();
int[] node = {0, 1, 2, 3, 4, 5, 6};
int firstNode = node[0];
depthFirstSearch(firstNode, 7);
}
public void depthFirstSearch(int first,int n){
int v,i;
stack.push(first);
while(!stack.isEmpty()){
v = stack.pop();
if(visited[v]==0) {
System.out.print("\n"+(v+1));
visited[v]=1;
}
for (i=0;i<n;i++){
if((adjMatrix[v][i] == 1) && (visited[i] == 0)){
stack.push(v);
visited[i]=1;
System.out.print(" " + (i+1));
v = i;
}
}
}
}
}
And the matrix from the input file looks like this:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Take a look at this part:
int input = scanner.nextInt();
int[][] adjMatrix = new int[8][8];
for(int i=0; i < input; i++) {
for (int j=0; j < input; j++) {
adjMatrix[i][j] = scanner.nextInt();
}
}
First you read a number, input.
Then you read input rows, in each row input columns.
This is your input data:
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
What is the first number, that will be read by scanner.nextInt().
It's 0. So the loop will do nothing.
Prepend the number 8 to your input, that is:
8
0 1 0 0 1 1 0 0
1 0 0 0 0 1 1 0
0 0 0 1 0 0 1 0
0 0 1 0 0 0 0 1
1 0 0 0 0 1 0 0
1 1 0 0 1 0 0 0
0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0
Btw, it's a good idea to verify that you have correctly read the matrix.
Here's an easy way to do that:
for (int[] row : adjMatrix) {
System.out.println(Arrays.toString(row));
}
There are several other issues in this implementation:
The number 7 appears in a couple of places. It's actually a crucial value in the depth-first-search algorithm, and it's actually incorrect. It should be 8. And it should not be hardcoded, it should be derived from the size of the matrix.
It's not a good practice to do computation in a constructor. The purpose of a constructor is to create an object. The depth-first-logic could be moved to a static utility method, there's nothing in the current code to warrant a dedicated class.
Fixing the above issues, and a few minor ones too, the implementation can be written a bit simpler and cleaner:
public static void dfs(int[][] matrix) {
boolean[] visited = new boolean[matrix.length];
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
while (!stack.isEmpty()) {
int v = stack.pop();
if (!visited[v]) {
System.out.print("\n" + (v + 1));
visited[v] = true;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[v][i] == 1 && !visited[i]) {
visited[i] = true;
stack.push(v);
v = i;
System.out.print(" " + (i + 1));
}
}
}
}

setCells method sets four cells to a certain value instead of just one cell

So I'm making a Grid class. Here is my setCells method:
public boolean setCells(int rows[], int cols[], int vals[]) {
if (rows.length == cols.length && cols.length == vals.length && vals.length == rows.length) {
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < cols.length; j++) {
for (int k = 0; k < vals.length; k++) {
setValue(rows[i], cols[j], vals[k]);
}
}
}
return true;
}
return false;
}
And here's my client code:
public static void main(String[] args)
{
int rows[] = {1,2};
int columns[] = {1,2};
int values[] = {1,2};
Grid grid1 = new Grid(5, 7);
Grid grid2 = new Grid(8);
grid1.displayGrid();
grid2.displayGrid();
System.out.println(grid1.isEmpty());
grid1.setCells(rows, columns, values);
grid1.displayGrid();
Now whenever I use arrays with one element, the method works fine. However, when the arrays have more than one element, it sets four cells to that value instead of just one. Like this:
0 0 0 0 0 0 0
0 2 2 0 0 0 0
0 2 2 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
It's supposed to look like this:
0 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 2 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
Can anybody help me with this?
Your current algorithm has three nested loops, meaning that it attempts to set every possible combination of rows and columns to every listed value, rather than simply setting each cell once as desired. You only need one loop to iterate through a variable tracking index into all three arrays:
if (rows.length == cols.length && cols.length == vals.length) {
for (int i = 0; i < rows.length; i++) {
setValue(rows[i], cols[i], vals[i]);
}
}
Additionally, if you already know that rows and cols have the same lengths, and that cols and vals have the same lengths, then the third check (rows and vals have same length) is not necessary. I've removed it in the example code snippet directly preceding.

Array out of Bounds Exception when populating 2D Array maze

I am currently prepping to head into a Data Structures Course and as a result have begun reading on certain topics before hand. I am currently studying up on Stacks but have come across a problem.
I am currently coding a Maze App that uses stacks to auto-solve a maze. However, I am experiencing a problem when it comes populating the maze itself.
Code below:
import java.io.*;
import java.util.*;
public class Maze {
private Square move;
private char[][] maze;
private SquareStack s;
private String path =
"C:\\Users\\Sigh\\workspace\\StegmannStackMaze\\maze.txt";
private File file = new File(path);
public Maze(){
s = new SquareStack();
maze = new char[12][12];
}
public void getMaze() throws IOException{
for (int row = 0; row < 12 ; ++row){ // Creates the left/right walls of the maze " | | "
maze[row][0] = '1';
maze[row][11] = '1';
}
for ( int col = 0; col < 12 ; ++col){ // Creates upper and lower walls of the maze
maze[0][col] = '1';
maze[11][col] = '1';
}
Scanner filescan = new Scanner(path);
for( int row = 1; row <= 10 ; ++row){
String line = filescan.nextLine();
String delim = "[ ]+";
String[] tokens = line.split(delim);
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
filescan.close();
}
}
Here is the .txt file
0 0 1 E 1 0 0 1 1 1
0 1 1 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0 1 0
1 1 1 1 1 0 1 1 0 0
0 0 0 1 0 0 0 1 0 1
0 1 0 1 0 1 1 1 0 1
0 1 0 1 0 0 0 1 0 0
1 1 0 1 1 1 0 1 1 0
0 1 0 0 0 0 0 1 1 0
0 1 0 1 1 0 1 0 0 0
The Exception itself occurs at this particular line once col = 2.
for(int col = 1; col <= 10; ++col)
maze[row][col] = tokens[col-1].charAt(0);
}
From what I gather, this line takes each token that is created and populates the column. However, I am not sure why I get a exception.
Thanks for reading and hopefully I can get some insight from you guys.
Changes
Scanner filescan = new Scanner(path);
to
Scanner filescan = new Scanner(file);
The path is a String variable rather than File instance.

How do I generate a Matrix style output

I'm trying to get an output of a random string consisted of 1's and 0's in a Matrix style. I know how to display a string consisted of 1's and 0's, but I can't keep on looping through it for some reason. What I'm trying to do, is that whenever the StringBuilder reaches the length of 20, I want to start the loop on a new line again and repeat this 100 times.
import java.util.List;
import java.util.Random;
public class main {
static Random rand = new Random();
static StringBuilder x = new StringBuilder();
static int a = 0;
public static void main(String[] args) {
generatingnumber();
}
public static void generatingnumber() {
for (int bv = 0; bv <= 100; bv++) {
int random = rand.nextInt(50);
if (random % 2 == 0) {
x.append(" 0");
} else {
x.append(" 1");
}
if (x.length() == 20) {
System.out.println(x);
}
}
}
}
public class MatrixFilm {
public static void main(String[] args) {
int rows = 100;
int cols = 20;
for (int count1 = 0; count1 < (rows * cols); count1++) {
for (int count2 = 0; count2 < cols; count2++) {
int randomNum = 0 + (int) (Math.random() * 2);
System.out.print(" " + randomNum);
}
System.out.println();
}
}
}
Result:
0 0 1 0 0 0 0 1 0 0 1 1 0 0 1 0 1 1 1 1
1 1 0 1 1 1 0 1 0 1 0 1 1 0 1 1 0 0 1 0
0 1 0 0 1 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0
0 1 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 0 1 0
0 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 0 0
....
Your string has length of 20 characters only once. You are not interested in whether x.length() == 20 but if x.length() % 20 == 0.
For a new line you can append "\n" (or "\r\n" for Windows machine) to the string, everytime just before printing it.
Change println to print (which doesn't add new line character at the end of printed string) in order to maintain continuity between prints.
Taking all into account:
if (x.length() % 20 == 0) {
x.append("\r\n");
System.out.print(x);
}
However it still wouldn't be enough, for "\r\n" itself adds to the length of the string. This should work:
if (x.length() % 20 == 0) {
x.replace(x.length() - 2, x.length(), "\r\n");
System.out.print(x);
}
You can also - and it would be better to... - reset the string, as #owlstead has mentioned.
if (x.length() == 20) {
System.out.println(x);
x.setLength(0);
}
Anyway; what I presented is not a solution for the problem. Only solution to - probably improper - approach you have currently taken on it.

Categories

Resources