How to print matching elements in different positions between two arrays? (java) - java

I have two arrays. Array1 holds 5 randomly generated numbers and array2 holds 5 guesses inputted by the user. I'm trying to count the matches but the only matches that are being read are the ones in the same position. How can I get my program to count the same number even if it's in a different position?
Here's what I've got so far:
int count = 0;
for (i=0;i<array1.length;i++){
if(array1[i] == array2[i]){
count = count +1;
}
}
System.out.println("matching numbers : "+count);

If the two arrays are both small, i.e. each array contains only five elements, then you need a nested loop. For each element in the random numbers array, iterate through the guesses array.
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
count++;
}
}
}
System.out.println("matching numbers : "+count);
Note that the above is appropriate when both arrays are small. When both arrays are large the above is not appropriate.

You just need the intersection between the two arrays and then to count the size of the result array.
So you can avoid to manually loop over the two arrays just simply using the retainAll method on List class:
https://docs.oracle.com/javase/7/docs/api/java/util/List.html#retainAll
Here is a junit test that shows how to solve using this approach:
#Test
public void TestArraysIntersection() {
Integer[] randomlyGenerated = {1,2,3,4,5};
Integer[] userInput = {4,2,5,3,6};
System.out.println("Randomly generated numbers are: " + Arrays.toString(randomlyGenerated));
System.out.println("Number selected by the user are: " + Arrays.toString(userInput));
List<Integer> intersectionList = new ArrayList<>(Arrays.asList(randomlyGenerated));
intersectionList.retainAll(Arrays.asList(userInput));
System.out.println("Matching numbers are " + intersectionList.size() + " and the values are: "+ intersectionList);
}
Test result is the following:
Randomly generated numbers are: [1, 2, 3, 4, 5]
Number selected by the user are: [4, 2, 5, 3, 6]
Matching numbers are 4 and the values are: [2, 3, 4, 5]

You need to loop through both arrays. In your code you are comparing each element of one array with the element in the same position of the other array, but you have to compare each element of one array with every element of the other array, like this:
public class MyClass {
public static void main(String args[]) {
int[] numbers = {1, 3, 0, 6};
int[] guesses = {3, 8, 5, 1, 2};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < guesses.length; j++) {
if (numbers[i] == guesses[j]) {
System.out.println("A match on positions "+i+" and "+j+". "+numbers[i]+" = "+guesses[j]);
}
}
}
}
}
Output:
A match on positions 0 and 3. 1 = 1
A match on positions 1 and 0. 3 = 3
Of course, instead of outputting the values that match, you can instead increment a count like in your example, and show instead how many elements matched.

Related

Maximum of each pair of index of the array

I need to create an array, compare each pair of this array, and then find and print the largest element of each pair. I have created an array like below, but it's printing me only the two largest of the whole array!
public class Main {
public static void main(String[] args) {
int[] arr = {1, -5, 2, 6, 10, 7};
int a = arr[0];
int b = arr[1];
for (int i = 0; i<arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (a > b || b > a) {
a = arr[i];
b = arr[j];
}
}
}
System.out.println(a);
System.out.println(b);
}
}
In the example below, I have 3 pairs (6 elements) and I want to get maximum of each pair as an example:
Input: {1, -5, 2, 6, 10, 7}
Output: 1, 6, 10
I appreciate any help you can provide.
Your program does not print the two largest numbers. It prints the two last numbers of the array. If you add a 200 in the mid of the array, it will still print 10 and 7.
Also, the System.out.println()-lines are outside any loop, so they will run only once.
If you want to get the higher number out of the first and second, the third and fourth, fifth and sixth element and so on (due to the expected output, I assume this is what you want to get), then the for-loop will fail like this. On each run of the loop, it will check if a > b or b > a. If that's the case, a gets the value of arr[i] and b the value of arr[j]. On the last run, i will be the second last value and j the last value of the array, so you will always get the last two elements. Unless you compare two times the same value in the array, then a and b will get the same value and nothing will change anymore from there.
If you want to compare the pairs like I described, then maybe you should instead try something like this:
for(int i = 0; i < arr.length; i+=2)
{
if(!(i == arr.length-1)) // in case there is no i+1 index anymore
{
if(arr[i]>arr[i+1])
{
System.out.println(arr[i]);
}
else if(arr[i+1]>arr[i])
{
System.out.println(arr[i+1]);
}
}
}

How can I get N smallest number in an array?

I'm trying to get the N smallest numbers (given by the user) in an array without using methods like sort()... in the last step, I keep getting only the smallest values and 0 for the rest.. where's the problem?
//1- Scanner to take inputs
Scanner input = new Scanner(System.in);
//2- Take the array size as input and store it in "sizeOfArr" var
System.out.print("Enter the array size: ");
int sizeOfArr = input.nextInt();
//3- Assign the input as an array size
int array[] = new int[sizeOfArr];
//4- Looping on the array and update its values by inputs taken from the user
for(int i = 0; i < array.length; i++) {
System.out.print("Enter "+ (i+1) + "-st element: ");
array[i] = input.nextInt();
}
//5- Print out the array after convert it to String
System.out.println(Arrays.toString(array));
//6- Find the smallest element in the array and print it
int minVal = array[0];
for(int i = 0; i < array.length; i++) {
if (array[i] < minVal) {
minVal = array[i];
}
}
// System.out.println(minVal);
//7- Find the (n) smallest of number defined by the user
System.out.print("Enter the number of smallest numbers do you want: ");
int n = input.nextInt();
//8- new array to store n smallest numbers
int smallestNums[] = new int[n];
//9- trying to loop on the original array n times
int counter;
for(int i = 0; i < n ; i++) {
//10- trying to loop on the original array to store the smallest values in smallestNum[] array.
for(int j = 0; j < array.length; j++) {
smallestNums[i] = minVal;
}
if(smallestNums[i] == smallestNums[i]) {
break;
}
}
System.out.println(Arrays.toString(smallestNums));
Here is one way. Just do a partial sort with the outer loop limit equal to the number of items required. This is variant of the selection sort. This example, varies n in the outer list for demo purposes.
int[] array = { 10, 1, 5, 8, 7, 6, 3 };
for (int n = 1; n <= array.length; n++) {
int[] smallest = getNSmallest(n, array);
System.out.printf("smallest %2d = %s%n", n,
Arrays.toString(smallest));
}
prints
smallest 1 = [1]
smallest 2 = [1, 3]
smallest 3 = [1, 3, 5]
smallest 4 = [1, 3, 5, 6]
smallest 5 = [1, 3, 5, 6, 7]
smallest 6 = [1, 3, 5, 6, 7, 8]
smallest 7 = [1, 3, 5, 6, 7, 8, 10]
Here is the method. The first thing to do is copy the array so the
original is preserved. Then just do the sort and return array of smallest elements.
public static int[] getNSmallest(int n, int[] arr) {
int[] ar = Arrays.copyOf(arr, arr.length);
int[] smallest = new int[n];
for (int i = 0; i < n; i++) {
for (int k = i + 1; k < ar.length; k++) {
if (ar[i] > ar[k]) {
int t = ar[i];
ar[i] = ar[k];
ar[k] = t;
}
}
smallest[i] = ar[i];
}
return smallest;
}
For this task, you don't have to sort the whole array. Only a group of N elements has to be sorted. I.e. only a partial sorting is required.
Below, I've provided two implementations for this problem. The first utilizes only plane arrays and loops, the second makes use of the PriorytyQueue.
The first solution maintains a variable pos which denotes the position in the result array which isn't assigned yet. Note that the default value for an element of the int[] is 0. It's important to be able to distinguish between the default value and a zero-element from the given array. Hence we can't rely on the values and have to track the number of elements that are assigned.
Every element of the source array gets compared with all the elements of the result array that are already assigned. The new element will be added to the result array in two cases:
nested loop has reached an unoccupied position pos in the result array;
an element in the result array that is greater than the next element from the given array has been found.
In the first case, a new element gets assigned the position denoted by pos. In the second case, a new element has to be inserted
nested loop iterates over the given array at the current position i and all elements must be shifted to the right. That's what the method shiftElements() does.
The First solution - Arrays & Loops
public static int[] getSmallest(int[] arr, int limit) {
int[] result = new int[Math.min(limit, arr.length)];
int pos = 0;
for (int next: arr) {
for (int i = 0; i < Math.min(pos + 1, result.length); i++) {
if (i == pos) result[i] = next;
else if (result[i] > next) {
shiftElements(result, next, i, Math.min(pos + 1, result.length));
break;
}
}
pos++;
}
return result;
}
private static void shiftElements(int[] arr, int val, int start, int end) {
int move = arr[start];
arr[start] = val;
for (int i = start + 1; i < end; i++) {
int temp = arr[i];
arr[i] = move;
move = temp;
}
}
Maybe you'll be more comfortable with the first version, but if you are somehow familiar with the Collections framework, then it's a good time to get acquainted with PriorytyQueue. In the nutshell, this collection is backed by an array and maintains its element in the same order as they were added, but when an element is being deleted collection retrieves the smallest one according to the natural order or based on the Comparator, which can be provided while instantiating the PriorytyQueue. It uses a sorting algorithm that is called a heapsort which allows removing a single element in O(log N) time.
The Second solution - PriorytyQueue
public static int[] getSmallestWithPriorityQueue(int[] arr, int limit) {
Queue<Integer> queue = new PriorityQueue<>();
populateQueue(queue, arr);
int[] result = new int[Math.min(limit, arr.length)];
for (int i = 0; i < result.length; i++) {
result[i] = queue.remove();
}
return result;
}
private static void populateQueue(Queue<Integer> queue, int[] arr) {
for (int next: arr) {
queue.add(next);
}
}
main & utility-method to generate an array
public static void main(String[] args) {
int[] source = generateArr(100, 10);
System.out.println("source : " + Arrays.toString(source));
int[] result1 = getSmallest(source, 3);
System.out.println("result(Arrays & Loops) : " + Arrays.toString(result1));
int[] result2 = getSmallestWithPriorityQueue(source, 3);
System.out.println("result(PriorityQueue) : " + Arrays.toString(result2));
}
public static int[] generateArr(int maxVal, int limit) {
Random random = new Random();
return IntStream.generate(() -> random.nextInt(maxVal + 1))
.limit(limit)
.toArray();
}
output
source : [61, 67, 78, 53, 74, 51, 50, 83, 59, 21]
result(Arrays & Loops) : [21, 50, 51]
result(PriorityQueue) : [21, 50, 51]
Randomized select allows to find k-th ranked element in linear time on average.
It alters the input order, so practically, it makes sense to just sort and return k-th element of the sorted array. Especially if there are several such calls on the given input array.

How to find the even numbers of a list in Java [duplicate]

Code written below is correct, but I want to shorten this code.
Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.
int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {
a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 == 0) {
b[k] = a[j];
k++;
}
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 != 0) {
b[k] = a[j];
k++;
}
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {
System.out.println(b[i]);
}
Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.
Here is a simple program for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* #author Momir Sarac
*/
public class GroupByEvenAndOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a collection
List<Integer> listOfNumbers = new ArrayList<>();
// do code within a loop for 10 times
for(int i=0;i<10;i++)
{
//print to screen this text
System.out.println("Input your number:");
//get next input integer
int number = scanner.nextInt();
// add it to collection
listOfNumbers.add(number);
}
// sort this collection, list of numbers
// convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
//print sorted collection
System.out.println("Ordered list ..." + listOfNumbers);
}
}
In this version, it copies the even to the start, and the odd to the end.
static int[] sortEvenOdd(int... nums) {
int even = 0, odd = nums.length, ret[] = new int[nums.length];
for (int num : nums)
if (num % 2 == 0)
ret[even++] = num;
else
ret[--odd] = num;
return ret;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
int[] sorted = sortEvenOdd(arr);
System.out.println(Arrays.toString(sorted));
}
prints
[2, 4, 6, 10, 9, 7, 3, 1]
This Code will help you to segregate Even and Odd numbers.
// java code to segregate even odd
// numbers in an array
public class GFG {
// Function to segregate even
// odd numbers
static void arrayEvenAndOdd(
int arr[], int n)
{
int i = -1, j = 0;
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them.
Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter.
I created a simple example where I did not check for NumberFormatException when parsing the String to an int:
import java.util.Arrays;
import java.util.Scanner;
public class SortedArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of array: ");
final int arrayLength = Integer.parseInt(scanner.nextLine());
int intArray[] = new int[arrayLength];
for (int l = 0, r = arrayLength - 1; l <= r; ) {
System.out.print("Enter new array value: ");
int v = Integer.parseInt(scanner.nextLine());
intArray[v % 2 == 0 ? l++ : r--] = v;
}
System.out.println("Output: " + Arrays.toString(intArray));
}
}
Sample input/output:
Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]
I recommend reading up on streams, they will make collection processing a lot easier for you
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(0);
//this way you simply traverse the numbers twice and output the needed ones
System.out.println(numbers.stream()
.filter(x->x%2==0)
.collect(Collectors.toList()));
System.out.println(numbers.stream()
.filter(x->x%2==1)
.collect(Collectors.toList()));
//this way you can have the numbers in two collections
numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);
//this way you will have a map at the end. The boolean will tell you if the numbers are odd or even,
// and the list contains the numbers, in order of apparition in the initial list
numbers.stream().collect(Collectors.groupingBy(x->x%2==0));
A performant way to check if a number is even, is to use
if ( (x & 1) == 0 )

How to display the last three elements of an array (my example)

I need to write a code that will display the last three elements of an array using for loop. 1. The arrays size can be modified and the code should cope with that. 2. The elements should be displayed as they were entered (from left to right).
import java.util.Arrays;
public class Task4 {
public static void main(String[] args) {
int[] array = {7, -3, 9, -11, 18, 99, 2, 11};
System.out.println("Current array: " + Arrays.toString(array));
System.out.println("Last three elements of an array: ");
for (int i = array.length / 2 + 1; i < array.length; i++) {
System.out.print(array[i] + " ");
/*need to display last three elements of an array using for loop.
the elements should be displayed as they were entered(from left-to-right)*/
}
}
}
The code works only for this specific array. My question was is there any alternative solutions that will work for any array size?
you can try to start from the index that equals the length-3 by changing the loop into this :
for (int i = Math.max(0,array.length-3); i < array.length; i++) {
A java stream option here:
IntStream.of(array)
.skip(Math.max(array.length - 3, 0))
.forEach(System.out::println);

to display the even number followed by all odd numbers

Code written below is correct, but I want to shorten this code.
Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.
int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {
a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 == 0) {
b[k] = a[j];
k++;
}
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 != 0) {
b[k] = a[j];
k++;
}
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {
System.out.println(b[i]);
}
Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.
Here is a simple program for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* #author Momir Sarac
*/
public class GroupByEvenAndOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a collection
List<Integer> listOfNumbers = new ArrayList<>();
// do code within a loop for 10 times
for(int i=0;i<10;i++)
{
//print to screen this text
System.out.println("Input your number:");
//get next input integer
int number = scanner.nextInt();
// add it to collection
listOfNumbers.add(number);
}
// sort this collection, list of numbers
// convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
//print sorted collection
System.out.println("Ordered list ..." + listOfNumbers);
}
}
In this version, it copies the even to the start, and the odd to the end.
static int[] sortEvenOdd(int... nums) {
int even = 0, odd = nums.length, ret[] = new int[nums.length];
for (int num : nums)
if (num % 2 == 0)
ret[even++] = num;
else
ret[--odd] = num;
return ret;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
int[] sorted = sortEvenOdd(arr);
System.out.println(Arrays.toString(sorted));
}
prints
[2, 4, 6, 10, 9, 7, 3, 1]
This Code will help you to segregate Even and Odd numbers.
// java code to segregate even odd
// numbers in an array
public class GFG {
// Function to segregate even
// odd numbers
static void arrayEvenAndOdd(
int arr[], int n)
{
int i = -1, j = 0;
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them.
Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter.
I created a simple example where I did not check for NumberFormatException when parsing the String to an int:
import java.util.Arrays;
import java.util.Scanner;
public class SortedArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of array: ");
final int arrayLength = Integer.parseInt(scanner.nextLine());
int intArray[] = new int[arrayLength];
for (int l = 0, r = arrayLength - 1; l <= r; ) {
System.out.print("Enter new array value: ");
int v = Integer.parseInt(scanner.nextLine());
intArray[v % 2 == 0 ? l++ : r--] = v;
}
System.out.println("Output: " + Arrays.toString(intArray));
}
}
Sample input/output:
Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]
I recommend reading up on streams, they will make collection processing a lot easier for you
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(0);
//this way you simply traverse the numbers twice and output the needed ones
System.out.println(numbers.stream()
.filter(x->x%2==0)
.collect(Collectors.toList()));
System.out.println(numbers.stream()
.filter(x->x%2==1)
.collect(Collectors.toList()));
//this way you can have the numbers in two collections
numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);
//this way you will have a map at the end. The boolean will tell you if the numbers are odd or even,
// and the list contains the numbers, in order of apparition in the initial list
numbers.stream().collect(Collectors.groupingBy(x->x%2==0));
A performant way to check if a number is even, is to use
if ( (x & 1) == 0 )

Categories