Can someone be so kind to let me know why the heck javac is printing extra lines with zeros when executed the following lines of code? I have intentionally printed the number of possible lines in the first line, which is exactly equal to the number of nonzero lines. Any advice?
Code:
int[] fa = new int[15];
int[][] sa = new int[100][3];
int a=0, b=0;
for(int i=0; i<15; i++){
fa[i] = i+1;
}
for(int i=0; i<fa.length; i++){
for(int j=i+1; j<fa.length; j++){
for(int k=j+1; k<fa.length; k++){
if(fa[i]+fa[j]+fa[k]==15){
sa[a][0] = fa[i];
sa[a][1] = fa[j];
sa[a][2] = fa[k];
a++;
}
}
}
}
System.out.println(a);
for(int i=0; i<sa.length; i++){
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
The output:
12
1 2 12
1 3 11
1 4 10
1 5 9
1 6 8
2 3 10
2 4 9
2 5 8
2 6 7
3 4 8
3 5 7
4 5 6
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
To print you are iterating on sa:
for(int i=0; i<sa.length; i++){
And at the beginning you stated it has 100 rows (default values to 0):
int[][] sa = new int[100][3];
It shows those 100 rows independently of what you did on your second for with fa.
Try with:
for(int i=0; i<a; i++){
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
You are printing the content of the entire sa regardless of how many items you have added to it. The first 12 items print correctly, while the remaining items print the initial values of int[3] arrays, which happen to be zeros.
You can fix this by iterating up to a items, like this:
for(int i=0; i < a; i++) {
// ^^^
for(int j=0; j<3; j++){
System.out.print(sa[i][j]+" ");
}
System.out.println();
}
Alternatively, you could switch to using lists in place of arrays. Since lists grow dynamically, you would be able to avoid this problem altogether:
class Triple {
private final a, b, c;
public Triple(int a, int b, int c) {this.a=a; this.b=b; this.c=c;}
public int getA() { return a; }
public int getB() { return b; }
public int getC() { return c; }
}
List<Triple> sa = new ArrayList<>();
...
if(fa[i]+fa[j]+fa[k]==15){
sa.add(new Triple(fa[i], fa[j], fa[k]));
}
...
for (Triple t : sa) {
...
}
Related
i have a problem with my code. I'm making a program that should display like this:
0 2 3 4
5 0 7 8
9 10 0 11
12 13 14 0
Here's my code:
int rows = 4, count1=1, count2=4;
for(int i=1; i<=rows; i++){
for(int j=1; j<=rows; j++){
if(j==count1){
System.out.printf("0");
}else{
System.out.print(count1);
}
}
if(i<=rows){
count1++;
count2--;
}
System.out.printf("\n");
}
But the output shown is like this:
0 1 1 1
2 0 2 2
3 3 0 3
4 4 4 0
Can somebody tell me what is wrong with my code? Thank you
Use a counter (e.g. count in the code given below) initialized with 1 to print the values. Print 0 when i==j. Increase the counter whether you print the value of the counter or 0.
Do it as follows:
public class Main {
public static void main(String[] args) {
int rows = 4, count = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows; j++, count++) {
if (i == j) {
System.out.printf("%3d", 0);
} else {
System.out.printf("%3d", count);
}
}
System.out.printf("\n");
}
}
}
Output:
0 2 3 4
5 0 7 8
9 10 0 12
13 14 15 0
I can't see a need for two counters. Increment count1 on EVERY iteration of your inner loop. Replace the first condition with if (j == i).
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
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));
}
}
}
}
Actually the purpose of the whole code is to get input values (0 or 1) in an array then check entered array for 6 continuous 0's then insert '1'after each 6 consecutive 0's. I found that this block
if(j>5){
shift(i+6);
bits[i+6] = 1;
count+=1;
System.out.println(count);
}
is executed even if there is no 6 consecutive 0's in the entered array. Then to check the problem. I added this statement
System.out.println("ABHINAV " + j );
and here is output:-
Entered Bits are:
1
0
1
0
1
0
1
0
1
0
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 1
ABHINAV 0
ABHINAV 6
I found the problem - the variable 'j' increments to 6 and hence the 'if' block is entered. My Question is:-
How 'j' is getting incremented to 6 (as you can see the last line of the output snap).
How this problem can be solved. What I am doing wrong.
Here is the whole code
class Stuff{
public static final int LENGTH=6;
public int count=0;
int n;
public int bits[] = new int[40];
Scanner inputs = new Scanner(System.in);
Stuff(int x){
n=x;
}
public void input(){
for(int i=0 ; i<n ; i++){
bits[i] = inputs.nextInt();
}
}
public void len_check(){
int j=0;
for(int i = 0 ; i< n ; i++){
j=0;
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
System.out.println("ABHINAV " + j );
if(j>5){
shift(i+6);
bits[i+6] = 1;
count+=1;
System.out.println(count);
}
}
}
public void shift(int u){
for(int i=n ; i>= u ;i--){
bits[i+1] = bits[i];
}
}
public void display(){
for(int i=0 ; i<n+count ; i++){
System.out.println(" " + bits[i]);
}
}
}
class Problem{
public static void main(String args[]){
int n;
Scanner inputs = new Scanner(System.in);
System.out.println("\nEnter bit stream length");
n = inputs.nextInt();
Stuff stuff = new Stuff(n);
System.out.println("Now Enter the bits: ");
stuff.input(); // Enter the bit stream
System.out.println("Entered Bits are: ");
stuff.display();
stuff.len_check();
System.out.println("Altered Bits are: ");
stuff.display();
}
}
It is because the input is only 10 positions long, after the 10 first values the array bits is filled with 0 (standard value).
It is working as programmed, finding 6 0 starting at position 10.
It should stop when reaching the position n - 5, e.g:
...
int j = 0;
for (int i = 0 ; i< n-5 ; i++) {
j = 0;
...
the bits variable was instantiated with the length 40,
public int bits[] = new int[40];
this so the bits[] were an array of zeros with length 40. After that the first ten elements ere replaced by the inputs. Here's the array:
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
value 1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ...
This code:
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
when i=9, it increments j 6 times because bits[9] to bits[14] are 0.
bits is an int array of length 40 so it's full of 0 after what you have scanned for System.in.
When i = n-1, you check the last digit you entered which is 0 and all the next one are 0 so j increments to 6.
for(int i = 0 ; i< n ; i++){
j=0;
while(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
This will just set j to 6 right away. Use an if instead:
if(bits[i+j] == 0 && j<LENGTH){
j+=1;
}
i want setting an array and below is my code
public static void setArray()
{
int i = 5;
int j = 5;
int testarray[][] = new int[i][j];
for(int x = 0;x<i;x++)
{
for(int y=0;y<j;y++)
{
System.out.print("0 ");
}
System.out.println("");
}
}
the result is something like this:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
if i want to put a number/alphabet beside to let the user know which column, how can i do that ?
Expected Result:
====================
1 2 3 4 5
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need another initial for-loop to print the numbers, then you need to add another print statement within your second for-loop to print the letter for each row:
System.out.print(" ");
for (int x = 0; x < i; x++) { // this prints the numbers on the first row
System.out.print(" " + x);
}
System.out.println();
for (int x = 0; x < i; x++) {
System.out.print((char) ('A' + x) + "|"); // this prints the letters
for (int y = 0; y < j; y++) {
System.out.print("0 ");
}
System.out.println("");
}
0 1 2 3 4
A|0 0 0 0 0
B|0 0 0 0 0
C|0 0 0 0 0
D|0 0 0 0 0
E|0 0 0 0 0
You need to print 1, 2, 3, 4, 5 .. column number of times and print A, B, C, D .. till you reach the number of rows. Try coding it yourself, it's not that difficult (I don't want to provide a ready-made code)