Two Dimensional Matrix as Input - java

how to write two dimensional matrix as input and identifies the number with maximum number of occurrences in the matrix.
Example Input :
2 // no of rows
3 // no of columns
1 2 3 2 3 3 // here the matrix taken as input is 2 x 3 matrix. Remaining six numbers are values for the particular matrix. (elements in the first row are 1 2 3 and elements in the second row are 2 3 3)
Example output : 3
import java.util.*;
class ArrayOccurence
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
sc.nextLine();
int column = sc.nextInt();
sc.nextLine();
int element = 0;
int occurence = 0;
int arr[][] = new int[row][column]; // size of the array
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
arr[i][j] = sc.nextInt();
}
//Do not modify the code above
/* Enter your code here */
// Do not modify code below
System.out.println("Matrix element "+element+" occurs "+occurence+" times in the matrix");
}
}

Substitute your line which says Enter your code here with the following:
ArrayList<Integer> a = new ArrayList<Integer>();
int oc = 0;
int number = 0;
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++){
if(a.isEmpty()){
a.add(arr[i][j]);
}
else if(a.contains(arr[i][j])){
int temp=0;
for(int k=0; k<a.size(); k++){
if(a.get(k) == arr[i][j]){
temp++;
}
}
if(temp > oc){
number = arr[i][j];
oc = temp;
}
a.add(arr[i][j]);
}
else{
a.add(arr[i][j]);
}
}
}
Hope this helps.

You could use the double for loop again to count the occurence of each numbers:
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
//count occurences with a HashMap<Integer,Integer> or something like that
}
Loop into your HashMap to find the one with most occurence..

Related

i want to create a bar chart of array with given user inputs

You are given a number n, representing the size of array a.
You are given n numbers, representing elements of array a.
You are required to print a bar chart representing value of arr a.
A bar chart of asterisks representing value of array a
SAMPLE INPUT:-
5
3
1
0
7
5
SAMPLE OUTPUT:-
I tried getting this input from this approach can anyone help me? What should I do to get the same?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
int x = arr[i];
for (int j = 0; j < x; j++) {
System.out.print("*" + "\n");
}
System.out.println();
}
}
}
A 2D array of chars may be used to represent the graph field to "draw" vertical bars char[][] map.
The dimensions of this array are:
height: the maximal number in the input arr
width: the number of columns (arr.length) plus an empty column between each asterisk bar, that makes: 2 * arr.length - 1
it may be better to have a parameter space between the bars and calculate the width of map accordingly: (space + 1) * arr.length - space
Populate each row of the map with default whitespaces (maybe using Arrays.fill).
Nested loops: Fill asterisks in the relevant columns from bottom to top, calculate indexes of the columns with regard to space parameter.
Loop: Print each row of map converting the char[] into String.
Coding is left for exercise.
//finding largest element in an array
int l = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] > l)
l = arr[i];
}
//traversing using largest element as no. of rows
for(int i = l; i > 0; i--) {
for(int j = 0; j < n; j++) {
if(i <= arr[j])
System.out.print("* ");
else
System.out.print(" ");
}
System.out.println();
}

Need to print the max element column in java

Hello I am new in java and I want to write a program where I will print the max element from the column in 2D table. I am updating a picture to show what actually I want to print.
Here is the code:
import java.util.*;
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
int[][] table = new int [col][row];
int max= 0;
for(int i=0; i<col; i++){
for(int j=0; j<row; j++){
max= table[i][0];
table[i][j]= sc.nextInt();
if(max<table[i][j]){
max= table[i][j];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
}
}
You can index a matrix (2D table) like this:
matrix[row][column]
where row and column are 0-based indexes.
You have to change the loop like this:
int max= 0;
for(int i=0; i<col; i++){
// select first element of a column as temp max
max= table[0][i];
for(int j=0; j<row; j++){
// cycle on rows
if(max<table[j][i]){
max= table[j][i];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
You have to cycle on column. Select the first element of a column as temporary maximum
You have to init the max when you end a row, not inside the nested loop
Side note: I suggest you to keep the code clean (because is a simple example and I assume you have a little file) and separate tasks:
First, read the file (perhaps print the file content to be sure the content it's ok)
Then, check the maximum of each column
In this way will be simpler for you to catch problems.
You need to separate the values insertion and finding the maximum value so you can iterate the array by columns
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
table[i][j] = sc.nextInt();
}
}
int[][] table = new int[col][row];
for (int i = 0; i < col; i++) {
int max = table[0][i];
for (int j = 0; j < row; j++) {
if (max < table[j][i]) {
max = table[j][i];
}
}
System.out.println("Maximum number is " + max);
System.out.println();
}
}
}
Output
Maximum number is 10
Maximum number is 5
Maximum number is -3
Maximum number is 9

Need to print rows of multidimensional array as columns

This is my program output:
Enter the size of 2D array:
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
and I need this instead:
1 12 5 16
2 11 6 15
3 10 7 14
4 9 8 13
I want the 2d array to be of size NxN where n is the integer inputted by the user. I want the first consecutive values to be stored in the even indexed columns from top to bottom and the next consecutive values to be stored in the odd indexed columns from bottom to top.
import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}
}
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println("\n");
}
}
public static int[][] transpose (int[][] array) {
if (array == null || array.length == 0)//empty or unset array, nothing do to here
return array;
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
return array_new;
}
}
As Sean pointed out in the comments, your transpose() function returns a new array but you are not capturing that and using it. The original array remains unchanged, which is what you are displaying at the end.
Change:
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
To:
int[][] newArr = transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : newArr) {
Try this out. It should do what you have described in the question.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int j = 0; j < n; j += 2) {
for(int i = 0; i < n; i++) {
arr[i][j]=inc++;
}
}
for(int j = 1; j < n; j += 2) {
for(int i = n - 1; i >= 0; i--) {
arr[i][j]=inc++;
}
}
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println();
}
}

Fill 2D array square and print in specific patterns

Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}

how to automatically populate a 2d array with numbers

Hi i am trying to auto populate a 2d array based on user input.
The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array.
for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
But i am struggling to think of the right statement that will do this.
for the moment my code just prints out a 2d array containing *.
Has anyone any ideas how i could print out the numbers , i'm really stuck.
my code follows:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
Read n value,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.
int counter = 1;
for(int x = 0; x < num1; x++)
{
for(int y = 0; y < num2; y++)
{
grid[x][y] = counter++;
}
}
Afterwards you can output the array again with a double for loop.
I am not sure if I understand you right.
You have problem with the code printing *?
If yes, then the reason for that is this
System.out.print("*");
Should be
System.out.print(grid[row]);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int arraySize = input.nextInt();
System.out.println("Length: " + (arraySize*arraySize));
int[][] array = new int[arraySize][arraySize];
int count = 1;
for (int i=0;i<arraySize;i++) {
for (int j=0;j<arraySize;j++) {
array[i][j] = count;
if (j != (arraySize-1))
System.out.print(count + "-");
else
System.out.println(count);
count++;
}
}
}
This code should print out the numbers how you want them.

Categories

Resources