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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...