Print matrix in Java - java

I want the output to look like:
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]
My code right now outputs:
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
for (int j = 0; j < Matrix.length; j++) {
for (int k = 0; k < Matrix[0].length; k++) {
System.out.print(Matrix[j][k] + " ");
}
System.out.print("\n");
}
How can I make this work?

Try this
for (int[] row : Matrix)
System.out.println(Arrays.toString(row));

Just print commas and brackets around your loop and after the number:
for (int j = 0; j < Matrix.length; j++) {
System.out.print("[");
for (int k = 0; k < Matrix[0].length; k++) {
System.out.print(Matrix[j][k] + " ");
if (k + 1 < Matrix[0].length) System.out.print(", ")
}
System.out.print("]\n");
}

Print a [ before your first line and a ] after your last. Then add a comma before the space. Also, Java variable names start with a lower case letter (by convention). You could also use a for-each loop and something like,
int[][] matrix = { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 } };
for (int[] array : matrix) {
System.out.print("[");
for (int i = 0; i < array.length; i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println("]");
}
which will produce your requested output (but will also handle jagged arrays).

for(i=0;i<row_count;i++) {
for(j=0;j<column_count;j++) {
System.out.print(Matrix[i][j]+" ");
}
System.out.print("\n");
}

Related

How to align data with different lengths in table format

Notice how the '0' of the collisions column in the 3rd line is shifted, as well as other numbers, what is a fix to that? [
This is my current output
System.out.println(""+capacity +"\t\t\t "+size()+"\t\t "+num+"\t\t"+ data + "\t\t\t" + collisions)
I would start by precomputing the lengths of all of the header fields. Then use that and formatted io to build a table programmatically. Something like,
String[] headings = {
"Capacity",
"Size",
"Num",
"data",
"Collisions"
};
int[] lengths = new int[headings.length];
for (int i = 0; i < headings.length; i++) {
lengths[i] = headings[i].length() + 4;
}
int[][] values = {
{ 100, 1, 1, 241, 0 },
{ 100, 2, 1, 289, 0 },
{ 100, 3, 1, 4, 0 }
};
for (int i = 0; i < headings.length; i++) {
System.out.printf("%-" + lengths[i] + "s", headings[i]);
}
System.out.println();
for (int i : lengths) {
for (int j = 0; j < i; j++) {
System.out.print("=");
}
}
System.out.println();
for (int[] arr : values) {
for (int i = 0; i < arr.length; i++) {
System.out.printf("%-" + lengths[i] + "s", arr[i]);
}
System.out.println();
}
Outputs
Capacity Size Num data Collisions
=================================================
100 1 1 241 0
100 2 1 289 0
100 3 1 4 0

How to remove rows and columns containing only zeros from a 2d matrix?

Given an integer matrix of size, say, M x N, you have to write a program to remove all the rows and columns consisting of all zeros. Your program must remove those rows and columns that consist of zero valued elements only. That is, if all the elements in a row (column) are zeros, then remove that row (column). All the remaining rows and columns should be output.
Input Specification:
The first line of input will have two integers, say, M and N. M specifies the number of rows in the matrix and N specifies the number of columns in the matrix.
This will be followed by M lines, each consisting of N integers. Note: Assume 1 <= M <= 10 and 1 <= N <= 10. Also, you may assume that there is at least one non-zero element in the given matrix.
Output Specification:
The output should be the resulting matrix.
Each row of the output matrix should be terminated by a newline character.
There should be exactly one space (not tab) between successive elements in each row.
Example1:
Sample Input:
4 4
1 2 3 4
0 0 0 0
5 6 7 8
0 0 0 3
Sample Output:
1 2 3 4
5 6 7 8
0 0 0 3
Example2:
Sample Input:
4 5
1 2 0 3 5
0 0 0 0 0
4 5 0 6 9
7 8 0 9 1
Sample Output:
1 2 3 5
4 5 6 9
7 8 9 1
The solution I found was as follows. It works only for rows and columns having either non-negative or non-positive numbers:
import java.util.Scanner;
public class RemoveZeroFromMatrix {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter rows and column");
int m = s.nextInt();
int n = s.nextInt();
int[][] a = new int[m][n];
int[][] b = new int[m][n];
int[][] c = new int[m][n];
System.out.println("enter the matrix");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("input matrix");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int sumRow = 0, x = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sumRow += a[i][j];
}
if (sumRow != 0) {
for (int k = 0; k < n; k++) {
b[i - x][k] = a[i][k];
}
} else {
x++;
}
sumRow = 0;
}
int sumCol = 0, y = 0, temp = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - x; j++) {
sumCol += b[j][i];
}
if (sumCol != 0) {
for (int k = 0; k < n - x; k++) {
if (temp == 0) {
c[k][i] = b[k][i];
}
if (temp == 1 && n > 3) {
c[k][i] = b[k][i + 1];
}
}
} else {
for (int k = 0; k < n - x; k++) {
c[k][i] = b[k][i + 1];
temp = 1;
}
}
sumCol = 0;
}
System.out.println("outut matix:");
for (int i = 0; i < m - x; i++) {
for (int j = 0; j < n - y - temp; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Removing columns from a matrix is more difficult than removing rows. For this reason, to simplify the code, you can use the matrix transposition something like this:
Try it online!
public static void main(String[] args) {
int[][] arr1 = {
{1, 2, 3, 4},
{0, 0, 0, 0},
{5, 6, 7, 8},
{0, 0, 0, 3}};
int[][] arr2 = {
{1, 2, 0, 3, 5},
{0, 0, 0, 0, 0},
{4, 5, 0, 6, 9},
{7, 8, 0, 9, 1}};
int[][] arr3 = removeZeroRowsNColumns(arr1);
int[][] arr4 = removeZeroRowsNColumns(arr2);
// output
Arrays.stream(arr3).map(Arrays::toString).forEach(System.out::println);
//[1, 2, 3, 4]
//[5, 6, 7, 8]
//[0, 0, 0, 3]
Arrays.stream(arr4).map(Arrays::toString).forEach(System.out::println);
//[1, 2, 3, 5]
//[4, 5, 6, 9]
//[7, 8, 9, 1]
}
public static int[][] removeZeroRowsNColumns(int[][] arr) {
return removeZeroRows(removeZeroColumns(arr));
}
public static int[][] removeZeroColumns(int[][] arr) {
return transposeMatrix(removeZeroRows(transposeMatrix(arr)));
}
public static int[][] transposeMatrix(int[][] arr) {
// assume that we have a rectangular array, i.e. matrix
int[][] transposed = new int[arr[0].length][arr.length];
IntStream.range(0, arr.length)
.forEach(i -> IntStream.range(0, arr[0].length)
.forEach(j -> transposed[j][i] = arr[i][j]));
return transposed;
}
public static int[][] removeZeroRows(int[][] arr) {
return Arrays.stream(arr)
// filter out rows consisting of all zeros
.filter(row -> !Arrays.stream(row).allMatch(i -> i == 0))
.toArray(int[][]::new);
}

How Can I Get This List to Print Repeated Values in an Array Without Printing the Value Twice

public static void printOrganizedList(int[] array) {
int[] temp = array;
System.out.println("N Count");
for(int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if(array[i] == array[j]) {
count++;
}
}
for(int n = i-1; n > 0; n--) {
if(array[n] == array[i]) {
break;
}
else {
System.out.println(array[i] + " " + count);
}
}
}
}
This method is made to take in an array and print the duplicate values along with the amount of times it appears in the array. Like this:
-12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12
The program output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
My issue is that no matter what I try the method always spits out the duplicate number along with its amount of repeats as many times as it is repeated. So instead of outputting
"-12 4"
It will output :
"-12 4"
"-12 4"
"-12 4"
"-12 4"
Also I'm aware that there are more advanced and efficient techniques but we haven't learned a lot of that stuff yet.
Thanks in advance.
This can be easily acheived using a HashMap. You can create a Hashmap which would save the element as key and keep the number of occurrences as the value.
public static void printOrganizedList(int[] array) {
System.out.println("N Count");
HashMap<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < array.length; i++){
if (countMap.containsKey(array[i])){
int count = countMap.get(array[i]);
countMap.replace(array[i], count + 1);
}else{
countMap.put(array[i], 1);
}
}
Iterator iterator = countMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry mapElement = (Map.Entry) iterator.next();
int key = (int) mapElement.getKey();
int count = (int) mapElement.getValue();
System.out.println(key + " " + count);
}
}
Also the time complexity of the program that you have written goes to O(N^2) which can be a really big bottleneck when it comes to large programs.
The above program with hashmap implementation would only cost you O(N)
If the range of the input array is reasonable (for instance, from -12 to 12, not from Integer.MIN_VALUE to Long.MAX_VALUE), you may apply count sorting:
define min and max values in the array,
count the frequencies,
and print out the numbers whose frequencies are greater than 1:
int min = arr[0], max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
else if (arr[i] > max) max = arr[i];
}
int[] freq = new int[max - min + 1];
for (int i = 0; i < arr.length; i++) {
freq[min + i]++;
}
for (int i = 0; i < freq.length; i++) {
if (freq[min + i] > 1) {
System.out.println((min + i) + " " + freq[min + i]);
}
}
public static void main(String[] args) {
printOrganizedList(new int[] { -12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12 });
}
public static void printOrganizedList(int[] array) {
System.out.println("N\tCount");
Map<Integer, Integer> freq = new TreeMap<>();
for (int i = 0; i < array.length; i++) {
if (freq.containsKey(Integer.valueOf(array[i])))
freq.put(Integer.valueOf(array[i]), freq.get(Integer.valueOf(array[i])) + 1);
else
freq.put(Integer.valueOf(array[i]), 1);
}
for (Integer key : freq.keySet()) {
System.out.println(key + "\t" + freq.get(key));
}
}
, output
N Count
-12 4
1 4
2 2
3 3
4 2
, Another solution to match your code
public static void printOrganizedList(int[] array) {
System.out.println("N\tCount");
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
int count = 0;
// calc freq
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j])
count++;
}
if (count > 1)
System.out.println(array[i] + "\t" + count);
i += count;
}
}

grouping algorithm java n choose k

I have 10 numbers in a vector container contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. And I want n numbers in a group, for example:
n = 3
[1,2,3], [4,5,6], [7,8,9], [10]
[2,3,4], [5,6,7], [8,9,10], [1]
Is there an algorithm to find all the combinations?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
List<int[]> subsets = new ArrayList<>();
int[] s = new int[k]; // here we'll keep indices
// pointing to elements in input array
if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
subsets.add(getSubset(input, s));
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
Thank you.

Printing matrix line in Java

I need to construct a method that receives a matrix as argument and prints its lines. For example, the method will receive the matrix below
int[][] matrix = {
{3, 1, 2, 7, 2, 5, 6, 2},
{2, 10, 20, 12, 13},
{3, 7, 12, 15, 18, 4},
{2, 11, 21, 12, 13}
};
And it must return
Line 0 : 3 1 2 7 2 5 6 2
Line 1 : 2 10 20 12 13
Line 2 : 3 7 12 15 18 4
Line 3 : 2 11 21 12 13
Here is the method:
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
for (int j = 0; j < matrix[i].length; ++j){
System.out.print("Line nb " + i + " : " + matrix[i][j] + " ");
}
}
}
But it does not print in the way I want. It prints like that and I'm trying to figure out how to solve it.
Line 0 : 3
Line 0 : 1
Line 0 : 2
Line 0 : 7
Line 0 : 2
Line 0 : 5
Line 0 : 6
Line 0 : 2
// And so on for other lines
You are calling System.out.print for each element of the array instead of each row of the array. Modify like this :
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
System.out.print("Line " + i + " :"); // line header
for (int j = 0; j < matrix[i].length; ++j){
System.out.print(" " + matrix[i][j]);
}
System.out.println(""); // end of line
}
}
Note how an empty space is added before each element " " + matrix[i][j] to avoid trailing whitespace.
Also bear in mind you could write the second for loop like this
for (int n : matrix[i]) {
System.out.print(" " + n);
}
How about something like:
int rowNumber = 0;
for (int[] row : matrix){
System.out.println("Line " + (rowNumber++) + " : " + Arrays.toString(row));
}
which will generate
Line 0 : [3, 1, 2, 7, 2, 5, 6, 2]
Line 1 : [2, 10, 20, 12, 13]
Line 2 : [3, 7, 12, 15, 18, 4]
Line 3 : [2, 11, 21, 12, 13]
Use the code below
public static void displayLines(int[][] matrix){
for (int i = 0; i < matrix.length; ++i){
System.out.print("Line nb " + i + " : " );
for (int j = 0; j < matrix[i].length; ++j){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void displayLines(int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line " + i + " : ");
for (int j = 0; j < matrix[i].length; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
int[][] matrix = { { 3, 1, 2, 7, 2, 5, 6, 2 }, { 2, 10, 20, 12, 13 },
{ 3, 7, 12, 15, 18, 4 }, { 2, 11, 21, 12, 13 } };
for (int i = 0; i < matrix.length; ++i) {
System.out.print("Line " + i + " :");
for (int j = 0; j < matrix[i].length; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}

Categories