Making An Array of Selected Values That Only Displays Specific Values - java

I'm trying to figure out how to print out a second array that is based off my first one but only displays values that are greater than the value to its left and less than the value to it's right and displaying these values by row in the row that they are in the original array. Here's my code so far.
public static void main(String[] args)
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
row = 3;
col = 6;
// enter array elements.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.println("Enter a value: ");
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("Matrix Display :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
}

You won't know how many of the elements fit your criteria, so you need to use a mutable object. Since each row might have a different number of matching numbers, you won't be able to make a normal array without null values in it most of the time.
Use a 2D ArrayList, scan through your original 2D array, and add the value that match your criteria to the corresponding row of your ArrayList.
You could do something like this:
int width = arr[0].length-1;
ArrayList<ArrayList<Integer>> listoflists= new ArrayList<ArrayList<Integer>>();
// Scan array for matching values
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
listoflists.add(new ArrayList<Integer>());
if(j==0 && arr[i][0]<arr[i][1])
listoflist.get(i).add(arr[i][0]);
else if(j==width && arr[i][width]>arr[i][width-1]
listoflist.get(i).add(arr[i][width]);
else if( #this is the last condition to check from both sides)
listoflist.get(i).add(arr[i][j]);
}
}

Related

closed and open elements in an array

I am writing a code to indicate open and closed elements in a 2d array. An open element is represented with . and a closed element is represented with *. The first column in the array must be completely open whereas all the other columns must be closed. The output should be:
.**
.**
.**
The array is also going to vary in size as the user will determine how big the array is. I have managed to code a 2D array grid as this is not hard, however, I am trying to now use an if-statement to make the first column all open. I placed the if-statement within the nested loop:
import java.util.Arrays;
import java.util.Scanner;
public class trial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
grid[i][j] ='.';
if(grid[j].length > grid[0].length) {
System.out.println("");
}else {
System.out.print('*');
}
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
This, however, is giving me an output that looks like this:
*.*.*.
*.*.*.
*.*.*.
*.*.*.
I have tried placing the if-statement outside of this nested for-loop but I then get an error with my variables as they have not been defined. Any assistance as to how to fix this or make it that I can get values for my i and j variables outside of the for-loop would be greatly appreciated.
I slightly modify your code to make it fit the description.
i and j will vary when the loop proceeds, and should be accessed inside the loop only.
It seems that you want to change the content inside grid, which can be accessed outside the loop after processing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
grid[i][j] = '.';
if(j > 0) {
grid[i][j] = '*';
}
System.out.print(grid[i][j]);
}
System.out.println();
}
// you cannot access i/j outside the loop scope. instead, you can access the grid
System.out.println("Loaded array:");
Arrays.stream(grid).forEach(System.out::println);
}
Just check if the current column is 0 or not
Just a minor change will work here
I am writing only the main loop below
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
if(j == 0){ //0th column make it dot(.)
grid[i][j] ='.';
}
else { //For other columns put asterisk(*)
grid[i][j] = '*';
}
}
}
Here's a different way to think about 2D arrays. They are simply a 1D array where each element is itself another 1D array (a complete "row").
With that in mind, here's a different way to initialize and print the contents of the 2D array using a mixture of enhanced and indexed for loops:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
for(char[] row : grid) {
for(int col=0; col<row.length; col++) {
row[col] = (col == 0) ? '.' : '*';
}
}
for(char[] row : grid) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
Output:
What size square grid do you want?
5
.****
.****
.****
.****
.****

How to print first five elements of an matrix in Java

My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.

Need to find out the duplicate element in array without using Hashmaps

I am a newbie here. I wanted to print out the duplicate elements in an array.
This code will print out the duplicate elements.
Suppose I'm taking an array of size 5 with elements [1,2,5,5,5]
This code will print:
Duplicate elements: 5,5,5 //(since 5 is being repeated thrice.)
But I want the output something like this
Duplicate Elements: 5 //( instead of printing 5 thrice)
import java.util.*;
import java.util.Scanner;
public class duplicateArray{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x =sc.nextInt();
int arr[]=new int[x];
int i,count=0;
for(i=0;i<x;i++){
arr[i]=sc.nextInt();
}
System.out.print("Array: ");
for(i=0;i<x;i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
System.out.print("Duplicate elements: ");
for(i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
System.out.print(arr[j]+" ");
}
}
}
}
}
The following code does it without creating any additional data structure. For each element, it counts the number of duplicates previously encountered and only prints the first duplicate.
If I were doing this in the real world, I would use a Set but I'm assuming you haven't learnt about them yet, so I'm only using the array that you've already created.
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}
One solution is to create a separate List to store any duplicates found.
That, in addition to using the .contains() method of the List, you can ensure only one entry per int is made.
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
Output:
Duplicates: [1, 5]
This is pretty simple however you need to sort array before. All you need to know if duplicate for an element exists or not and do the printing in the outside for loop. Rest is described in comments
Arrays.sort(arr); // Sort Array
for (int i = 0; i < arr.length; i++) {
boolean hasDuplicate = false; // Assume that arr[i] is not repeating
for (int j = i + 1; j < arr.length; j++) {
// Check if it is repeating
if (arr[i] == arr[j]) {
// If it repeats
hasDuplicate = true;
}
// Since array is sorted we know that there is no value of arr[i] after this
if (arr[i] != arr[j]) {
// Set i to the last occurrence of arr[i] value
i = j - 1;
break; // Since there no occurrence of arr[i] value there is no need to continue
}
}
// Print the element at i
if (hasDuplicate)
System.out.print(arr[i] + " ");
// In next iteration loop will start from the index next to the last occurrence of value of arr[i]
}
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}
Without using Hashmaps, I think your best option would be to first sort the array and then count the duplicates. Since the array is now in order you can print the duplicates after each number switch!
If this is for an assignment go ahead and google bubble sort and implement it as a method.

having trouble replacing default zeros in 2d array with white spaces

My goal to to make three different 2D arrays, and for the last two replace all zeroes in the array values for blank spaces instead. I've tried using printf("%s","[]") but instead of replacing the zeros they just add the brackets above the array. i believe it has something to do with the placement of my else statement.
public class arrayprgm1{
public static int[][] Table(int x, int y){//creating first 2D array
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
array[row][column]=(row+column)*3;// algorithm used for first 2D array
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up values of first array
}
}
System.out.printf("The total of all the numbers added together is: %2d\n", sum);// using format print to display sum
return array;//return array created to the main method
}//end of Table method
public static int[][] Odds(int x, int y){//creating second 2D array
int[][]array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 !=0){ // if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;// algorithm used for second array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up all odd values
}
}
for(int row=0; row< array.length;row++){
for(int column=0;column<array[row].length;column++){
}
}System.out.printf("The total of all the odd numbers added together is: %2d\n", sum);//format print used to display sum of all odd numbers
return array;
}//end of Odds Method
public static int[][] Evens(int x, int y){ //Creating the third 2D array that will hold all even values
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){//for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 ==0){//if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;//algorithm used for third array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;// declaring integer to sum up all the even values
for (int row=0; row < array.length; row++){//for loop to create array
for (int column=0; column < array[row].length; column++){//nested for loop
sum = sum + array[row][column];// algorithm used to sum up all even numbers
}
}
System.out.printf("The total of all the even numbers added together is: %2d\n", sum);// format print used to display sum of all even numbers
return array;
}//end of Evens method
public static void main(String[] args){//main method
int[][]array = new int[15][15];//create array to pass to arrays method
array = Table(15,15);
for(int row=0; row < array.length; row++){ //for loop to properly display array in a square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Odds(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Evens(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
}//end of main method
}//end of public class arrayprgm1
You can't replace a zero with a character like space in an array containing integers as you intend to do it. Instead what you need to do this is handle this when you output the array and check for zero values there.
For instance
for(int row=0; row < array.length; row++){
for(int column=0; column<array[row].length;column++){
int value = array[row][column];
if (value == 0) {
System.out.printf(" ");
else {
System.out.printf("%4d",value);
}
}
}

Calling a method to print an array in single line

I've been trying to work out what is wrong but I can't seem to figure it out. Essentially my code will get the user to input N size of array. The array will then be filled with random numbers generated from 1-100. I have a printArray method which prints the elements of an array in a single line that I've tested on a fixed array and it works, but when I call it from the generated array it gives me a lot of extra 0's.
Here is the code:
Scanner scan = new Scanner(System.in);
System.out.println("Size of array:"); //prompts the user enter size of array
int size = scan.nextInt();
int array[] = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) + 1;
printArray(array);
and here is the display method:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i == 0) {
System.out.print(array[i]);
}
else if (i == array.length) {
System.out.print(array[i]);
}
else
System.out.print("," + array[i]);
}
}
When I run the code it will generate an output like this:(3 as example)
Size of array to sort?
3
36,0,036,68,036,68,75, where it's supposed to just be 36,68,75.
You are printing the array multiple times in a single line.
In the first iteration you print 36,0,0, In the second iteration you print 36,68,0 and only in the final iteration you print the fully initialized array - 36,68,75.
Move printArray(array); to the end of the loop. You might want to add a println at the end of printArray.
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) + 1;
}
printArray(array);

Categories