Summing two arrays by element, issue with carrying the 1 - java

So I've gotten these two arrays to add properly when there is no need to carry anything. so a[0,1,1] + b[0,1,1] will give me c[0,0,2,2], but if I similarly do a[0,9,9] + b[0,9,9] I only get c[0, 0, 8, 8]. The loop in method addBigInts doesn't seem to work the way I thought it would. Any thoughts are appreciated.
import java.util.*;
public class AddBigInts {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//init firstNum array
int[] firstNum = new int[getDigit()];
System.out.println("First number:");
//gets input to pop array
firstNum = getInt(firstNum);
//second array is same length
int[] secondNum = new int[firstNum.length];
System.out.println("Second number:");
//pop second array
secondNum = getInt(secondNum);
System.out.println(Arrays.toString(firstNum));
System.out.println(Arrays.toString(secondNum));
addBigInts(firstNum, secondNum);
}
//creates array that is one place bigger than entered #
public static int getDigit (){
Scanner console = new Scanner(System.in);
System.out.print("How many digits? ");
int arraySize = console.nextInt();
return arraySize + 1;
}
//populates array
public static int[] getInt (int[] num){
Scanner console = new Scanner(System.in);
for (int i=num.length-1; i>0; i--){
System.out.print("Digit " + i + ": ");
num[i] = console.nextInt();
}
return num;
}
//adds both arrays by index into the sum array
public static int[] addBigInts (int[]numArray1, int[] numArray2){
int count = Math.max(numArray1.length, numArray2.length);
int[] sum = new int[count+1];
//starting at numArray1 & 2 index, sums ints
for (int i=count-1; i>=0; i--){
//sum has to be +1 for numArray1 & 2 indexes
sum[i+1] = numArray1[i] + numArray2[i];
if (sum[i+1]>9){
//this line below doesn't seem to execute
sum[i]++;
sum[i+1] = sum[i+1] - 10;
}
else;
}
System.out.println(Arrays.toString(sum));
return sum;
}
}

You have:
sum[i+1] = numArray1[i] + numArray2[i];
You need:
sum[i+1] += numArray1[i] + numArray2[i];
By assigning instead of adding you are overwriting the carried 1 from the previous digit.

In your add bigints function, try change store the addition into a temp variable and use that in the if statement
int temp = numArray1[i] + numArray2[i]
if( temp > 9)

Related

Recursion method in Java providing incorrect output

I am working on a program that will take five numbers from a user then using recursion will provide the user with the sum of those numbers. My program appeared to be working at first however in my testing I am finding that it is just taking the first number entered by the user and basically multiplying it by five rather than taking the different numbers and finding the sum. Where am I going wrong with this? Like I said I am not getting any errors however it is not taking the additional four numbers and calculating the sum of the five numbers. Any help is always appreciated thank you.
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class sumRecusion2 {
static int i;
static int N = 5;
static int[] userNum= new int[N];
public static int sumUser(int newArray[]) {
int n = newArray.length;
if (n == 0)
return 0;
int ans = newArray[0]+sumUser(Arrays.copyOf(newArray, n-1));
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scnr = new Scanner(System.in);
try {
for(i = 0; i<=userNum.length-1; i++) {
System.out.println("Please enter a number: ");
userNum[i]= scnr.nextInt();
}}
catch(InputMismatchException ex) {
System.out.println("Please enter an integer without a decimal point!");
}
System.out.println("The sum of your numbers is: "+ sumUser(userNum));
}
}
Arrays.copyOf(newArray, n - 1) is just trimming of the last element from the array, meaning you are just summing the first element n times.
I would consider using Arrays.copyOfRange(newArray, 1, n) instead, which will make a copy of the array starting from the second element (trimming of the first element)
I, personally, might be tempted to pass in the array AND the index of the element to be summed, which would be more efficient then making n number of copies of the array...
static int i;
static int N = 5;
static int[] userNum = new int[N];
public static int sumUser(int newArray[], int index) {
if (index >= newArray.length) {
return 0;
}
int ans = newArray[index] + sumUser(newArray, index + 1);
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
userNum = new int[] {1, 2, 3, 4, 5};
System.out.println("The sum of your numbers is: " + sumUser(userNum, 0));
}
But, your requirements might differ

How to store the result of each iteration of a for loop into an array in java

Score Finder (100 Marks)
Praveen is finding a job as a Computer Science teacher in school.
He has been rejected many times by different schools but this time he is determined to get the job.
He goes to the principal of the school St. Mary.
The principal says that in his school there is Grading and Credit system.
There are N subjects and each subject has a credit Ci attached to it (1 <= i <= N).
Each student gets a particular grade in each subject and each grade has a point value which are:
A = 10,
A(minus) = 9,
B = 8,
B(minus) = 7,
C = 6,
C(minus) = 5
Now if there are 3 subjects of credits 4, 3 and 2 respectively and a particular student scores A(minus),
B and C in these 3 subjects respectively then his score would be calculated as follows:
Total Score=Summation of product of Grade point and corresponding credit for each subject.
= ( (9*4) + (3*8) + (2*6) ) = 72.
He wants Praveen to tell total distinct Scores that are possible
to be given to a student given credits of N subjects by assigning different grades to each subject.
Input Format
Your function contains a single argument- a one-dimensional Integer Array A of N elements where each represents Credit of that subject.
The first line of input contains an Integer N denoting the size of the array.
Next N lines of input each containing an Integer denoting the credit Ci of ith subject
Constraints
1 <= N <= 100
1 <= Ci <= 5
Output Format
You must return a single integer denoting the total number of scores that are possible to be given.
Sample TestCase 1
Input
2
1
2
Output
16
now I am writing code like this
package javaapplication1;
import java.util.Scanner;
public class CandidateCode {
private static void possibleCombination(int input) {
int i=0;
int[] a=new int[Grades.length];
a[i]=input;
System.out.println("the a is "+a[i]);
}
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
public static void main(String[] args) {
int i=0,j,totalSummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int index = uInput.nextInt();
int[] Credit = new int[index];
for (i = 0; i <= Credit.length-1; i++) {
Credit[i] = uInput.nextInt();
System.out.println("credit is" + Credit[i]);
for ( j = 0; j <= Grades.length - 1; j++) {
totalSummation = +(Grades[j] * Credit[i]);
possibleCombination(totalSummation);
// System.out.println("total sum is " + totalSummation);
}
}
}
}
Now I want to store the values calculated in each iteration...
Meaning for
iteration first the values are 10,9,8,7,6,5,4,3,2,1
itertion second the values are 20,18,16,14,10,8,6,4,2
i want to sum each value of 1st iteration with all the values of 2nd iteration.
i,e 10+20, 10+18, 10+16, 10+14, 10+10, 10+8, 10+6, 10+4, 10+2
similarly for 9,8,7,6,5,4,3,2,1
To achieve this I need to store the values per iteration but I am stuck here, please guys help me to get rid of this problem thank you in advance.
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Sample {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
int nValue = scan.nextInt();
if(nValue<1 || nValue>100){
System.out.println("Array Value cannot be less than 1 or greater than 100");
}
int[] inputCredits = new int[nValue];
for( int i=0 ; i < nValue ; i++){
inputCredits[i]=scan.nextInt();
if(inputCredits[i]<1 || inputCredits[i]>5){
System.out.println("Credit Value cannot be less than 1 or greater than 5");
}
}
List<Integer> list1 = Arrays.stream(inputCredits).boxed().collect(Collectors.toList());
List<Integer> list2 = Arrays.asList(5,6,7,8,9,10);
//checked for basic constraints up till this point
//Next what we multiply all the inputted Credits with the possible grades and
// store in the list where x input Credits will produce a list of x*6 entries
// where first six entries are the possibilities for the first Credit, next 6
// entries for the 2nd credit and so on, having this knowledge we loop through // the list to get all the possible scores
List<Integer> permutedList = list1.stream().flatMap(i -> list2.stream().map(j -> i*j)).collect(Collectors.toList());
List<Integer> listForDistinctSet= new ArrayList<Integer>();
for(int i=0; i<6 ; i++){
listForDistinctSet.add(permutedList.get(i));
}
Set<Integer> distinctSet = new HashSet<Integer>();
for(int j=6,k=j+6;k<=permutedList.size();j=k,k=k+6){
Set<Integer> newSet = new HashSet<Integer>();
for(int i=0; i<listForDistinctSet.size(); i++){
for(; j<k ; j++){
int sum = listForDistinctSet.get(i) + permutedList.get(j);
newSet.add(sum);
}
j=k-6;
}
distinctSet=newSet;
listForDistinctSet = new ArrayList<>(distinctSet);
}
System.out.println(distinctSet.size());
}
}
If you don't want to store in a multi-dimensional array then you need to store each iteration in single dimensional array as below. But this code will work only for two credits.
public class CandidateCode {
private static int possibleCombination(int input)
{ int i=0;
int[] a=new int[Grades.length];
a[i]=input;
return a[i];
}
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4,
3, 2, 1};
public static void main(String[] args) {
int i=0,j,totalSummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int index = uInput.nextInt();
int[] Credit = new int[index];
int[] creditarr = new int[10];
int[] credit1 = new int[10];
int[] credit2 = new int[10];
for (i = 0; i <= Credit.length-1; i++) {
Credit[i] = uInput.nextInt();
System.out.println("credit is" + Credit[i]);
for ( j = 0; j <= Grades.length - 1; j++) {
totalSummation = +(Grades[j] * Credit[i]);
creditarr[j]=possibleCombination(totalSummation);
if(Credit[i]==1) {
credit1[j]=creditarr[j];
}
if(Credit[i]==2){
credit2[j]=creditarr[j];
}
}
}
for(int k=0;k<credit1.length;k++) {
for(int l=0;l<credit2.length;l++) {
int final_no=credit1[k]+credit2[l];
System.out.println("final_no :" +final_no);
}
}
}
}
Is this what you want?
I guess the below code would be the best solution.This code will work for the no of credits you mention.
public class Candidate {
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5};
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0,score=0,totalsummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int arraylength = uInput.nextInt();
int[] credits= new int[arraylength];
ArrayList<Integer> combination = new ArrayList<Integer>();
for (i = 0; i <credits.length; i++) {
credits[i] = uInput.nextInt();
}
switch(credits.length) {
case 1:
for(int c1=10;c1>=5;c1--) {
totalsummation = c1*credits[0];
combination.add(totalsummation);
}
break;
case 2:
for(int g:Grades) {
for(int c2=10;c2>=5;c2--) {
totalsummation=g*credits[0]+c2*credits[1];
combination.add(totalsummation);
}
}
break;
case 3:
for(int g:Grades) {
for(int c3=10;c3>=5;c3--) {
totalsummation=g*credits[0]+c3*credits[1]+c3*credits[2];
combination.add(totalsummation);
}
}
break;
case 4:
for(int g:Grades) {
for(int c4=10;c4>=5;c4--) {
totalsummation=g*credits[0]+c4*credits[1]+c4*credits[2]+c4*credits[3];
combination.add(totalsummation);
}
}
break;
case 5:
for(int g:Grades) {
for(int c5=10;c5>=5;c5--) {
totalsummation=g*credits[0]+c5*credits[1]+c5*credits[2]+c5*credits[3]+c5*credits[4];
combination.add(totalsummation);
}
}
break;
default:
System.out.println("Invalid Input");
}
ArrayList<Integer> distinctnos =(ArrayList<Integer>) combination.stream().distinct().collect(Collectors.toList());
System.out.println(distinctnos.size()); }
}
Hope this answers your question.
Ok, following our discussion in comments: you don't need two for loops.
for i = 0; i < array.size(); i++ {
sum += grade[i]*credit[i]
}
Sorry for the generic coding style. Is it what you want?

Find Lowest, Highest, Median and Average Score using findKth

For this program, my goal is to...
Find the Highest, Lowest, Median and Average Score by using findKth
The user must input the numbers (Enter -1 to stop scanner) and they do not know how many there are and if they are sorted
However, I am seeing some issue with trying to do this.
The findKth method I am provided only takes in an int[]arr, and I cannot find a way to initialize an array to the specific size need for this project.
Could someone suggest a way to to do this?
Below are my test methods and my findKth
import java.util.*;
public class Statistics
{
public static void main(String[]args)
{
System.out.print("Enter Scores, -1 to end: ");
Scanner keyboard= new Scanner(System.in);
String numbers = null;
while(keyboard.nextInt()!=-1)
{
numbers= keyboard.next();
}
String[] parts = numbers.split(" ");
int[] n1 = new int[parts.length];
for(int n = 0; n < parts.length; n++)
{
n1[n] = Integer.parseInt(parts[n]);
}
int highest= n1.length-1;
int lowest=0;
int median= n1.length/2;
QuickSort.findKth(n1, highest);
System.out.println("High: "+n1[highest]);
QuickSort.findKth(n1, lowest);
System.out.println("Low: "+n1[lowest]);
QuickSort.findKth(n1, median);
System.out.println("Median: "+n1[median]);
}
}
public static void findKth(int[] arr, int k)
{
findKth(arr, 0, arr.length, k);
}
//Pre: arr[first]..arr[last-1] contain integers
// k must be in [first..last-1]
//Post: The elements in arr has been rearranged in such a way that arr[k] now contains the kth
// largest element
public static void findKth(int[] arr, int first, int last, int k)
{
int pivotLoc = rearrange(arr, first, last);
if (pivotLoc==k) return;
else if (pivotLoc>k) findKth(arr, first, pivotLoc, k);
else findKth (arr, pivotLoc +1, last, k);
}
I've tried different methods such as trying to parse the string for the numbers however I cannot do this as i cannot find a way to properly stop the scanner when the user inputs -1.
Also i have tried using ArrayList, but findKth with ONLY take an int[]arr. So this will not work.
Suggestions? I am stumped.
Use a List to collect the input:
List<Integer> input = new ArrayList<>();
input.add(n); // add each number
Then to convert to an array after all input:
int[] array = input.stream().mapToInt(Integer::intValue).toArray();
Your input loop is buggy. Although out of scope of the question, try a simpler loop, for example:
while (true) {
int n = keyboard.nextInt();
if (n == -1)
break;
input.add(n);
}

How to add 2 For-Each Loops to the below code?

I need to write a program that takes 10 floating-point numbers as inputs.
The program should display the average of the numbers followed by all of the numbers that are greater than the average.
Part of my requirements include writing a method that takes an array of doubles as a parameter and returns the average of the data in the array, and I am required to use at least 2 for-each loops in this program, and am not sure where to place them. The program works perfectly now, it just needs to have two for each loops added.
Here is what I have so far.
public class Floats {
public Floats() {
}
public static void main(String[] args) {
int count = 0, ct = 0, inc = 0, avc = 0, ac = 0, incre = 0, greaterCount = 0;
double sum = 0, average = 0, number = 0;
Scanner reader = new Scanner(System.in);
double[] array = new double[10];
double[] averageArray = new double[1];
double[] greaterArray = new double[10];
//inputs and appends to an array
while (count < array.length) {
System.out.print("Enter a number: ");
number = reader.nextInt();
array[count] = number;
sum = sum + number;
count++;
}
average = sum / count;
//counts
while (inc < array.length) {
if (array[inc] > average) {
greaterArray[inc] = array[inc];
incre++;
}
inc++;
}
//prints all numbers
System.out.println("All of the numbers entered: ");
while (avc < array.length) {
System.out.print(array[avc] + "," + " ");
avc++;
}
//average displayed
averageArray[0] = average;
System.out.println("");
System.out.println("The average of all numbers entered: ");
System.out.println(averageArray[0]);
//larger than average
System.out.println("Numbers greater than the average: ");
while (ac < inc) {
if (greaterArray[ac] != 0) {
System.out.println(greaterArray[ac]);
}
ac++;
}
}
}
Thanks for the help in advance! Let me know if you have any questions!!
I don't want to do your homework for you, but I will try to give a helpful recommendation. The Arrays.asList(array) method returns a list that can easily be used as the source of a for-each loop.
Since it was pointed out that a for-each loop can be used on an array and a collection that implements Iterable, my answer above isn't necessary. With that in mind, I'll provide some example code:
String[] array = new String[] {"Test", "String", "Array"};
for (String string : array) {
}
Print all the numbers in double[] array.
for (double d : array) {
System.out.print(d + ", ");
}
Print all the numbers in array greater than average
for (double d : array) {
if (d > average) {
System.out.println(d);
}
}

A set of random values in an int array of a user specified size

Write a method to generate and return a set of random values in an int array of a user specified size. The values should all be between +/- N, where N is a constant such as 100.
Thank you.
Here's Mine;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
int limit, numbers;
Random random = new Random();
Scanner scan = new Scanner(System.in);
System.out.print ("Enter your limit value for your array: "); //Needs to be positive.
limit = scan.nextInt();
int[] list = new int[limit];
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + ", ");
}
numbers = random.nextInt(limit - (0 - limit)) + (0 - limit);
System.out.println (numbers);
System.out.println (list[numbers]);
}
}
public List<Integer> random(int range, int count){
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<count;i++){
if(Math.random() > 0.5){
//adding positive value with probability of 0.5
result.add((int)(Math.random() * (double)range));
}else{
//adding negative value with probability of 0.5
result.add(-1 * (int)(Math.random() * (double)range));
}
}
return result;
}
If you want to create your own random number generator, the easiest one to implement will be Linear Congruential Generator. Read from wiki and try yourself. Ask here if you need help.

Categories