removing similar element from the array from sum of any two integer - java

My input is one integer suppose M and the program must print all the combination of two integer x and y where x + y = M.
Let us take our input as M = 50 and array element as 25 20 25 30 15 45 45 5
and my required output is
5 45,20 30,25 25.
But my output is coming as
5 45,5 45,20 30,25,25
How to remove the occurrence of that two times 5 45?
My code is as follows
Scanner s = new Scanner(System.in);
int m = s.nextInt();
s.nextLine();
String str = s.nextLine();
StringTokenizer st = new StringTokenizer(str);
int len = st.countTokens();
int[] a = new int[len];
String[] temp = new String[len];
for (int i = 0; i < len; i++)
{
temp[i] = st.nextToken();
a[i] = Integer.parseInt(temp[i]);
}
Arrays.sort(a);
for (int i = 0;i < len-1; i++)
{
for(int j = i + 1; j < len; j++)
{
if ((a[i] +a [j]) == m)
System.out.println(a[i] + " " + a[j]);
}
}

use break for skipping repeated number(inner loop) and check (a[i] - a[i+1]) == 0 and use continue to skip repeated number in outer loop.
include only the following changes in the for loop, works perfectly
// Init a new array.
for(int i=0;i<len-1;i++)
{
if((a[i] - a[i+1]) == 0)
continue; // for skipping repeated number in outer loop
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m ) {
System.out.println(a[i]+" "+a[j]);
break; // for skipping repeated number in inner loop
}
else if(a[i] == m/2){
System.out.println(a[i]+" "+a[i]);
break;
}
}
}
input
25 ,20, 25 ,30, 15, 45, 45, 5
output
5 45
20 30
25 25
input
5 ,5 ,45, 45, 45
output
5 45

(5 45) is printed two times as 45 occured 2 times in your input (25 20 25 30 15 45 45 5), if you need distinct pairs remove duplicates from array.
anyway this is not the best optimized solution. for more details check https://www.geeksforgeeks.org/count-pairs-with-given-sum/

you can try to store in a list what you printed and not repeat a print if already printed.
Scanner s=new Scanner(System.in);
int m=s.nextInt();
s.nextLine();
String str=s.nextLine();
StringTokenizer st=new StringTokenizer(str);
int len=st.countTokens();
int a[]=new int[len];
String []temp=new String[len];
for(int i=0;i<len;i++)
{
temp[i]=st.nextToken();
a[i]=Integer.parseInt(temp[i]);
}
Arrays.sort(a);
List<String> output = new ArrayList<>();
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m) {
String msg = a[i]+" "+a[j];
if(!output.contains(msg)) {
System.out.println(msg);
output.add(msg);
}
}
}
}
s.close();

When just printing the correct pairs, you cannot check for the former solutions. You can add a[i] and a[j] whose sum is M to an array. After that, if a new pair summary gives M, you can check the array if elements in it.
Scanner s=new Scanner(System.in);
int m=s.nextInt();
s.nextLine();
String str=s.nextLine();
StringTokenizer st=new StringTokenizer(str);
int len=st.countTokens();
int a[]=new int[len];
String []temp=new String[len];
for(int i=0;i<len;i++)
{
temp[i]=st.nextToken();
a[i]=Integer.parseInt(temp[i]);
}
Arrays.sort(a);
// Init a new array.
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m) {
// if(new array contains a[i]) continue;
//array.add(a[i]);
//array.add(a[j]);
System.out.println(a[i]+" "+a[j]);
}
}
}

I wouldn't try to reinvent the wheel. Just put every pair in a java.util.Set so you only have distinct pairs:
Add this right before your last nested loop:
Set<String> pairs = new HashSet<>();
And change System.out.println(a[i] + " " + a[j]); to pairs.add(a[i] + " " + a[j]);
And in the end you can print the contents of the Set.
Try it online.

Related

Program to read seven integer values and print out the number of occurrences of each value

as the title suggests, i'm trying to input 7 integers and be able to output those integers along with a count for how many duplicates there were among them.
Using the code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
}
}
with the input: 12 23 44 22 23 22 55
I keep getting duplicates in my output, like so:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.
For clarity, what i'm aiming for is:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times
I appreciate any and all suggestions.
You can use a vector to store all occurs for each number
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
int duplicates[] = new int[7];
for(int i = 0; i < 7; i++)
duplicates[i] = 0;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates[i]++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates[i] + " times.");
}
}
The output for the input 12 23 44 22 23 22 55 will be:
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : userInput) {
if (map.containsKey(i))
map.put(i, map.get(i) + 1);
else
map.put(i, 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Number " + entry.getKey() + " occurs " + entry.getValue() + " times.");
}
}
Currently, the program calculates occurrence of each digit in an array and that's where duplicate digits its doing duplicate efforts.
There are different ways of achieving what you are trying to do, the straight forward way could be, store the numbers in a map, which key as number and value as 1, and increment whenever the same digit is encountered again.
There are couple of ways:
Using sorting:
Arrays.sort(userInput);
for(int i=0;i<userInput.length;){
int count = 1;
int j = i + 1;
while(j < userInput.length && userInput[i] == userInput[j]{
j++; count++;
}
System.out.println("Number "+userInput[i]+" occurs "+count +" times");
i = j;
}
This will reduce the time complexity to O(N log N)
you can further improve this till O(N) using HashMap
use HashMap
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i : userInput) {
Integer j = hm.get(i);
hm.put(i, (j == null) ? 1 : j + 1);
}
for (Map.Entry<Integer, Integer> val : hm.entrySet()) {
System.out.println("Number " + val.getKey() + " occurs " + val.getValue() + " times.");
}
You can do the same By using HashMap<Integer, Integer> as shown below.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
HashMap<Integer, Integer> numberCountMap = new HashMap<>();
for(int element : userInput){
numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
}
numberCountMap.forEach((key, value) -> System.out.println("Number " + key + " occurs " + value + " times."));
}
My approach would be -
First of all to change j to j = i+1 because you dont need an extra iteration to confirm that array[i]==array[i].
Second thing is to store the results in a Map<digit , occurances> and print from the map at the end of the method.
for (int i = 0; i < 7; i++) {
int duplicates = 1;
for (int j = i+1; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
map.put(i , duplicates);
It would be more efficient to store the numbers in a Map.
Assuming your input is 12 23 44 22 23 22 55
void duplicates(){
//acquire input and store it in a List
Scanner input = new Scanner(System.in);
List<Integer> numbers = input.nextLine().split(" ");
//store the values into a map
HashMap<Integer, Integer> numbersMap = new HashMap<>();
for(int number : numbers){
//if the map contains the number already, then increase it's occurence by one
//otherwise store it into the map with the value of 1
int newValue = numbersMap.containsKey(number) ? numbersMap.get(number) + 1 : 1;
numbersMap.put(number, newValue);
}
//print results
numbersMap.forEach((k, v) -> {
System.out.println(String.format("The number %d occured %d times.", k, v));
});
}
You can implement this in a very clean way using streams:
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class IntegerCounter {
public static Map<Integer, Long> countOccurences(int[] input) {
return Arrays.stream(input)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
}
Here is a test case that demonstrates it's usage:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
public class IntegerCounterTests {
#Test
public void shouldReturnCorrectCount() {
int[] input = {12,23,44,22,23,22,55};
Map<Integer, Long> expectedResult = Map.of(12, 1L, 23, 2L, 44, 1L, 22, 2L, 55, 1L);
Map<Integer, Long> result = IntegerCounter.countOccurences(input);
result
.entrySet()
.stream()
.forEach(e -> System.out.println(String.format("Number %d occurs %d times.", e.getKey(), e.getValue())));
Assertions.assertEquals(expectedResult, result);
}
}
Next to an assertion to verify that the result is indeed what you want I also added the lines to show the output to standard out:
Number 22 occurs 2 times.
Number 55 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 12 occurs 1 times.
You already handled the hard part. The only thing you should do is, putting writed values to a list, and if list contains the next value, simply, not to write this value again
this is your code :
`
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
}
}
`
and this is the code, i modified a bit
List<Integer> values = new ArrayList<>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
if(!values.contains(userInput[i]){
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
values.add(userInput[i]);
}
}
}
here, the list creation of me, can be wrong. But i think you got the idea.
Good luck

Given 2 numbers, build an array that holds all numbers within them

Refreshing my Java, With 2 numbers as user input , I'm trying to display all numbers in between. My code works using different types, likse strings, String builder and using Java8. But somehow, the Array part does not work..
Here is my code..
System.out.println("Enter the first number :");
Scanner key = new Scanner(System.in);
int num1 = key.nextInt();
int num2 =0;
System.out.println("Enter the Second number :");
try{
num2 = key.nextInt();
do {
if (num2 < num1) {
System.out.println("Second number " + num2 + " is less than " + num1);
System.out.println("Enter the Second number :");
num2 = key.nextInt();
}
} while(num2 <num1);
}
catch (ArithmeticException e) {
if (num2 <num1)
{
System.out.println("Second number " +num2 + "cannot be less than " + num1);
}
}
int length = (num2 - num1) +1;
int [] numOfIntegers = new int [length];
System.out.println("Now the length of numOfInteger is : " + numOfIntegers.length);
// TimeUnit.SECONDS.sleep(2);
//int counter = num1;
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
RESULT is like this :
Numbers within 2 and 8 Using an Array is [0, 0, 2, 3, 4, 5, 6]
What am I doing wrong..
Java 8 allows to do that in one line with IntStream
DOCUMENTATION
public static void main(String[] args) {
int[] a = IntStream.range(num1, num2+1).toArray();
for(int aa:a)
{
System.out.println(aa);
}
}
EXAMPLE: If you Substitute Num1= 2 and Num2=8 , Output Will be 2 3 4 5 6 7 8
When you fill your array, you start at index num1. You should start at index 0. That is
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
should be
for(int i=0; i < length; i++)
{
numOfIntegers[i] = num1 + i;
}
You need to add an variable to loop the array index from 0 th position to array length. Since your for loop first point to an index in the middle. i.e. here it is 2 and it goes forward up to array length. You could change it as below.
for ( int i = num1, k = 0; k < length; i++ )
{
numOfInteger[k++] = i;
}
Here in this loop:
for(int i=num1;i<length; i++)
{
numOfIntegers[i] = i ;
}
You start adding at index num1, which is why the first couple slots in your Array are still your default value. You want to start the index at zero:
for(int i = num1, j = 0; j < length; i++) {
numOfInteger[j++] = i;
}
Which will produce:
[2, 3, 4, 5, 6, 7, 8]
In the final loop:
for(int i = num1 ; i < length; i++)
{
numOfIntegers[i] = i ;
}
You are basically counting from num1 to length i.e the loop counter is being assigned values (2,3,4,5,6) and 0,1 positions of the array are being left out with 0 as default values.
Adjust the loop to iterate from 0 to length like below:
for(int i = 0 ; i < length ; i++)
{
numOfIntegers[i] = num1 + i;
}

Adding corresponding elements of two arrays into third array

I am trying to let the user input the number of elements arrA and arrB should have and also making the user choose the int number they want for each corresponding element in both, arrA and arrB. Then, creating the third arrC with the sum of the corresponding elements in arrA and arrB and then printing arrA, arrB and arrC.
The output should look like this:
Input the length: 5
Enter a value for first array, position 0: 1
Enter a value for first array, position 1: 6
Enter a value for first array, position 2: 13
Enter a value for first array, position 3: -3
Enter a value for first array, position 4: 8
Enter a value for second array, position 0: 9
Enter a value for second array, position 1: -4
Enter a value for second array, position 2: 1
Enter a value for second array, position 3: 65
Enter a value for second array, position 4: 18
first: 1 6 13 -3 8
second: 9 -4 1 65 18
result: 10 2 14 62 26
This is the code I have written so far and I need help as to how would i use scanner to let the user choose the input length of arrA and arrB and the elements in arrA and arrB. This is what the code looks like so far :-
class ArrayArithmetic
{
public static void main ( String[] args )
{
int[] arrA = { 11, -27, 89, 17};
int[] arrB = {-3, 24, -9, -16};
int[] sum = { 0, 0, 0, 0};
for(int i = 0; i < arrA.length - 1; i++)
{
for(int j = 0; i < arrB.length - 1; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
}
}
Lets suppose you have only 2 arrays to make it easy and don't nest loops, when you understand this pieces of code you can wrap all the method with a new loop and create infinite arrays to sum to result if you want... but you have to understand the basics first:
Create a Scanner and ask user for the lenght of the arrays:
Scanner sc = new Scanner(System.in);
// ask user!
System.out.println("Input the length:");
int arrayLength = in.nextInt();
Create the arrays with given lenght
int[] fistArray = new int[arrayLength];
int[] secondArray = new int[arrayLength];
int[] totals = new int[arrayLength];
Fill fist array iterating positions from 0 to number entered by user:
for (int i = 0; i < arrayLength; i ++) {
System.out.println("Enter a value for first array, position "+ i);
try {
firstArray[i] = Integer.parseInt(sc.nextLine());
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
Fill second array iterating positions from 0 to number entered by user and get the sum of each pos:
for (int i = 0; i < in.nextInt(); i ++) {
System.out.println("Enter a value for second array, position "+ i);
try {
secondArray[i] = Integer.parseInt(sc.nextLine());
totals[i] = fistArray[i] + secondArray[i];
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
And print the results:
System.out.println(Arrays.toString(firstArray));
System.out.println(Arrays.toString(secondArray));
System.out.println(Arrays.toString(totalsArray));
Finally, don't forget to close your Scanner to avoid memory leaks as pointed drgPP so:
sc.close();
The following code should do as you wanted:
import java.util.*;
class ArrayArithmetic
{
public static void main ( String[] args )
{
Scanner in = new Scanner(System.in);
System.out.print("Input the length ");
int len = in.nextInt();
int[] arrA = new int[len];
int[] arrB = new int[len];
int[] sum = new int[len];
for (int i = 0; i < len; i++){
System.out.print("Enter a value for first array, position " + i + ": ");
arrA[i] = in.nextInt();
}
for (int i = 0; i < len; i++){
System.out.print("Enter a value for second array, position " + i + ": ");
arrB[i] = in.nextInt();
}
for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
} }
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Length of arrays: ");
try {
//Initializing length of array
int length = sc.nextInt();
//Constructing our arrays based on length
int[] arrA = new int[length];
int[] arrB = new int[length];
int[] arrSum = new int[length];
//Populating our array A via a loop
for (int i=0; i<arrA.length; i++) {
System.out.println("Values for arrA at index: "+i);
int value = sc.nextInt();
arrA[i]=value;
}
//Populating our array B via a loop
for (int i=0; i<arrB.length; i++) {
System.out.println("Values for arrB at index: "+i);
int value = sc.nextInt();
arrB[i]=value;
}
//Call the method to calcualte our sum which will be in sum array
arrSum = makeSum(arrA, arrB, length);
System.out.println(Arrays.toString(arrSum));
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
// Method to calculate our Sum Array based on the length and the Array A and B
public static int[] makeSum (int[] arrA, int[] arrB, int length) {
int[] arrSum = new int[length];
for (int i=0; i<arrA.length; i++) {
for (int j=0; j<arrB.length; j++) {
arrSum[j]=arrA[i]+arrB[j];
}
}
return arrSum;
}
Perhaps this is your question:
Scanner scan = new Scanner(System.in);
System.out.println("Enter size: ");
int size =scan.nextInt();
Integer[] arrA = new Integer[size];
ArrayList<Integer> arrB = new ArrayList<Integer>(size);

How do I get the right output for this array?

I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]

arraylist java counting runs of integers

I am new to java and array lists. I am supposed to sort populate an array full of random integers, then if there is a run (multiples of the same number in a row), put ( ) around that run.
So if the random list is:
2 3 4 5 5 5 5 6 7 7 9
2 3 4 (5 5 5 5) 6 (7 7) 9
This is what I have so far:
import java.util.*;
class Run {
public static void main (String [] args){
Scanner m = new Scanner(System.in);
System.out.print("Enter length wanted: ");
int len = m.nextInt();
System.out.print("Enter max number wanted: ");
int max = m.nextInt();
max = max -1;
int[] x = new int[len];
ArrayList<String> y = new ArrayList<String>();
//Filling x with random numbers
for(int i = 0; i<len; i++){
x[i] = ((int)(Math.random()*max)+1);
}
System.out.println("Orginal Array: " + Arrays.toString(x));
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i++]){ //I just don't know how I am exactly supposed to sort this
}else{
}
}
//Array List with ()
System.out.println("Runs labeled Array: " + y);
}
}
You're going to need a String to display the final output. Also, don't go out of the array.
Try Something like this:
x = Collections.sort(x);
String s = "";
boolean b;
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i+1]){
s+=" ("+i+" ";
b = true;
}else{
if(b == true){
s+=i+") ";
b = false;
}
s+=i + " ";
}
}
use Collections.sort(yourList) to sort your ArrayList.
If you dont wanna use API methods.
try :
for(int i=0;i<list.size(); i++){
for(int j=i+1; j<list.size(); j++){
if(list.get(i)>list.get(j)){
temp = list.get(i);
list.set(i,list.get(j));
list.set(j, temp);
}
}
}

Categories