Skip to main content

Apple and Orange Hackerrank solution in Java | Java 8 solution

Java 8 solution for Apple and Orange HackerRank problem 

Apple and Orange solution using java 8

Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house. 

In the diagram below:

  • The red region denotes the house, where s is the start point, and t is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right. 
  • Assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b.
  • When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. *A negative value of d means the fruit fell d units to the tree's left, and a positive value of d means it falls d units to the tree's right.

Apple and Orange problem description

 

Given the value of d for m apples and n oranges, determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range [s, t])?

For example, Sam's house is between s = 7 and t = 10. The apple tree is located at a = 4 and the orange at b = 12. There are m = 3 apples and n = 3 oranges. Apples are thrown apples = [2, 3, -4] units distance from a, and oranges =[3, -2, -4] units distance. Adding each apple distance to the position of the tree, they land at [4 + 2, 4 + 3, 4 + -4] = [6, 7, 0]. Oranges land at [12 + 3, 12 + -2, 12 + -4] = [15, 10, 8]. One apple and two oranges land in the inclusive range 7 - 10 so we print 

1
2

See full problem description on HackerRank :

Lets see solution.

Solution 1 : Apple and Orange solution using for loop

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    public static void countApplesAndOranges(int s, int t, int a, int b,
            List<Integer> apples, List<Integer> oranges) {
       
        int totalApples = 0;
        for (Integer apple : apples) {
            if ((a + apple) >= s &&  (a + apple) <= t) {
                totalApples++;
            }
        }
        
        int totalOranges = 0;
        for (Integer orange : oranges) {
            if ((b + orange) >= s &&  (b + orange) <= t) {
                totalOranges++;
            }
        }
        
        System.out.print(totalApples + "\n" +totalOranges);

    }
}


public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int s = Integer.parseInt(firstMultipleInput[0]);

        int t = Integer.parseInt(firstMultipleInput[1]);

        String[] secondMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int a = Integer.parseInt(secondMultipleInput[0]);

        int b = Integer.parseInt(secondMultipleInput[1]);

        String[] thirdMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int m = Integer.parseInt(thirdMultipleInput[0]);

        int n = Integer.parseInt(thirdMultipleInput[1]);

        List<Integer> apples = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        List<Integer> oranges = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        Result.countApplesAndOranges(s, t, a, b, apples, oranges);

        bufferedReader.close();
    }
}

Solution explanation :

  • In countApplesAndOranges() method we already have s as start point, t as end point, a as apple tree location, b as orange tree location, and list of apples and oranges location that are fallen.
  • So we have to simply count the total number of apples and oranges that are fall in sam's house (between start point s and end point t).
  • Loop through both apples and oranges list one by one and count all fruits that are fallen into sam's house location.
  • Define two int variable totalApples and totalOranges and initialize with 0.
  • Traverse loop from 0 to apples list size. check which apples are fallen into sam's house location. Increment totalApple, if apple is found in sam's house location. do same thing for oranges list.
  • Last, print totalApples and totalOranges variable values.

Output explanation :

s = 7, t = 11, a = 5, b = 15, apples = [-2, 2, 1], oranges = [5, -6]

  • totalApples = 0, totalOranges = 0
  • Traverse through apples list.
    • index = 0 | 5 + -2 >= 7 && 5 + -2 <= 11 becomes false.
    • index = 1 | 5 + 2 >= 7 && 5 + 2 <= 11 becomes true.
      • totalApples++ | totalApples = 1.
    • index = 2 | 5 + 1 >= 7 && 5 + 1 <= 11 becomes false.

  • totalApples = 1, totalOranges = 0
  • Traverse through oranges list.
    • index = 0 | 15 + 5 >= 7 && 15 + 5 <= 11 becomes false.
    • index = 1 | 15 + -6 >= 7 && 15 + -6 <= 11 becomes true.
      • totalOranges++ | totalOranges = 1.

  • totalApples = 1, totalOranges = 1

 

lets see another solution using java 8 

Solution 2 : Apple and Orange solution using Java 8

public static void countApplesAndOranges(int s, int t, int a, int b,
        List<Integer> apples, List<Integer> oranges) {
   
    long totalApples = apples.stream()
            .filter(apple -> (a + apple) >= s && (a + apple) <= t)
            .count();
    
    long totalOranges = oranges.stream()
            .filter(orange -> (b + orange) >= s && (b + orange) <= t)
            .count();
    
    System.out.print(totalApples + "\n" +totalOranges);

}

Solution explanation :

We are using Java 8 stream filter() method for filtering out our condition data. if any condition is matched in filter method, it stores count in our int variable using count() method.

 

See other hackerrank problem and its solution in java :


Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last