Inputs needed in completing the solution - java

I am trying to solve a problem on multi dimensional array using Java. I need to print all the numbers appearing diagonally for a given two dimensional matrix. I have done for one scenario but not able to do for the rest of the elements
public class TwoDimensionalArray {
private static int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12,}, {13,14,15,16}};
public static void main(String args[]){
for (int i=0;i<4; i++){
for(int j=0;j < 4; j++){
System.out.print(" "+ array[i][j] +" ");
}
System.out.println();
}
System.out.println();
for (int i = 0;i < 4; i++){
int offset = 0;
for(int j = offset;j <= i; j++){
System.out.print("i >> "+i+" ");
System.out.print("j >> "+j);
System.out.println(" == "+ array[i][i+offset] +" ");
}
offset++;
}
}
}
I started off writing the below code to get the first diagonal elements printed correctly.
for (int i = 0;i < 4; i++){
int offset = 0;
System.out.print(array[i][i+offset] +" ");
offset++;
}
Output: 1 6 11 16
But when I try to extend the same approach by adding inner for loop, I start iterating from 0 till i every time which results it printing the elements more than one time and not with correct output. Is my approach right or I am missing something when implementing the inner for loop.
The desired output should be like below:
1 6 11 16
2 7 12
3 8
4
5 10 15
6 11 16
7 12
8
9 14
10 15
11 16
12
This is not an assignment. I am just trying to improve my programming skills. Also please let me know the difficulty level of this problem on a scale of 1 to 5, 5 being hardest and 1 being simple.

I suppose you're looking for something like this:
private static int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12,}, {13, 14, 15, 16}};
private static void f(int y, int x) {
while ((y < 4) && (x < 4))
System.out.print(array[y++][x++] + " ");
System.out.println();
}
public static void main(final String args[]) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
f(i, j);
}

Related

I need to get all even numbers from random length 2D Array and make another 2D array with even numbers I've got

My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]

Java: Print out longest sequence of an integer array. Where's the problem?

The task is to let the user input 10 numbers into an array. Then to print out how long the longest sequence of growing numbers is.
So for 1 8 45 6 5 4 5 8 10 65 the longest sequence would be 4 5 8 10 65, which is length = 5
public class Main {
public static void main(String[] args) {
int []a = new int[10];
int c = 1;
int max = 0;
for(int i=0; i<a.length; i++){
a[i] = In.readInt();
}
for(int i=0;i<a.length-1;i++){
if(a[i]<a[i+1]){
++c;
if(c>max){
max=c;
}
}else{
c=1;
}
}
Out.print("Length = " + max);
}
}
The program I'm submitting this to says this is only 75% correct and I can't for the life of me figure out why, it works with every combination of numbers I could come up with.
I think you are on the right track, a slight modification of the if condition inside your for-loop by moving the increment of c (which I have presumed stands for counter/count)? inside it should make it work with all test cases:
import java.util.Arrays;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int aLength = 10;
int a[] = new int[aLength];
System.out.printf("Enter %d integers separated by spaces: ", aLength);
try (Scanner scanner = new Scanner(System.in)) {
for (int i = 0; i < aLength; i++) {
a[i] = scanner.nextInt();
}
}
int maxLength = 1, counter = 1;
for (int i = 0; i < aLength - 1; i++) {
if (a[i] < a[i + 1]) {
counter++;
maxLength = Math.max(maxLength, counter);
} else {
counter = 1;
}
}
System.out.printf("Max length is %d\n", maxLength);
}
}
Example Usage:
Enter 10 integers separated by spaces: 1 8 45 6 5 4 5 8 10 65
Max length is 5
Note technically a subsequence/sequence does not have to be continuous (if you were looking the longest subsequence with growing numbers the answer would be 6, i.e., 1, 5, 4, 8, 10, 65) however from what your required output is i.e., 5, it is clear you are looking for the longest sub-array or continuous subsequence/sequence.

Bubble sorting module not working seems; output wrong list (java)

I am writing a program that should output an array, the elements of the array reversed, the sum of the array, the average of the array, min and max of array, and the array sorted (ascending by selection sort and descending by bubble sort). Everything seems to check out, BUT the module descendingOrderBBS()'s output is incorrect. This is my code so far:
import java.util.Scanner;
import java.lang.String;
public class Main
{
public static String input;
public static int n;
public static void main(String[] args)
{
int[] file1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] file2 = new int[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int[] file3 = new int[]{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
inputData();
switch (input)
{
case "file1":
{
System.out.println("original array: ");
printArray(file1);
System.out.println(" ");
System.out.println("reversed array: ");
reverseArray(file1);
System.out.println(" ");
System.out.println("The sum of all elements: " + sum(file1));
System.out.printf("The average of all elements: %.1f%n", average(file1));
max(file1);
min(file1);
//System.out.printf("Array in ascending order (Selection Sort): %-10s", ascendingOrderSS(file1));
ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
//System.out.printf("Array in ascending order (Bubble Sort): %-10s", ascendingOrder(file1));
break;
}
case "file2":
{
System.out.println(file2);
break;
}
case "file3":
{
System.out.println(file3);
break;
}
default :
{
Scanner keyboard = new Scanner(System.in);
System.out.println("File not found, try again: ");
inputData();
break;
}
}
}
private static String inputData()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please input file: ");
input = keyboard.nextLine();
return input;
}
private static void printArray(int f[])
{
for (int i = 0; i < f.length; i++)
{
System.out.printf("%-10s", f[i]);
}
}
private static void reverseArray(int f[])
{
int end = f.length - 1;
for (int start = 0; start < end; start++, end--)
{
int temp = f[start];
f[start] = f[end];
f[end] = temp;
}
for (int i = 0; i < f.length; i++)
{
System.out.printf("%-10s", f[i]);
}
}
private static int sum(int f[])
{
int sum = 0;
for (int i = 0; i < f.length; i++)
{
sum += f[i];
}
return sum;
}
private static float average(int f[])
{
float average = 0;
int sum = 0;
for (int i = 0; i < f.length; i++)
{
sum += f[i];
}
average = sum / f.length;
return average;
}
private static void max(int f[])
{
int largest = f[0];
for (int i = 0; i < f.length; i++)
{
if (f[i] > largest)
{
largest = f[i];
}
}
System.out.println("Max: " + largest);
}
private static void min(int f[])
{
int smallest = f[0];
for (int i = 0; i < f.length; i++)
{
if (f[i] < smallest)
{
smallest = f[i];
}
}
System.out.println("Min: " + smallest);
}
private static void descendingOrderBBS(int f [])
{
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < f.length; i++)
{
for (j = i + 1; j < f.length; j++)
if (f[i] < f[j])
{
temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
System.out.println("Array in descending order (Bubble Sort): ");
for (int x = 0; x < f.length; x++)
{
System.out.printf("%-10s", f[x]);
}
}
private static void ascendingOrderSS( int f [])
{
int a = 0;
int b = 0;
int minIndex = 0;
for (a = 0; a < f.length - 1; a++)
{
minIndex = a;
for (b = a + 1; b < f.length; b++)
{
if (f[b] < f[minIndex])
{
minIndex = b;
}
}
int temp = f[minIndex];
f[minIndex] = f[a];
f[a] = temp;
}
System.out.println("Array in ascending order (Selection Sort): ");
for (int x = 0; x < f.length; x++)
{
System.out.printf("%-10s", f[x]);
}
}
}
Here is the whole program run together
Please input file: file1
original array:
1 2 3 4 5 6 7 8 9 10
reversed array:
10 9 8 7 6 5 4 3 2 1
The sum of all elements: 55
The average of all elements: 5.0
Max: 10
Min: 1
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
2 1 3 4 5 6 7 8 9 10
Process finished with exit code 0
I've tried changing the variables to a/b instead of i/j. I made all the modules private to see if that would make a difference, but nothing I've tried has done a thing. Oh and I've also tried using different IDEs.
This is the output with both sorting modules together:
ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
2 1 3 4 5 6 7 8 9 10
Process finished with exit code 0
Output with ascending module ignored:
//ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
Array in descending order (Bubble Sort):
10 9 8 7 6 5 4 3 2 1
Process finished with exit code 0
I'm not sure on why descendingOrderBBS() is changing. I've been up till 5:12am finishing this last project.
All fixed:
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
10 9 8 7 6 5 4 3 2 1
Process finished with exit code 0
For your first issue why it's printing 5.0 and not 5.5 is because sum / f.length is a division of integers and the value after the . will be dropped, however turning sum into float or casting sum to float will solve this issue.
Your current code (this prints 1.0):
float average = 3 / 2;
System.out.println(average);
The fix (this prints 1.5):
float sum = (float)3 / 2;
System.out.println(sum);
3 and 2 are the variables sum and f.length in your code.

Multidimensional array in Java with for function - Schildt

This multidimensional array of displayed in Schildt' book, 9th edition.
I do not understand how the output, except for the 0, 1, 2, 3, 4.
Can you explain how the other for loop works?
I understand that 4 and 5 are the number of rows and columns, but I do not comprehend the values: 15, 16, 17, 18, 19.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
The loops are executed and k is incremented for total 4*5 = 20 times. Here is how the program is executed
for(i=0; i<4; i++) // Run outer loop 4 times
for(j=0; j<5; j++) { // For every outer loop iteration, run inner loop 5 times
twoD[i][j] = k;
k++; // for every inner loop iteration, increment k by 1
}

Square Array Program

Using java, I am supposed to create a program that stores the square of the numbers 0, 1, 2 & 9 in an ArrayList of 10 elements.
I have created part of the code that displays the numbers and its squares but the program goes straight down with all the numbers and does not look organized. Can someone help me write it out like like this instead:
number: 0 square: 0
number: 1 square: 1
number: 2 square: 4
Code
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int value : temp) {
System.out.println(value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(value);
}
}
You need just one loop like this :
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i] + "\t" + (int)Math.pow(temp[i], 2));
}
}
OutPut
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
If you want to store your results in an ArrayList you can use :
List<int[]> array = new ArrayList<>();//create a List which take an array of int
int arr[] = new int[2];//create a temporary array of 2 elements
for (int i = 0; i < temp.length; i++) {
System.out.println("Number: " + temp[i] + " \tSquare: " + (int) Math.pow(temp[i], 2));
arr[0] = temp[i];//add your number to your array pos 1
arr[1] = (int) Math.pow(temp[i], 2);//add the power to the 2ed position
array.add(arr);//add your array to your list
}
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
// here you are printing all your numbers in the array, so the output will be:
// 0
// 1
// ...
// 9
for (int value : temp) {
System.out.println(value);
}
// after that, you calculate and store them in the same array; so your array now look like this:
// [0,1,4,9,...,81]
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
// here you are printing again your array
// 0
// 1
// 4
// ...
// 81
for (int value : temp) {
System.out.println(value);
}
}
to get your desired outcome, you have to calculate the number before printing everything... one option will be to create another array
int[] square = new int[9];
calculate in the first for loop and save the result in the square array and print them, something like this:
for (int i = 0; i < temp.length; i++) {
square[i] = (int) Math.pow(temp[i],2);
System.out.println("number " + temp[i] + " square: " + square[i]);
}
Assuming the original question which referred to an ArrayList was correct (the OP's example only had an array), and assuming the results are supposed to be stored in the array (per the question), then the following will work:
public static void main(String[] args)
{
// instantiate ArrayList
List<Double> array = new ArrayList<>();
// load the values
for (int i = 0; i < 10; ++i) {
array.add(i, Math.pow(i, 2));
}
// output
for (int i = 0; i < array.size(); ++i) {
System.out.println(String.format("%2d\t%3.0f", i, array.get(i)));
}
}
Output:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
Try this :
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
for (int value : temp) {
System.out.println("number : "value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(" square : " + value + "\n");
}
}

Categories