Array elements Comparison Java - java

As a beginner I am doing online problems to understand arrays, this is not homework but practice. Any advice helps!
The code should take user input.
Problem:
Print two space-separated integers denoting the respective comparison scores earned by A and B.
Sample Input
5 6 7
3 6 10
Sample Output
1 1
Explanation
In this example:
A = (a0, a1, a2) where the values are (5,6,7)
B = (b0,b1,b2) where the values are (3,6,10)
Compare each individual score:
a0 > b0 ==> so A receives 1 point.
a0 = b0 ==> nobody receives a point.
b0 > a0 ==> so B receives 1 point.
A's comparison score is 1 and B's comparison score is 1. Thus, we print 1 1 on a single line.
Approach 1:
First I though of implementing this as a 2d array but I only got this far as I am not sure where to implement the comparison:
public class CompareElem2DArray{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int array2d [][]= new int[3][3];
System.out.println("Please enter 3 marks for A and 3 marks for B: ");
for(int a = 0; a<3; a++) //row
{
for(int b=0; b<3; b++)//column
{
int array2d[a][b] = in.nextInt();
}
}
for (int column = 0; column<3; column++)
{
for(int row=0; row<3; row++)
{
System.out.println( array2d[column][row]+" ");
}
}
System.out.println();
}
}
Approach 2:
This is my second attempt without using 2D arrays.
public class Comparison {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a0 = in.nextInt();
int a1 = in.nextInt();
int a2 = in.nextInt();
int b0 = in.nextInt();
int b1 = in.nextInt();
int b2 = in.nextInt();
int a[] = new int[3];
int b[] = new int[3];
int firstAns = 0;
int secondAns = 0;
for(int i = 0; i<3; i++)
{
int a[i] = in.nextInt();
System.out.println(a[i]);
}
for(int j = 0; j<3; j++)
{
int b[j] = in.nextInt();
System.out.println(b[j]);
}
for(int z = 0; z<3; z++)
{
if(a[z]>b[z])
{
firstAns++;
}
else if(a[z]<b[z])
{
secondAns++;
}
else
{
return;
}
}
System.out.println(firstAns);
System.out.println(secondAns);
}
}

You can try doing
int[] ar = {5,6,7,3,6,10};
int halflen= (ar.length)/2;
int[] result = new int[halflen];
for(int i=0,j=halflen;i<halflen;i++,j++)
{
result[i]=ar[i]-ar[j];
}
Now you have a array with 3 results , if 0 is draw whatever how is > 0 made the point you can eliminate the array inside loop if you want and add your if ther too like :
If (ar [i] > ar [j]) A++;
If (ar [i]<ar [j]) B++;

In approach 1., I think that what you need is [3][2] or [2][3] array (you have 2 sets of data, in one set there are 3 numbers).
Then the comparison goes in second loop (in this case, array2d is [3][2]):
for(int i=0; i<3; i++)
{
//comparison goes here
}
You need to compare values of array2d[i][0] with array2d[i][1].
When input is: 5 6 7 3 6 10
Your 2d array is something like:
5 6 7
3 6 10
So the second loop is comparing 5 with 3, 6 with 6 and 7 with 10.

Related

Failed to recognize number sorting array at new array in JAVA

I am having a trouble when it is starting to sort the array in chronological number, first and foremost, I built a 2 scanner array that will merge in the final line but it resulted a mess and the last line character line were flashed a 0
Here is my source code:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner x = new Scanner (System.in);
System.out.print("Enter the number of elements of the first array: ");
int first = x.nextInt();
int ffinal[] = new int[first];
for(int i=0;i<ffinal.length;i++)
{
System.out.print("");
ffinal[i]=x.nextInt();
}
System.out.print("Enter the number of elements of the second array: ");
int second = x.nextInt();
int sfinal[] = new int[second];
for(int i=0;i<sfinal.length;i++)
{
System.out.print("");
sfinal[i]=x.nextInt();
}
int n = ffinal.length;
int m = sfinal.length;
int res[] = new int [n+m];
int i = 0, j=0, k=0;
while(i< n && j<m )
{
if(ffinal[i] <= sfinal[j])
{
res[k]=ffinal[i];
i+=1;
k+=1;
}
else
{
res[k]=sfinal[j];
j+=1;
k+=1;
}
}
System.out.print("New array:");
for (i=0; i<n+m;i++)
{
System.out.print(" "+res[i]);
}
}
}
Output:
Enter the number of elements of the first array: 3
2 3 10
Enter the number of elements of the second array: 2
10 16
New array: 2 3 10 0 0
Expected Output:
Enter the number of elements of the first array: 3
2 3 10
Enter the number of elements of the second array: 2
10 16
New array: 2 3 10 10 16
The issue is with your while condition while(i< n && j<m ).
Suppose all your elements of 1st array is smaller than 2nd array, after adding those to the new array, i will be equal to n, so the condition i<n in while(i< n && j<m ) becomes false and exits the loops.
The elements of 2nd array is not added to the new array.
Assume your a1[] = {1,2} and a2[] = {3,4,5}.
n is 2 and m is 3.
as per your code, 1 and 2 will be added to new array a3[].
now i will become 2 while j is still 0.
In this while(i< n && j<m ), i<n which is 2<2 is false. So the while-loop will stop.
Then what about the elements of array a2? {3,4,5} is not added to new array a3.
You can do as #UnholySheep suggested. If you want to continue with yours,
I've corrected your code.
int i = 0, j=0, k=0;
while(i< n || j<m )
{
if(i<n && i<m)
{
if(ffinal[i] <= sfinal[j])
{
res[k]=ffinal[i];
i+=1;
k+=1;
}
else
{
res[k]=sfinal[j];
j+=1;
k+=1;
}
}
else if(i<n)
{
res[k]=ffinal[i];
i+=1;
k+=1;
}
else
{
res[k]=sfinal[j];
j+=1;
k+=1;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner x = new Scanner (System.in);
System.out.print("Enter the number of elements of the first array: ");
int first = x.nextInt();
int a[] = new int[first];
for(int i=0;i<a.length;i++)
{
System.out.print("");
a[i]=x.nextInt();
}
System.out.print("Enter the number of elements of the second array: ");
int second = x.nextInt();
int b[] = new int[second];
for(int i=0;i<b.length;i++)
{
System.out.print("");
b[i]=x.nextInt();
}
int j = 0, k = 0;
int c [] = new int[a.length+b.length];
for (int i = 0; i < c.length; i++)
{
if (j < a.length && k < b.length)
{
if (b[k] < a[j])
{
c[i] = b[k];
k++;
}
else
{
c[i] = a[j];
j++;
}
}
else if (k < b.length)
{
c[i] = b[k];
k++;
}
else
{
c[i] = a[j];
j++;
}
}
System.out.print("New array: ");
for(int i = 0; i < c.length; i++)
{
System.out.print(c[i]+" ");
}
}
}
Thank you I answered it!
Look at the trace here for your code
n:2, m:3
i:0,j:0,k:0 | first array 2 3 | second array 10 16 | New array: 0 0 0 0 0
i:1,j:0,k:1 | first array 2 3 | second array 10 16 | New array: 2 0 0 0 0
i:2,j:0,k:2 | first array 2 3 | second array 10 16 | New array: 2 3 0 0 0
At the end of the loop, i has the value 2
In while loop condition while(i< n && j<m ), i<n -> 2<2 will give false and the condition fails and exits the loop.
but as you can see there are elements still remaining in second array so what you need to do is add two additional loops.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner x = new Scanner (System.in);
System.out.print("Enter the number of elements of the first array: ");
int first = x.nextInt();
int ffinal[] = new int[first];
for(int i=0;i<ffinal.length;i++)
{
System.out.print("");
ffinal[i]=x.nextInt();
}
System.out.print("Enter the number of elements of the second array: ");
int second = x.nextInt();
int sfinal[] = new int[second];
for(int i=0;i<sfinal.length;i++)
{
System.out.print("");
sfinal[i]=x.nextInt();
}
int n = ffinal.length;
int m = sfinal.length;
int res[] = new int [n+m];
System.out.println();
int i = 0, j = 0, k = 0;
while(i < n && j < m )
{
if(ffinal[i] <= sfinal[j])
{
res[k]=ffinal[i];
i+=1;
k+=1;
}
else
{
res[k]=sfinal[j];
j+=1;
k+=1;
}
}
// if there are any remaining elements from any of the two arrays add them to res array
while(i < n){
res[k]=ffinal[i];
i+=1;
k+=1;
}
while(j < m){
res[k]=sfinal[j];
j+=1;
k+=1;
}
System.out.print("New array:");
for (i=0; i<n+m;i++)
{
System.out.print(" "+res[i]);
}
}
}
In the above code it first checks i < n -> 2<2 -> false,
it then goes to the next while loop j < m -> 0 < 3 -> true so loop throught elements in second array and add into the res array
I would separate the code that perform the merge from the input parsing, it will make the code more testable, furthermore, this request the two input arrays to be sorted.
import java.util.Objects;
public class MyClass {
public static int[] merge(int[] first, int[] second) {
//Check that the input are not null
Objects.requireNonNull(first, "First array cannot be null");
Objects.requireNonNull(first, "Second array cannot be null"); // duplicates are allowed so the result size is known up-front
int[] result = new int[first.length + second.length];
// cursor over the three arrays, starting from the beginning
int f = 0;
int s = 0;
int r = 0;
//loop over first array until is complete
for (; f != first.length; ++r) {
if (s == second.length) {
//if nothing left in the second array, let's copy everything
//from first into result and return
System.arraycopy(first, f, result, r, first.length - f);
return result;
}
// let's copy the smaller of the two into result
if (second[s] < first[f]) {
result[r] = second[s];
++s;
} else {
result[r] = first[f];
++f;
}
}
//we complete the loop over first, let's copy everything left from
//second to result
System.arraycopy(second, s, result, r, second.length - s);
return result;
}
//use JUnit instead, I am using an online compiler and
// I cannot bring dependencies in
public static void check(int[] a, int[] b) {
assert(a.length == b.length);
for (int i = 0; i < a.length; i++)
assert(a[i] == b[i]);
}
public static void main(String args[]) {
check(new int[]{2, 3, 10, 10, 16}, merge(new int[]{2, 3, 10}, new int[]{10, 16}));
check(new int[]{2, 3, 10}, merge(new int[]{2, 3, 10}, new int[]{}));
check(new int[]{10, 16}, merge(new int[]{}, new int[]{10, 16}));
check(new int[]{2, 3, 5, 10, 10, 16}, merge(new int[]{2, 3, 10}, new int[]{5, 10, 16}));
}
}
UPDATE
replace while loop with System.arraycopy

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

System.out.println is not printing output

Here is my code to find even Fibonacci numbers and to add them:
package a;
import java.util.*;
public class A {
//this about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] n = new int[t];
int[] nn = new int[t];
int i,j,sum;
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
nn[0]=1;
for(i = 0 ; i<t;i++){
sum = 0;
for(j= 1;j<n[i];j++){
nn[j] = j+nn[j-1];
if(nn[j]%2==0)
{
sum += nn[j];
}
}
System.out.println(sum); //this is not printing the output
}
}
}
Sample Input
2
10
100
Sample Output
10
44
The problem is that this line System.out.println(sum); is not printing anything.
Any ideas?
In your code you have
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
The problem is that the program is waiting for you to enter t integers. I don't know what values you want there, but change it to something more like this
for(int a0 = 0; a0 < t; a0++){
n[a0] = 0;//But instead of 0 the actual number that you want to set for the value.
}
I hope you find this helpful!
I do not see a problem here. Just took the code, compiled and executed it. After specifying the value for t and also providing t input values, I saw an output on the console.
stefan#linux-3047:~$ java A
5 (t)
1 (1st of 5 values)
2 (2nd of 5 values)
3 (3rd of 5 values)
4 (4th of 5 values)
5 (5th of 5 values)
0 (System.out.println)
2 (System.out.println)
6 (System.out.println)
6 (System.out.println)
6 (System.out.println)
Multiple problems exist here.
One error at line 25 if the t for example is 5:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at application.A.main(A.java:25)
Added some System.out.println(...) to see how you can fix it cause i don't know the code you want to add:
package application;
import java.util.*;
public class A {
// This about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
System.out.println("Enter a number below:\n");
Scanner in = new Scanner(System.in);
int t = in.nextInt();
System.out.println("You entered..." + t+"\n");
// Arrays
int[] n = new int[t];
int[] nn = new int[t];
int i, j, sum;
// First For Loop
for (int a0 = 0; a0 < t; a0++) {
System.out.println("Enter a number a0..");
n[a0] = in.nextInt();
System.out.println("You entered ao=:" + a0+"\n");
}
nn[0] = 1;
// Second For Loop
for (i = 0; i < t; i++) {
sum = 0;
for (j = 1; j < n[i]; j++) {
nn[j] = j + nn[j - 1];
if (nn[j] % 2 == 0) {
sum += nn[j];
}
}
// this is not printing the output
System.out.println("Sum is:="+sum);
}
}
}

fixing Exception in main thread

Everything with my code seems to work correctly, whenever the boolean method returns true. However, when trying to test false, after the user enters 10 numbers I receive the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at FunArrays.main(FunArrays.java:15
What am I missing or overlooking with my code?
Here is my code:
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter ten numbers....");
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
boolean lucky = isLucky(userArray);
if (lucky){
sum(userArray);
} else
sumOfEvens(userArray);
}
public static boolean isLucky(int [] numbers){
for (int i = 0; i <= numbers.length; i++){
if (numbers[i]== 7 || numbers[i] == 13 || numbers[i] == 18){
return true;
}
}
return false;
}
public static void sum(int [] numbers){
int sum = 0;
for (int x = 0; x <= numbers.length -1; x++){
sum += numbers[x];
}
System.out.println(sum);
}
public static void sumOfEvens(int [] numbers){
int evens = 0;
for (int y = 0; y <= numbers.length -1; y++){
if (numbers[y] % 2 == 0){
evens += numbers[y];
}
}
System.out.println(evens);
}
}
You are entering 10 numbers but your array has only 9 spots. Change it to
int [] userArray = new int [10];
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
Your array size is 9 (from index 0 to index 8) and your loop increment b from 0 to 9 (10 cases)
In this case b should be less than 9 in your loop.
So you could replace by this code:
int maxInput = 9;
int [] userArray = new int [maxInput];
for(int b = 0; b < maxInput ; b++){
userArray [b] = input.nextInt();
}
You should declare a size 10 array, since you are accepting 10 values from the user.
int [] userArray = new int [9];
Here is a good read on Arrays: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html
You're trying to store 10 numbers in an array of length 9.
Use int[] userArray = new int[10];

How to print the number according to the ranks of a student

input:
4
22 96 12 49
output:
2 4 1 3
What I want in output is the rank of a student according to the input.
However what I was trying til now is going wrong.
int count=0;
Scanner sc =new Scanner(System.in);
System.out.println("enter a number");
int a =sc.nextInt();
long[] b=new long[a];
for (int i = 0; i < a; i++) {
b[i]=sc.nextLong();
}
Arrays.sort(b);
for (int j = a-1; j >= 0; j--) {
System.out.println(b[j]);
count++;
System.out.println(count);
}
You can take help from the utility Arrays Java has! Use indexOf, binarySearch etc. to find the index of a given element from an array.
Scanner sc =new Scanner(System.in);
System.out.println("enter a number");
int a =sc.nextInt();
long[] b = new long[a];
for (int i = 0; i < a; i++) {
b[i]=sc.nextLong();
}
long[] tem = new long[a];
System.arraycopy(b, 0, tem, 0, a);
Arrays.sort(b);
for (int i = 0; i < a; i++) {
int res = java.util.Arrays.binarySearch(b, tem[i]);
System.out.print(res + 1 + " ");
}
This program gives:
input:
4
22 96 12 49
output:
2 4 1 3
Look, if the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(value)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, value)
You have to maintain the original index in order to print the way you want.
Instead of creating an integer array, create a 'wrapper' array. So even after sorting, you know the original index of the element so you will be able to put it's rank in the correct index.
Class Wrapper{
Int index;
Int value ;
}
Wrapper [] input;
For(int I=0; I< n ; I++){
Int value = scan next value;
Input[i] = new Wrapper (I,value);
}
sort input based on value; // ascending order
Int[] output;
For(int I=0; I < input.length; I++){
output[input[i].index] = i+1; // to start the rank from 1.
}
Print output array

Categories

Resources