How to align data with different lengths in table format - java

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

Related

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;
}
}

Determine which column contains the maximum sum of its elements

I would like to know, how to find out which column in the 2D-array has got the largest sum. How would I approach this?
public static void main(String args[]) {
int[][] array = {
{ 132, 154, 118 },
{ 355, 101, 50 },
{ 432, 143, 365 },
{ 462, 234, 185 }
};
}
You could go with a nested for loop
int maxCol = 0;
int valOfMaxCol = 0;
for(int i = 0; i < 3; i++){
int sum = 0;
for(int j = 0; j < array.length; j++){
sum += array[j][i];
}
if(sum > valOfMaxCol){
valOfMaxCol = sum;
maxCol = i;
}
}
System.out.println("Max Col is " + (maxCol + 1) + " with the value " + valOfMaxCol);

Print matrix in 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");
}

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("");
}

I want to get the consutive pair of natural number all increment or decrement sequence

suppose i have a array 2, 9, 0, 6, 1, 2, 3, 6,12,0,3,9
so first pair should be 1,2,3 because its the fixed increment.
second pair should be 6,12
and third pair should be 0,3,9
int[] arr = {2, 9, 0, 6, 1, 2, 3, 6};
System.out.println(">>>>>>>"+array(arr));
//to get the max sequence.
int sequenceLength = 3;
Map<String, Integer> map = new HashMap<String, Integer>();
int count;
String str1, str2;
for (int i = 0; i <= arr.length - sequenceLength; i++) {
str1 = "";
count = 0;
for (int a = i; a < i + sequenceLength; a++) {
str1 += "" + arr[a];
}
if (map.get(str1) != null) {
continue;
} else {
map.put(str1, count);
}
for (int ii = i; ii <= arr.length - sequenceLength; ii++) {
str2 = "";
for (int a = ii; a < ii + sequenceLength; a++) {
str2 += "" + arr[a];
}
if (str1.equals(str2)) {
count++;
map.put(str1, count);
}
}
}
PSEUDO CODE:
incrementArray = new Array<pair>
increasingSequences = new Array<pair> //size of N
increasingSequenceCount = 0 //You start with 0 incrementing arrays
for i -> N
value = array[i];
for j -> incrementArray.length
if (incremtentArray[j] == value + incrementArray[j])
addValueToIS(value, j) //adds to array j of increasingSequences
else
incrementArray.close(j) //closes increasingSequence array
incrementArray.push(array[i], increasingSequenceCount++);
At the end increasingSequences will contain X number of arrays of size > 1. These are your sequences

Categories