String Number Addition Java - java

This is my second week learning Java and I'm trying to implement some functions that I saw in the book I'm studying with.
With the first function I wanted to represent an integer as an array of integer digits so that I can bypass the range of integer values.
For example:
1st Function
Input : integerInput(123456)
Output : integerString[] = {1,2,3,4,5,6}
2nd function
Input : stringInput[] = {123456}
Output : integerString[] = {1,2,3,4,5,6}
3rd function:
(I want to add the 2 integer string values as in like normal addition)
Input : integerString1[] = {1,2,3,4,5,6} integerString2[] = {1,2,3,4,5,6}
Output : [2,4,6,9,1,2]
This is what I have so far, it is full of mistakes and all i could get is an empty output. Would appreciate any help.
Thanks.
public class tryingOut{
public static int[] integerToNumberArray(int value) {
String temp = Integer.toString(value);
int[] list = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
list[i] = temp.charAt(i) - '0';
}
return list;
}
public static boolean isNumeric(String value) {
if (value == null) {
return false;
}
try {
int d = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static int[] stringToNumberArray(String value) {
boolean checkNumeric = isNumeric(value);
if (checkNumeric = false) {
return null;
} else {
String[] items = value.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
}
}
return results;
}
}
public static int[] addNumberArrays(int[] a1, int[] a2) {
int[] result = null;
return result;
}
public static void main(String[] args) {
int test1 = 19;
int test2 = 823;
int[] list1 = integerToNumberArray(test1);
int[] list2 = integerToNumberArray(test2);
// stringToNumberArray(test1);
// stringToNumberArray(test2);
}
}

Welcome to the world of Programming with JAVA. Firstly, I appreciate your enthusiasm for programming and the efforts you made.
As mentioned in the comments by Basil Bourque you can achieve this by BigInteger. However, I like your interest for trying this yourself and therefore I will try to share a code below with as much description I can provide to make it understable to you.
To point out few mistakes in your original code:
You do not need to handle null separtely with if-condition for your method isNumeric(String value) becaause the try-catch block will automatically handle it for you.
For stringToNumberArray(String value) method you do not need to use the String.split and also it was quite unclear what you did there in line String[] items = ...
Full code:
public class PlayingWithInt {
public static boolean isNumeric(String value) {
try {
Integer.parseInt(value);
} catch (NumberFormatException nfe) {
// This handles both null and other non int values so we don't need an extra condition to check for null
return false;
}
return true;
}
// Assuming argument value is "123456"
public static int[] stringToNumberArray(String value) {
if (isNumeric(value)) { // We generally don't write `== true` or `== false` with boolean values
char[] valueAsCharArray = value.toCharArray(); // valueAsCharArray = {'1', '2', '3', '4', '5', '6'}
int[] valueAsIntArray = new int[valueAsCharArray.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
for (int i = 0; i < valueAsCharArray.length; i++) {
valueAsIntArray[i] = valueAsCharArray[i] - '0';
}
return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
}
return null; // Null will be returned if the value is not numeric
}
// Assuming argument value is {"1", "2", "3", "4", "5", "6"}
public static int[] stringToNumberArray(String[] value) {
int[] valueAsIntArray = new int[value.length]; // valueAsIntArray = {0, 0, 0, 0, 0, 0}
for (int i = 0; i < value.length; i++) {
valueAsIntArray[i] = value[i].charAt(0) - '0';
}
return valueAsIntArray; // valueAsCharArray = {1, 2, 3, 4, 5, 6}
}
// Let's say value is 123456
public static int[] integerToNumberArray(int value) {
String valueAsString = Integer.toString(value); // valueAsString = "123456"
return stringToNumberArray(valueAsString); // We are using our already built method that does the same thing.
}
public static int[] addNumberArrays(int[] a1, int[] a2) {
int maxLength;
if (a1.length > a2.length) maxLength = a1.length;
else maxLength = a2.length;
int[] result = new int[maxLength + 1];
int i = a1.length - 1; // Index iterator for a1
int j = a2.length - 1; // Index iterator for a2
int k = result.length - 1; // Index iterator for result
int carry = 0; // carry to handle case when the sum of two digits more than deci/ ten (10)
while (i >= 0 && j >= 0) {
int sum = a1[i] + a2[j] + carry;
result[k] = sum % 10;
carry = sum / 10;
i--;
j--;
k--;
}
// If a1 has more digits than a2
while (i >= 0) {
int sum = a1[i] + carry;
result[k] = sum % 10;
carry = sum / 10;
i--;
k--;
}
// If a2 has more digits than a1
while (j >= 0) {
int sum = a2[j] + carry;
result[k] = sum % 10;
carry = sum / 10;
j--;
k--;
}
result[0] = carry;
return result;
}
public static void main(String[] args) {
int test1 = 123456;
int test2 = 123456;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
}
Output:
0246912
Additional Input and Output:
Example 1
Code:
public static void main(String[] args) {
int test1 = 19;
int test2 = 823;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
0842
Example 2
Code:
public static void main(String[] args) {
int test1 = 823;
int test2 = 19;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
0842
Example 3
Code:
public static void main(String[] args) {
int test1 = 999;
int test2 = 999;
int[] num1 = integerToNumberArray(test1);
int[] num2 = integerToNumberArray(test2);
int[] result = addNumberArrays(num1, num2);
for (int i : result) System.out.print(i); // This is known as enhanced-for-loop or for-each-loop
System.out.println();
}
Output:
1998
References:
String.toCharArray()
Enhanced for-loop |OR| For-Each Loop
Integer.parseInt(String value)

Related

The method should print the array elements between the indexes a and b including a and not including b in line 1

I don't know how to finish this code. Help someone.
package com.telukhin.hw4;
import java.util.Arrays;
public class Task10 {
public static void main(String[] args) {
int[] arr = new int[10];
list(arr, 2, 5);
}
private static void list(int[] arr, int a, int b) {
if (a >= 0 && b <= arr.length) {
for (int i = a; i < arr[b - 1]; i++) {
System.out.println(Arrays.toString(arr));
}
} else {
System.out.println("unknown");
}
}
} //
First of all, your array is empty. Take a look at the code below. In the for loop I'm checking that the index is between param a and b (including a, excluding b), and simply printing out the current index.
public static void main(String[] args) {
int[] arr = new int[10];
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
arr[5] = 5;
list(arr, 2, 5);
}
private static void list(int[] arr, int a, int b) {
if (a >= 0 && b <= arr.length) {
for (int i = a; i < b; i++) {
System.out.println(arr[i]);
}
} else {
System.out.println("unknown");
}
}
In your example you try to combine to approaches
Custom implementation
Iterate the interval and print each element
for (int i = a; i < b; i++) {
System.out.print(arr[i] + " ");
}
Existing implementation
int[] subArr = Arrays.copyOfRange(arr, a, b);
System.out.print(Arrays.toString(subArr));
You should use only one

java assign even elements to even index and odd to odd places and if the numbers are not equal add zeros to the places

I am trying to write code to display the even elements to even indexes and odd to odd indexes and if the numbers added numbers are same then add zeros accordingly.
Example:
x = [1,2,3,4]
output: 2 1 4 3
x = [1 1 1 4]
output: 4 1 0 1 0 1
I reached to get even and odd positions but stuck after that.
Below is my code.
import java.util.*;
class ArrayDemo3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Size of Array :: ");
int size = s.nextInt();
int[] x = new int[size];
System.out.println("Array Created having the size :: " + size);
System.out.println("Enter Elements for Array :: ");
for (int i = 0; i < size; i++) {
System.out.println("Enter element no-" + (i + 1) + " ::");
x[i] = s.nextInt();
}
System.out.println("Contents of Array ::");
for (int i = 0; i < size; i++) {
System.out.print(x[i] + " ");
}
for (int i = 0; i < size; i = i + 1) {
int even = 0;
int odd = 1;
if (i < size && x[i] % 2 == 0) {
System.out.print("even : ");
even = even + i;
System.out.print("position" + i + " " + x[i] + " ");
} else {
System.out.print("odd : ");
odd = odd + i;
System.out.print(i + " " + x[i] + " ");
}
if (even < size && odd < size) {
int temp = x[even];
x[even] = x[odd];
x[odd] = temp;
} else {
}
//System.out.print(x[i] + " ");
}
}
}
You can break up your problem in 3 parts:
First create two lists, one containing in encountered order the even numbers and the other the odd numbers:
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
Pad the shorter of the two lists with zeros (0s) to make it equal length as the other one:
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
Finally join intertwining both lists:
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
The following is the full working example:
public class ArrayRearrangement {
public static void main(String[] args) {
// int[] result = rearrange(1, 2, 3, 4);
int[] result = rearrange(1, 1, 1, 4);
System.out.println(Arrays.stream(result).boxed().collect(Collectors.toList()));
}
private static int[] rearrange(int... numbers) {
List<List<Integer>> numsByOddity = createOddityLists(numbers);
padShorterList(numsByOddity);
return joinLists(numsByOddity).stream().mapToInt(i->i).toArray();
}
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
}
Complete code on GitHub
Hope this helps.
Using arrays something like this we can do. Code needs to be optimised.
public static int[] arrangeInEvenOddOrder(int[] arr)
{
// Create odd and even arrays
int[] oddArr = new int[arr.length];
int[] evenArr = new int[arr.length];
int oCount = 0, eCount = 0;
// populate arrays even and odd
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenArr[eCount++] = arr[i];
else
oddArr[oCount++] = arr[i];
}
int[] resArr = new int[oCount >= eCount?
2*oCount : 2*eCount-1];
// populate elements upto min of the
// two arrays
for (int i =0; i < (oCount <= eCount?
2*oCount : 2*eCount ); i++ )
{
if( i%2 == 0)
resArr[i] = evenArr[i/2];
else
resArr[i] = oddArr[i/2];
}
// populate rest of elements of max array
// and add zeroes
if (eCount > oCount)
{
for (int i=2*oCount,j=0;i<2*eCount-1; i++)
{
if (i%2 == 0)
{
resArr[i] = evenArr[oCount+j];
j++;
}
else
resArr[i] = 0;
}
}
else if (eCount < oCount)
{
for (int i=2*eCount,j=0;i<2*oCount; i++)
{
if ( i%2 != 0)
{
resArr[i] = oddArr[eCount+j];
j++;
}
else
resArr[i] = 0;
}
}
return resArr;
}
Sort element based on index i.e if the element is even, it must be at even position and vise-versa
int sortArrayByEvenOddIndex(int arr[]) {
int n = arr.length;
int res[] = new int[n];
int odd = 1;
int even = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
res[even] = arr[i];
even += 2;
} else {
res[odd] = arr[i];
odd += 2;
}
}
return res;
}

How to populate an array till its length with some specific values from another array?

I have a function
int[ ] fill(int[ ] arr, int k, int n) that returns an array with the length n and values consists of repetition of first k elements.
My code is:
class Repeat_block {
public static void main(String[] args) {
// TODO Auto-generated method stub
int k = 3;
int n = 10;
int arr[] = { 1, 2, 3, 5, 9, 12, -2, -1 };
System.out.println(Arrays.toString(fill(arr, k, n)));
}
public static int[] fill(int[] arr, int k, int n) {
int arr2[] = new int[n];
if (k == 0 || n <= 0) {
return null;
}
for (int i = 0; i < n; i++) {
if (i <k) {
arr2[i] = arr[i];
}
}
return arr2;
}
}
The function should return 1,2,3,1,2,3,1,2,3,1
but it's returning 1, 2, 3, 0, 0, 0, 0, 0, 0, 0 . I tried with so many ideas
but could not figure out to get the right logic. Anybody with some best ideas.
Once i == k, you need to reset it to 0. Hence you need to use two loop variables.
for (int i = 0, j = 0; i < n; i++, j++) {
if (j == k) {
j = 0;
}
arr2[i] = arr[j];
}
Replace your for-loop with:
for (int i = 0; i < n; i++) {
arr2[i] = arr[i % k]
}
Try this.
public static int[] fill(int[] arr, int k, int n) {
if (k == 0 || n <= 0) {
return null;
}
int[] ret = new int[n];
int counter = 0;
int value = 1;
while (counter < n) {
if (value > k) value = 1;
ret[counter] = value;
value++;
counter++;
}
return ret;
}
I thought it will be easy using streams and I am sure that it can be done much easier but here is my poor attempt:
import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;
class Main
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int k = 3;
int n = 10;
int arr[] = { 1, 2, 3, 5, 9, 12, -2, -1 };
fill(arr, k, n);
}
public static void fill(int[] arr, int k, int n) {
String elementsToCopy = Arrays.stream(arr)
.limit(k)
.mapToObj(String::valueOf)
.reduce((a,b) -> a.concat(",").concat(b))
.get();
List<String> resultInList = Collections.nCopies(n, elementsToCopy);
resultInList
.stream()
.collect(Collectors.toList());
System.out.println(resultInList
.toString()
.replace(" ", "")
.replace("[", "")
.substring(0, n+n-1));
}
}
Just for practice, I done that in Python3 :
def fill(arr,k,n):
c = math.ceil(n/k)
return (arr[0:k]*c)[0:n]

Return the two largest integers of an array [duplicate]

I am attempting to return the two largest integers from my int array.
I am able to return the largest and the smallest fine, but I cannot get my algorithm to return the two largest.
Any help is greatly appreciated here.
Please forgive any errors in my code. This is a practice session and the question has been taken from last years exam material at university.
Here is my code:
public class TwoLargestIntsArray {
public static void main(String [] args){
int [] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
System.out.println(twoLargest(values));
System.out.println();
}
public static int twoLargest(int values[]){
int largestA = values[0];
int largestB = values[0];
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestA = values[i];
}
if(values[i] < largestA){
largestB = values[i];
}
}
return largestA + largestB;
}
}
You can write
public static int[] twoLargest(int values[]){
int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;
for(int value : values) {
if(value > largestA) {
largestB = largestA;
largestA = value;
} else if (value > largestB) {
largestB = value;
}
}
return new int[] { largestA, largestB };
}
public static void twoLargest(int values[]){
int largestA = values[0];
int largestB = -1;
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestB = largestA;
largestA = values[i];
}
else if (values[i] > largestB && values[i] != largestA) {
largestB = values[i];
}
}
System.out.println("Largest - " + largestA);
System.out.println("2nd largest Largest - " + largestB);
}
public class Test
{
public static int[] findTwoHighestDistinctValues(int[] array)
{
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int value:array)
{
if (value > max)
{
secondMax = max;
max = value;
}
else if (value > secondMax && value < max)
{
secondMax = value;
}
}
return new int[] { max, secondMax };
}
public static void main(String []args)
{
int [] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
int []ar = findTwoHighestDistinctValues(values);
System.out.println("1 = "+ar[0]);
System.out.println("2 = "+ar[1]);
}
}
OUTPUT:
1 = 25
2 = 20
//Java8&9 makes this easier with a cleaner code
int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
int maxSize = 2;
Arrays.stream(numbers) //stream
.boxed() //to Integer Object
.sorted(Comparator.reverseOrder()) //sorted
.limit(maxSize ) //keep N values
.forEach(System.out::println);
NB. We could use this astuce with any bean Object implementing comparable or by using a related custom comparator.
You cannot have a single function return 2 values. You either have to wrap them in an array, or use reference parameters.
Pass array to be filled with values:
public static void twoLargest(int [] values, int [] ret){
//...
ret[0] = largestA;
ret[1] = largestB;
}
int [] ret = new int [2];
twoLargest(values, ret);
// now ret[0] is largestA
// and ret[1] is largestB
Try this out:
public static int[] twoLargest(int values[]){
int[] result = new int[2];
int largestA = 0;
int largestB = 0;
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestB = largestA;
largestA = values[i];
}
}
result[0] = largestA;
result[1] = largestB;
return result;
}
I am assuming it will help you in case you are able to get the largest, secondlargest, thirdlargest and so on from a function. I have created such a one :
public static int xLargest(int values[], int largeIndex)
Just pass the array and the largeIndex, for largest send 1 , for second largest send 2 and so on.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class XLargestIntArray {
public static void main(String[] args) {
int[] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
System.out.println(xLargest(values,2));
System.out.println();
}
public static int xLargest(int values[], int largeIndex) {
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < values.length; index++) {
intList.add(values[index]);
}
Collections.sort(intList);
return intList.get(intList.size() - largeIndex);
}
}
You can also use nested class to store results of your computing. For example:
private static class Result {
int largestA;
int largestB;
Result(int largestA, int largestB) {
this.largestA = largestA;
this.largestB = largestB;
}
}
And then receive data something like:
Result result = twoLargest(values);
System.out.println(result.largestA);
System.out.println(result.largestB);
Answer by #Nilesh Jadav covers all cases. Answer by #Peter Lawrey fails in cases where the array has largest value is the last element. for example [10,2,5,1,8,20] returns 20 and 8 with the accepted solution.
public static void main(String[] args) {
int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
int temp = numbers[0];
int max = temp;
int lastMax = temp;
for (int index = 1; index < numbers.length; index++){
int currentIndex = numbers[index];
// check any time is it bigger than current maximum value
max = Math.max(max, currentIndex);
// if is grow up then should be max != temp; set old Max in last or
// is not group up but current index is bigger then last index update last max value
lastMax = max != temp ? temp : Math.max(currentIndex, lastMax);
temp = max;
}
System.out.println("Last max: " + lastMax);
System.out.println("Max:" + max);
}
private static void printTwoMaxNumberWithoutSortMethod(int[] input) {
int max=0,lastMax=0;
lastMax=input[0];
max=input[0];
for(int i=1;i<input.length;i++)
{
if(lastMax<input[i] & max<input[i])
{
lastMax=max;
max=input[i];
}
}
System.out.println("lastMax="+lastMax+" : max="+max);
}
public class TwoLargestIntArray {
public static void main(String [] args){
int a[] = new int[5];
a[0] = 110;
a[1] = 50;
a[2] = 15;
a[3] = 30;
a[4] = 60;
System.out.println(twoLargest(a));
System.out.println();
}
public static int twoLargest(int a[]){
int firstMax = 0;
int secondMax = 0;
for(int i = 0; i < a.length; i++){
if(a[i]>firstMax) {
secondMax=firstMax;
firstMax = a[i];}
else if (a[i]>secondMax) {
secondMax= a[i];
}
}
return firstMax + secondMax;
}}
If performance is not an issue here, which it shouldn't be on small arrays, this could be done with less code.
The most straightforward solution is to simply sort the array and return its last, and next to last value:
public static int[] twoLargest(int[] values) {
Arrays.sort(values);
return new int[]{values[values.length - 1], values[values.length - 2]};
}
The time complexity of the above code is O(n log (n)), as stated in the Javadoc for Arrays.sort():
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
If expected input is an array with less than two elements, some error handling would need to be added, such as throwing an exception.
public static int Compute(int _arrValues[]){
int _intX = _arrValues[0];
int _intY = _arrValues[1];
for(int i = 2; i < _arrValues.length; i++){
if(_arrValues[i] > _intX){
_intX= values[i];
}
else if(_arrValues[i] > _intY){
_intY = values[i];
}
}
return _intX + _intY;
}
Try this out
int [] array1={10,2,5,1,8,20};
int largest= array1[0];
int seclargest=array1[0];
for (int i=1;i<array1.length;i++)
{
if(largest <= array1[i])
{
seclargest=largest;
largest=array1[i];
}
}
System.out.println("largest and second largest are:" +largest + " " +seclargest);

Return the two largest integers in an array of values

I am attempting to return the two largest integers from my int array.
I am able to return the largest and the smallest fine, but I cannot get my algorithm to return the two largest.
Any help is greatly appreciated here.
Please forgive any errors in my code. This is a practice session and the question has been taken from last years exam material at university.
Here is my code:
public class TwoLargestIntsArray {
public static void main(String [] args){
int [] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
System.out.println(twoLargest(values));
System.out.println();
}
public static int twoLargest(int values[]){
int largestA = values[0];
int largestB = values[0];
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestA = values[i];
}
if(values[i] < largestA){
largestB = values[i];
}
}
return largestA + largestB;
}
}
You can write
public static int[] twoLargest(int values[]){
int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;
for(int value : values) {
if(value > largestA) {
largestB = largestA;
largestA = value;
} else if (value > largestB) {
largestB = value;
}
}
return new int[] { largestA, largestB };
}
public static void twoLargest(int values[]){
int largestA = values[0];
int largestB = -1;
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestB = largestA;
largestA = values[i];
}
else if (values[i] > largestB && values[i] != largestA) {
largestB = values[i];
}
}
System.out.println("Largest - " + largestA);
System.out.println("2nd largest Largest - " + largestB);
}
public class Test
{
public static int[] findTwoHighestDistinctValues(int[] array)
{
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
for (int value:array)
{
if (value > max)
{
secondMax = max;
max = value;
}
else if (value > secondMax && value < max)
{
secondMax = value;
}
}
return new int[] { max, secondMax };
}
public static void main(String []args)
{
int [] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
int []ar = findTwoHighestDistinctValues(values);
System.out.println("1 = "+ar[0]);
System.out.println("2 = "+ar[1]);
}
}
OUTPUT:
1 = 25
2 = 20
//Java8&9 makes this easier with a cleaner code
int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
int maxSize = 2;
Arrays.stream(numbers) //stream
.boxed() //to Integer Object
.sorted(Comparator.reverseOrder()) //sorted
.limit(maxSize ) //keep N values
.forEach(System.out::println);
NB. We could use this astuce with any bean Object implementing comparable or by using a related custom comparator.
You cannot have a single function return 2 values. You either have to wrap them in an array, or use reference parameters.
Pass array to be filled with values:
public static void twoLargest(int [] values, int [] ret){
//...
ret[0] = largestA;
ret[1] = largestB;
}
int [] ret = new int [2];
twoLargest(values, ret);
// now ret[0] is largestA
// and ret[1] is largestB
Try this out:
public static int[] twoLargest(int values[]){
int[] result = new int[2];
int largestA = 0;
int largestB = 0;
for(int i = 0; i < values.length; i++){
if(values[i] > largestA){
largestB = largestA;
largestA = values[i];
}
}
result[0] = largestA;
result[1] = largestB;
return result;
}
I am assuming it will help you in case you are able to get the largest, secondlargest, thirdlargest and so on from a function. I have created such a one :
public static int xLargest(int values[], int largeIndex)
Just pass the array and the largeIndex, for largest send 1 , for second largest send 2 and so on.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class XLargestIntArray {
public static void main(String[] args) {
int[] values = new int[5];
values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;
System.out.println(xLargest(values,2));
System.out.println();
}
public static int xLargest(int values[], int largeIndex) {
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < values.length; index++) {
intList.add(values[index]);
}
Collections.sort(intList);
return intList.get(intList.size() - largeIndex);
}
}
You can also use nested class to store results of your computing. For example:
private static class Result {
int largestA;
int largestB;
Result(int largestA, int largestB) {
this.largestA = largestA;
this.largestB = largestB;
}
}
And then receive data something like:
Result result = twoLargest(values);
System.out.println(result.largestA);
System.out.println(result.largestB);
Answer by #Nilesh Jadav covers all cases. Answer by #Peter Lawrey fails in cases where the array has largest value is the last element. for example [10,2,5,1,8,20] returns 20 and 8 with the accepted solution.
public static void main(String[] args) {
int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
int temp = numbers[0];
int max = temp;
int lastMax = temp;
for (int index = 1; index < numbers.length; index++){
int currentIndex = numbers[index];
// check any time is it bigger than current maximum value
max = Math.max(max, currentIndex);
// if is grow up then should be max != temp; set old Max in last or
// is not group up but current index is bigger then last index update last max value
lastMax = max != temp ? temp : Math.max(currentIndex, lastMax);
temp = max;
}
System.out.println("Last max: " + lastMax);
System.out.println("Max:" + max);
}
private static void printTwoMaxNumberWithoutSortMethod(int[] input) {
int max=0,lastMax=0;
lastMax=input[0];
max=input[0];
for(int i=1;i<input.length;i++)
{
if(lastMax<input[i] & max<input[i])
{
lastMax=max;
max=input[i];
}
}
System.out.println("lastMax="+lastMax+" : max="+max);
}
public class TwoLargestIntArray {
public static void main(String [] args){
int a[] = new int[5];
a[0] = 110;
a[1] = 50;
a[2] = 15;
a[3] = 30;
a[4] = 60;
System.out.println(twoLargest(a));
System.out.println();
}
public static int twoLargest(int a[]){
int firstMax = 0;
int secondMax = 0;
for(int i = 0; i < a.length; i++){
if(a[i]>firstMax) {
secondMax=firstMax;
firstMax = a[i];}
else if (a[i]>secondMax) {
secondMax= a[i];
}
}
return firstMax + secondMax;
}}
If performance is not an issue here, which it shouldn't be on small arrays, this could be done with less code.
The most straightforward solution is to simply sort the array and return its last, and next to last value:
public static int[] twoLargest(int[] values) {
Arrays.sort(values);
return new int[]{values[values.length - 1], values[values.length - 2]};
}
The time complexity of the above code is O(n log (n)), as stated in the Javadoc for Arrays.sort():
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
If expected input is an array with less than two elements, some error handling would need to be added, such as throwing an exception.
public static int Compute(int _arrValues[]){
int _intX = _arrValues[0];
int _intY = _arrValues[1];
for(int i = 2; i < _arrValues.length; i++){
if(_arrValues[i] > _intX){
_intX= values[i];
}
else if(_arrValues[i] > _intY){
_intY = values[i];
}
}
return _intX + _intY;
}
Try this out
int [] array1={10,2,5,1,8,20};
int largest= array1[0];
int seclargest=array1[0];
for (int i=1;i<array1.length;i++)
{
if(largest <= array1[i])
{
seclargest=largest;
largest=array1[i];
}
}
System.out.println("largest and second largest are:" +largest + " " +seclargest);

Categories

Resources