Not able to proceed with Series sum - java

I wanted to find the missing number in series so i thought a simple idea why not add all the numbers in array which are in series and hold it in one variable and then calculate the sum of series by formula Sn=n/2(a+l) but while calculating the series sum i am getting some error.
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0; int total=0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length-1];
total = [n/2*(a+l)];
System.out.print("The missing number is "+(sum-total));
}}
total = [n/2*(a+l)]; ............................(1)
This is where i am getting error.
enter image description here

You can use the below logic which is much simpler to use and understand
for(int i=0;i<ar.length-1;i++)
{
if(ar[i]!=ar[i+1]-1)
{
System.out.print("The missing number is "+(ar[i]+1)+"\n");
break;
}
}

The first thing is in total = [n/2*(a+l)]; [] is not valid syntax in this context. The second thing I noticed, is that your formula to calculate the sum seems odd, maybe you meant Sn = (n * (a + l)) / 2?. After making those two changes the code should look as follows:
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length - 1];
int total = (n * (a + l)) / 2;
System.out.print("The missing number is "+(sum - total));
// outputs 0 which is correct nothing is missing
// Now if you remove say 12 from the array
// by changing the array to int ar [] = {1,2,3,4,5,6,7,8,9,10,11,0,13};
// you should get back -12 which means 12 is missing
}
}

If you don't want to use my above logic. You have to make changes to your code:
Edit this:
int n = ar.length+1;
n has been assigned ar.length + 1 because that +1 is needed to compensate for the missing element in the array list
Also, the formula has not been correctly written into the code:
total = (n* (a + l))/2;
If you first divide n by 2 then, it will truncate the places after decimal point because n is an integer not a floating number. So, your logic would fail when n is not even.
And lastly, the missing number would be (sum-total) not the other way around because 'total' contains the missing number and 'sum' does not.
System.out.print("The missing number is "+(total-sum));

Related

How to multiply two long values in java

I am trying to multiply two largest numbers from an array of numbers. Its working fine for small numbers.
Correct input / output - this is working:
3 10 2 8
80
Correct input / output - this is failing:
2 100000 90000
9000000000
My output is however 10000000000 instead.
Can someone tell me what is wrong in my code?
public static Long sumPairwise(Long[] numbers){
int index=0;
int n = numbers.length;
for(int i=1;i<n;i++){
if(numbers[i]>numbers[index])
index=i;
}
numbers[n-1]= numbers[index];
index=0;
for(int j=1;j<n-1;j++){
if(numbers[j]>numbers[index])
index=j;
}
numbers[n-2]=numbers[index];
Long product = (numbers[n-2])*(numbers[n-1]);
return product ;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i=0;i<n;i++)
numbers[i]= sc.nextLong();
System.out.println(sumPairwise(numbers));
}
There is a bug in your code: numbers[n-1] may well contain the second highest number. You are overwriting that number with the highest number in your code, before you try and put it at the first to last position.
One way to overcome this is to sort the array using Arrays.sort, this way you are sure that the last two numbers are the highest and second highest number.
public static long multiplyLargestTwoNumbers(long[] numbers) {
long[] sortedNumbers = numbers.clone();
Arrays.sort(sortedNumbers);
int size = numbers.length;
// multiply highest and second highest number
return sortedNumbers[size - 1] * sortedNumbers[size - 2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long numbers[] = new long[n];
for (int i = 0; i < n; i++) {
numbers[i] = sc.nextLong();
}
System.out.println(multiplyLargestTwoNumbers(numbers));
}
Other changes:
using long instead of Long: try and use primitive types when the objective reference types are not needed (you need Long if you want to use e.g. a List because a List can only hold object references);
spaced out for loops, please use white space;
renamed method, as it does't add anything pairwise;
used curly braces for for loop in main method;
removed spurious parentheses in part that performs multiplication.
You might also introduce an if statement that first checks if the numbers array does indeed contain at least two elements. This is called a guard statement.
Finally remember that byte, short and long all contain signed numbers of a specific bit size. Basically you are performing calculations modulus 2^n where n is the bit size. If the value is too large it may overflow and return an incorrect result. For that you need BigInteger.
You are replacing the original number in that index with another number.
That is causing the issue.
Please just simply find the max 2 numbers from below logic and multiply.
Also, remember to close scanner.
Here the simple solution. This will work only for positive integers.
import java.util.Scanner;
public class Snippet {
public static long multiplyHighestTwoValues(Long[] numbers) {
long maxOne = 0;
long maxTwo = 0;
for (long n : numbers) {
if (maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if (maxTwo < n) {
maxTwo = n;
}
}
long product = maxOne * maxTwo;
return product;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i = 0; i < n; i++)
numbers[i] = sc.nextLong();
System.out.println(sumPairwise(numbers));
sc.close();
}
}
Instead of Long try to use BigInteger to multiply larger values that fit into long, otherwise your result may overflow.
Use BigDecimal instead for multiplying floating point numbers.

Finding a missing number in an array that uses a random generator

I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5

find all possible sums of a list without target

im trying to find all possible sums from a list.
The list consist of ints that are user inputed, and the number of inputs are decided by the user aswell( see code).
What i want is to check all possible sums without having a target.
The reason i dont want a target is because the program is then later suposed to chose one of these sums which is closest to 1000.
So if i was to pick 1000 as target i wouldnt be able to get say 1001.
Example input from user:
5 // user chose 5 numbers.
500,400,300,50,60 // numbers chosen by user.
Output would then be:
1010 // because 500+400+60+50= 1010 and closest to 1000.
Next example could be:
3 // user chose 3 numbers.
1,2,3 // numbers chosen by user.
Output would then be:
6 // because 1+2+3 = 6.
So back to my original question, how do is this done? Everytime i search "all possible sums of a list of ints" or simular i get with a target and it dosent work in this example.
public static void main(String[] args) throws Exception {
int bästaVikt;
int räknare = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> mylist = new ArrayList<Integer>();
int s;
s = sc.nextInt();
int ans = 0;
for(int i = 1; i <= s; i++) {
mylist.add(sc.nextInt());
}
for(int i = 0; i < mylist.size(); i++) {
Collections.sort(mylist);
System.out.print(mylist.get(i));
System.out.print(" ");
}
}
Half actual code half pseudo code, hope it helps.
input // the array that holds all numbers than the user input
int n = input.length();
ArrayList<Integer> combinations = new ArrayList<Integer>();
int totalSum = input.sum(); // sum of all the values the user input
ArrayList<Integer> allSums = new ArrayList<Ingeter>();
for(int i = 0; i < n; i++){
combinations = combine(i) // find all possible combinations of i integers in the input array; you can surely find code for retrieving combinations in another thread
foreach combination in combinations{
allSums.add(totalSum - combination.sum())
}
combinations = new ArrayList<Integer>(); // clear the combinations arraylist
}
return allSums; //all possible sums
minDistanceToNumber = absolute(allSums.get(0) - 1000); // define a function "int absolute(int value)" which will multiply value by -1 if it is less than 0 and return it or just return it if it is bigger than 0
minNumber = allSums.get(0); // this will hold the number which has the minimum distance to 1000, as in the example above
for each sum in allSums
if(absolute(sum - 1000) < minDistanceToNumber){
minDistanceToNumber = absolute(sum - 1000);
minNumber = sum;
}
}
return minNumber;

Numbers I can get by adding an array in java

I need to get a minimum number that I cant get by adding different numbers of an array. Basically if I have these numbers:1,1,1,5; I can get 1,2,3,5,6... but I cant get 4 so that is the number I am looking for. Now this is my code:
import java.util.Scanner;
public class Broj_6 {
public static void main(String[] args) {
Scanner unos = new Scanner(System.in);
int k;
int n = unos.nextInt();
int niz []= new int [n];
for(int i = 0;i<n;i++){
niz[i]=unos.nextInt();
}
BubbleSort(niz);
for(int i = 0;i<n;i++){
System.out.print(niz[i] + " ");
}
for(int br = 1;br<=10000;br++){
for(k = 1;k<n;k++){
if(niz[k]>br){
break;
}
}
int podniz [] = new int [k];
for(int i=0;i<podniz.length;i++){
niz[i] = podniz[i];
}
//This is where I will need my logic to go
}
}
static void BubbleSort (int [] niz){
int pom;
for(int i = 0;i<niz.length-1;i++){
for(int j = 0;j<niz.length-1-i;j++){
if(niz[j]>niz[j+1]){
pom = niz[j];
niz[j] = niz[j+1];
niz[j+1] = pom;
}
}
}
}
}
So the code goes by testing each number individually from 1 to 100000 and makes a subarray of all numbers given that are less than the number itself. Now here is the problem,I dont know how to mix and match the numbers in the subarray so it can get(or not get) the desired number. When every combination is tested and there is no desired number,I will break; the loop and print i. Just to clarify,I can only use addition,and each number can only go in once
You can achieve this as below:
Use two nested loops, like below to calculate the sum of different numbers:
List<Integer> additionList = new ArrayList<Integer>();
int []inputNumbers = .... // Logic to read inputs
for(int _firstIndex = 0; _firstIndex < totalInputs; _firstIndex++){
for(int _secondIndex = _firstIndex + 1; _secondIndex < totalInputs; _secondIndex++){
additionList.add(inputNumbers[_firstIndex]); // only because you have 1 in the sample output
additionList.add(inputNumbers[_firstIndex] + inputNumbers[_secondIndex ]);
}
}
Then sort additionList and look for any missing entry. The first missing entry will be your answer,
Sorting the whole array and then finding sum of all subarrays does solve the problem, but is costly: O(2n^2) ~ O(n^2).
More efficient way to solve this will be Kadane's Algorithm: http://en.wikipedia.org/wiki/Maximum_subarray_problem
What the algo does:
Start from first element and increase the array size (sub array) till you reach the sum you're desiring.
my_num = 1;
while(true){
if(sum_subarray) > my_num){
current position = new subarray;
}
and this subarray concept is calculated through Kadane's approach:
def sum_subarray(A):
sum_ending_here = sum_so_far = 0
for x in A:
sum_ending_here = max(0, max_ending_here + x)
sum_so_far = max(sum_so_far, sum_ending_here)
return sum_so_far
I couldn't solve the problem completely. 'my_num' mentioned here needs to be incremented from 1, and break when my_num > max_sum. I hope someone can add to it and make it compilable.
Note:
This will also take care if negative elements are present in array.

Calculate average in java

EDIT: I've written code for the average but I don't know how to make it so that it also uses ints from my args.length rather than the array.
I need to write a java program that can calculate:
the number of integers read in
the average value – which need not be an integer!
NOTE: I don't want to calculate the average from the array but the integers in the args.
Currently I have written this:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
result += nums[i];
}
System.out.println(result/count)
Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?
Thanks in advance.
Just some minor modification to your code will do (with some var renaming for clarity) :
double sum = 0; //average will have decimal point
for(int i=0; i < args.length; i++){
//parse string to double, note that this might fail if you encounter a non-numeric string
//Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
sum += Double.valueOf( args[i] );
}
double average = sum/args.length;
System.out.println(average );
Note that the loop can also be simplified:
for(String arg : args){
sum += Double.valueOf( arg );
}
Edit: the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.
Update:
As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:
BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
sum = sum.add( new BigDecimal( arg ) );
}
This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):
Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.
int values[] = { 23, 1, 5, 78, 22, 4};
int sum = 0;
for (int i = 0; i < values.length; i++)
sum += values[i];
double average = ((double) sum) / values.length;
This
for (int i = 0; i<args.length -1; ++i)
count++;
basically computes args.length again, just incorrectly (loop condition should be i<args.length). Why not just use args.length (or nums.length) directly instead?
Otherwise your code seems OK. Although it looks as though you wanted to read the input from the command line, but don't know how to convert that into an array of numbers - is this your real problem?
It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.
In your case, you want to convert args which is String[] into double
or int. You can do this using Arrays.stream(<arr>). Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s)) which will convert stream of Strings into stream of doubles.
Then you can use Stream.collect(supplier, accumulator, combiner) to calculate average if you want to control incremental calculation yourselves. Here is some good example.
If you don't want to incrementally do average, you can directly use Java's Collectors.averagingDouble() which directly calculates and returns average. some examples here.
System.out.println(result/count)
you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:
double avg = (double)result / (double)args.length
for 1. the number of integers read in, you can just use length property of array like :
int count = args.length
which gives you no of elements in an array.
And 2. to calculate average value :
you are doing in correct way.
Instead of:
int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
you can just
int count = args.length;
The average is the sum of your args divided by the number of your args.
int res = 0;
int count = args.lenght;
for (int a : args)
{
res += a;
}
res /= count;
you can make this code shorter too, i'll let you try and ask if you need help!
This is my first answerso tell me if something wrong!
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all
I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.
public double average(ArrayList<Double> x) {
double sum = 0;
for (double aX : x) sum += aX;
return (sum / x.size());
}
If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html
You'll fall into true luv!
public class MainTwo{
public static void main(String[] arguments) {
double[] Average = new double[5];
Average[0] = 4;
Average[1] = 5;
Average[2] = 2;
Average[3] = 4;
Average[4] = 5;
double sum = 0;
if (Average.length > 0) {
for (int x = 0; x < Average.length; x++) {
sum+=Average[x];
System.out.println(Average[x]);
}
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/Average.length);
}
}
}
// question: let, Take 10 integers from keyboard using loop and print their average value on the screen.
// here they ask user to input 10 integars using loop and average those numbers.so the correct answer in my perspective with java is below:-
import java.util.Scanner;
public class averageValueLoop {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int sum = 0;
for (int i = 0; i < 10; i++){
System.out.print("Enter a number: ");
sum = sum + sc.nextInt();
}
double average = sum / 10;
System.out.println("Average is " + average);
}
}
}

Categories