# Apple and Orange

# Apple and Orange

navjotahuja92 + 46 comments python way ;)

print(sum([1 for x in apple if (x + a) >= s and (x + a) <= t])) print(sum([1 for x in orange if (x + b) >= s and (x + b) <= t]))

chelBot + 2 comments omg...this is wonderful! I didn't know we could add 1 to a comprehension this way.

jonathandygert + 17 comments You can also use the fact that

`True == 1`

and`False == 0`

`print(sum(s <= a + d <= t for d in apples)) print(sum(s <= b + d <= t for d in oranges))`

nonotaka888 + 1 comment Great and simple way. I didn't know that. Thanks.

[deleted] + 6 comments This was my code, could anyone please help with what's the problem here?

def countApplesAndOranges(s, t, a, b, apples, oranges): apls = list(apples) orls = list(oranges) avf = [] ovf = [] for v in apls: if (a+v)>=s: avf.append(v) for g in orls: if (b+g)<=t: ovf.append(g) print len(avf) print len(ovf)

jamesallenvinoy + 0 comments You will have to consider both 's' and 't' for the both the loops.

ramrakesh64 + 0 comments Instead of appending to a list, you might have to take a variable with value 0 and then increment it in the IF loop. However, the problem with this kind of code(even I wrote the same) is this terminates because of the timeout error(though it is correct). First comment in this section gives an absolute answer.

oneacg + 0 comments [deleted]oneacg + 0 comments def countApplesAndOranges(s, t, a, b, apples, oranges): avf = [] ovf = [] for v in apples: if (a+v)>=s and (a+v)<=t: avf.append(v) for g in oranges: if (b+g)<=t and (b+g)>=s: ovf.append(g) print (len(avf)) print (len(ovf))

You dont have to create another list with in the definition. Also, as some one stated , you have to take both "s" and "t" into consideration. Remember we are trying to see if the apples fell with in the boundaries of "s" and "t".

vk71035 + 0 comments manaki avasarama ivi...velli pani chusko

Din96_Boy + 0 comments Thanks , i modified your code and i was able to get the answer

def countApplesAndOranges(s, t, a, b, apples, oranges): apple2 = list(apples) orange2 = list(oranges) count_apple =0 count_orange =0 for i in apple2: if s <= (a+i)<=t: count_apple +=1 for j in orange2: if s <= (b+j) <= t: count_orange +=1 print(count_apple) print(count_orange)

tpb261 + 1 comment I don't even use apple and orange lists (explicitly)

print(sum([s<=int(apple_temp)+a<=t for apple_temp in input().strip().split(' ')]))

)

punithsk + 2 comments appleno = 0 orangeno = 0 for no in apple: if (no + a) in range(s,t+1): appleno += 1 for no in orange: if (no + b) in range(s,t+1): orangeno += 1 print appleno print orangeno

It says timed out. Can you tell me why. I have changed it to no+a >= s and no+a <= t. But i need to know why the former one doesn't work. Thank you

Kush131 + 2 comments Not sure if you eventually figured it out, but I tried the same approach and was having issues too. What fixed it for me was replacing "... in range(s,t)" with greater than or equal to & less than or equal to statements. It must be something specific with in or range that is causing issues.

jonathandygert + 2 comments Using

`x in range(s, t)`

means that for each check, you have to do worst case scenario (t-s-1) equality comparisons. Using`s <= x < t`

means that you do 2 comparisons for each check.klu_170030059 + 0 comments int main(){ int s; int t,count1=0,count2=0; scanf("%d %d",&s,&t); int a; int b; scanf("%d %d",&a,&b); int m; int n; scanf("%d %d",&m,&n); int temp; for(int apple_i = 0; apple_i < m; apple_i++){ scanf("%d",&temp); if(temp+a>=s && temp+a<=t) { count1++; } } for(int orange_i = 0; orange_i < n; orange_i++){ scanf("%d",&temp); if(temp+b>=s && temp+b<=t) { count2++; } } printf("%d\n",count1); printf("%d",count2); return 0; }

[deleted] + 0 comments i did the same way but initialised range only once def countApplesAndOranges(s, t, a, b, apples, oranges): house_length = range(s,t+1) apple_tree_location =a orange_tree_location =b apple_house_hit_count=0 orange_house_hit_count=0 for fall_pos in apples: if fall_pos+apple_tree_location in house_length: apple_house_hit_count +=1 for fall_pos in oranges: if fall_pos+orange_tree_location in house_length: orange_house_hit_count +=1 print("{}\n{}".format(apple_house_hit_count,orange_house_hit_count))

`it worked .`

Jlookup + 4 comments OMG I'm switching

me = js; if (python == thisEasy){ me = python; }

SamRwanda + 0 comments Haha if you can switch please do it, Python is easy to fall in love with.

Unremarkable + 2 comments It isn't that much worse in JavaScript, except that JS Arrays don't have sum naturally.

Array.prototype.sum = function(f) { return this.reduce((s, v) => s + f(v), 0); } console.log( apple.sum(d => s - a <= d && d <= t - a)); console.log(orange.sum(d => s - b <= d && d <= t - b));

Or, just with reduce:

console.log( apple.reduce((sum, d) => sum + (s - a <= d && d <= t - a), 0)); console.log(orange.reduce((sum, d) => sum + (s - b <= d && d <= t - b), 0));

Or, by filtering instead:

console.log( apple.filter(d => s - a <= d && d <= t - a).length); console.log(orange.filter(d => s - b <= d && d <= t - b).length);

kidkkr + 1 comment I prefer map with filter. for more functionally speaking,

function addBy(num) { return (d) => d + num; } function isScored(d) { return s <= d && d <= t; } const larry = apples.map(addBy(a)).filter(isScored).length; const rob = oranges.map(addBy(b)).filter(isScored).length; console.log(larry, rob);

piyush_danej + 0 comments This solution does seem cute . But its using 4 loops . Kinda expensive .

piyush_danej + 1 comment yeah that seems simple for sure , But is there a way to solve it just using one loop ? I tried but all the tests didn't pass. However using 2 separate loops did it .

jorgesanure + 0 comments [[a,apples], [b,oranges]].forEach(fs => { console.log( fs[1] .reduce( (st,e) => st + (e+fs[0]>=s && e+fs[0]<=t ? 1:0) ,0 ) ); });

andrewsenner + 0 comments Careful,

`thisEasy`

could be a falsey value. :-)sd_afzal_hussain + 1 comment Python way ;)

me = python if python == thisEasy else js

apolo4pena + 0 comments `me = job = dictates(lang)`

Alekhya3110 + 0 comments hey! i did the same way though! python is great

diego_amicabile + 2 comments or len

print(len([x for x in apple if s <= x+a <= t ]), len([y for y in orange if s <= y+b <= t ]),sep = '\n')

ridoansalehnst + 0 comments what is the utility of 'x' before for loop ?

nsticco + 0 comments [deleted]

satyamdwivedi_s1 + 2 comments # include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

using namespace std;

int main(){ int s; int t; cin >> s >> t; int a; int b; cin >> a >> b; int m; int n;

`cin >> m >> n; int ctr1=0,ctr2=0; vector<int> apple(m); for(int apple_i = 0;apple_i < m;apple_i++){ cin >> apple[apple_i]; if(apple[apple_i]>0 && (s<=a+apple[apple_i] && a+apple[apple_i]<=t)) ctr1++; } vector<int> orange(n); for(int orange_i = 0;orange_i < n;orange_i++){ cin >> orange[orange_i]; if(orange[orange_i]<0 && (s<=b-abs(orange[orange_i]) && b-abs(orange[orange_i])<=t)) ctr2++; } cout<<ctr1<<"\n"<<ctr2; return 0;`

}

dahveed + 0 comments do you need to add the condition that apple[apple_i]>0 or orange[orange_i] <0? isn't this extra?

milczarek_r + 0 comments You can move the code for calculating number of fruits on house to function to keep it DRY:

int CalculateNumberOfFruitsOnHouse(int s, int t, int tree, const std::vector<int> &fruits) { int rel_s = s - tree; int rel_t = t - tree; int num = 0; for(int fruit : fruits){ if(fruit >= rel_s && fruit <= rel_t) ++num; } return num; }

SEK7I0N + 0 comments [deleted]kbenriquez + 1 comment I'm not a Python expert but wouldn't your code create an entry into an array for every value whether it be true or false? I'm concerned about the performance so I created my code below. Feedback would be greatly appreciated as well as tips to improve my coding. :D

def appleAndOrange(s, t, a, b, apple, orange): x = len([1 for i in apple if i+a in range(s,t+1)]) y = len([1 for i in orange if i+b in range(s,t+1)]) return [x,y]

klu_170030059 + 1 comment peace.....brooo....

klu_170030059 + 0 comments lollll...............

nsadi + 0 comments Alternate Python solution, make a range over the length of the house...

r = range(s,t+1) print(sum([a+x in r for x in apples])) print(sum([b+x in r for x in oranges]))

nsticco + 0 comments It's about 5 times faster on my machine to put the list comprehension within brackets:

print(sum([s <= a + d <= t for d in apples])) print(sum([s <= b + d <= t for d in oranges]))

laurence_woodwa1 + 0 comments This is beautiful. I dream that one day I'll solve one of these problems this elegantly. :-)

alijonmr05 + 0 comments great solution

kapoorkaran612 + 0 comments can you explain this ?

vidhyarukkumani + 0 comments good optimisation....thanks

utkarshGG + 0 comments a < b < c Saw this in python docs tutorial and wondered where this would be useful. Thanks @jonathandygert

congcongluk + 0 comments Brilliant

priti_jha + 0 comments This is great solution! I didn't know that true could be used for adding 1 in every iteration...

SamRwanda + 0 comments Me too :)

himanshu_tiwari + 0 comments Here's another one ;)

print([d+a>=s and d+a<=t for d in apple].count(True))

print([b+d>=s and b+d<=t for d in orange].count(True))

[DELETED] + 0 comments [deleted]fabien_dumay + 5 comments Nice... The Java 8 is not bad too :) a bit longer, but easy to understand.

Arrays.stream(apple) .filter(x -> x + a >= s && x + a <= t) .count(); Arrays.stream(orange) .filter(x -> x + b >= s && x + b <= t) .count();

FilipF + 0 comments Yup yup, streams make things elegant. Array streams also give you an opportunity to use

`.parallel()`

. Another variation is to skip reading into an array first:long orangeHits = IntStream.generate(()->in.nextInt()) .limit(n) .filter(d -> d+b>=s && d+b<=t) .count();

stonyark + 0 comments This is amazing. Thank you :D

ash_jo4444 + 0 comments How do you print the count?

mvmarlow + 0 comments this works in Eclipse for me but generates "illegal start of expression" at the code "x -> x+a". Sans quotes, of course.

vladimir_strati1 + 0 comments Or:

Arrays.stream(apples).filter(d -> ValueRange.of(s, t).isValidIntValue(a+d)).count()

abhishek106 + 0 comments this is amazing! thanks for sharing

Jlookup + 0 comments We are potentially dealing with a large number of large numbers. I don't want hold those big arrays in memory. I just want to evaulate each number and keep track of the count. Does this code accomplish that? Feedback please.

Python 3:

import sys def countHits(lHouse, rHouse, treeLoc): lDist = lHouse - treeLoc rDist = rHouse - treeLoc return sum(1 for spot in input().strip().split(' ') if hitHouse(int(spot), lDist, rDist)) def hitHouse(spot, lDist, rDist): if spot >= lDist and spot <= rDist: return True lHouse, rHouse = [int(x) for x in input().strip().split(' ')] aTree, oTree = [int(x) for x in input().strip().split(' ')] aCount, oCount = [int(x) for x in input().strip().split(' ')] print (countHits(lHouse, rHouse, aTree)) print (countHits(lHouse, rHouse, oTree))

lovereli + 1 comment more pythonic

print(sum([1 for each in apple if s <= (each + a) <=t])) print(sum([1 for each in orange if s <= (each + b) <=t]))

Slaunger + 1 comment No need for the list and no need for the '1'

s, t = map(int, input().split()) a, b = map(int, input().split()) _ = input() print(sum(s <= (a + i) <= t for i in map(int, input().split()))) print(sum(s <= (b + i) <= t for i in map(int, input().split())))

randybrown18 + 0 comments Recommend using lambda funtion for efficiency :D

djs21 + 3 comments Swift way:

print(apples.filter{$0 + a >= s && $0 + a <= t}.count) print(oranges.filter{$0 + b >= s && $0 + b <= t}.count)

jonathandygert + 0 comments Ruby way:

puts apples.count { |apple| (a + apple).between?(s, t) } puts oranges.count { |orange| (b + orange).between?(s, t) }

jay_yupinhu + 0 comments I love this swift solution!

AjaySenthu13 + 2 comments *// More simplified :-D*`print(apples.filter({s...t ~= $0 + a}).count) print(oranges.filter({s...t ~= $0 + b}).count)`

ariel205 + 0 comments This is the best solution because uses Ranges and Filter function. I also do it in this way.

NiteOwl066 + 0 comments I also find this solution the best. But I create a range constant to avoid repeating s...t and made the code a little bit easier to understand on quick glance.

let houseRange = s...t print(apples.filter({ houseRange.contains($0 + a) }).count) print(oranges.filter({ houseRange.contains($0 + b) }).count)

coderai + 0 comments We can also use

`range`

function here :`print(sum([ 1 for app in apple if a+(app) in range(s,t+1)])) print(sum([ 1 for org in orange if b+(org) in range(s,t+1)]))`

yash71720 + 0 comments OMG!! this is simply awesome dude.... i never thought that python could be this much flexible

Ardillo + 0 comments apple = list(filter(lambda x: s-a <= x <= t-a, map(int, input().split()))) orange = list(filter(lambda x: s-b <= x <= t-b, map(int, input().split()))) [print(x) for x in map(len, [apple, orange])]

satyamdwivedi_s1 + 0 comments # include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

using namespace std;

int main(){ int s; int t; cin >> s >> t; int a; int b; cin >> a >> b; int m; int n;

`cin >> m >> n; int ctr1=0,ctr2=0; vector<int> apple(m); for(int apple_i = 0;apple_i < m;apple_i++){ cin >> apple[apple_i]; if(apple[apple_i]>0 && (s<=a+apple[apple_i] && a+apple[apple_i]<=t)) ctr1++; } vector<int> orange(n); for(int orange_i = 0;orange_i < n;orange_i++){ cin >> orange[orange_i]; if(orange[orange_i]<0 && (s<=b-abs(orange[orange_i]) && b-abs(orange[orange_i])<=t)) ctr2++; } cout<<ctr1<<"\n"<<ctr2; return 0;`

}

LeHarkunwar + 1 comment Did nearly the same

print(len([1 for app in apple if app >= s-a and app <= t-a])) print(len([1 for ora in orange if ora <= t-b and ora >= s-b]))

Slaunger + 1 comment No need for the '1', and the [] and the condition can be written simpler. Also no need to read the entire thing in as a list, which can be very memory consuming. Here using all iterators

... print(sum(s <= (a + i) <= t for i in map(int, input().split()))) print(sum(s <= (b + i) <= t for i in map(int, input().split())))

LeHarkunwar + 0 comments Yeah, that's a good way to do it, I also did this in another question.

dinesh_pi + 0 comments can someone explain the sum function and for function please

minLewis + 0 comments That is beautiful, I feel like such a barbarian...

app_cnt = 0 org_cnt = 0 for ap in apple: if ap > 0: if t >= a+ap >= s: app_cnt += 1 for og in orange: if og < 0: if t >= b+og >= s: org_cnt += 1 print(app_cnt) print(org_cnt)

suryach750 + 0 comments can you explain what is the use of "1" here

cryomick + 0 comments print(len([x for x in apple if x>0 and a+x>=s and a+x<=t])) print(len([y for y in orange if y<0 and b+y<=t and b+y>=s]))

I know that the savings are miniscule, but discarding the distances are to the left of the apple tree or to the right of the orange tree reduces the number of values to check.

della90 + 0 comments You can also get rid of

`(x + a) >= s and (x + a) <= t`

and replace it with`s <= a + d <= t`

or`a + d in range(s, t+1)`

nimish_gupta + 0 comments [deleted]mahesh_vemula + 0 comments c = list(filter(lambda x: x==True, map(lambda x: a+x in range(s,t+1),apples))) d = list(filter(lambda x: x==True, map(lambda x: b+x in range(s,t+1),oranges))) print(str(len(c))+"\n"+str(len(d)))

Is this code worthy?

thma1 + 0 comments Python rocks!

mariojsanchez15 + 0 comments The solution is very elegant, but the complexity of the algorithm is being affected as a consequence.

srisamatha80 + 0 comments another way:) print(len([i for i in apples if i+a in range(s,t+1)])) print(len([i for i in oranges if i+b in range(s,t+1)]))

I_Shaunt + 0 comments print(sum((a + i) in range(s, t+1) for i in appleDistance)) print(sum((b + i) in range(s, t+1) for i in orangeDistance))

dimare_christian + 0 comments similarly, you could:

apples = map(lambda x: 1 if s <= a+x <= t else 0, apples) oranges = map(lambda x: 1 if s <= b+x <= t else 0, oranges) print(sum(apples), sum(oranges))

they're both pretty pythonic. but list comprehensions are bae

qwerty983 + 2 comments `int ax = apples.Where(x=>s<=(x+a)&&(x+a)<=t).Count(); int ox = oranges.Where(x=>s<=(x+b)&&(x+b)<=t).Count(); c# style ;)`

rearbreed + 0 comments [deleted]anon117 + 1 comment Here is a c# way that doesn't do uneeded additions or comparisons.

Console.WriteLine(apples.Where(x => HitHouse(s,t,a,x)).Count()); Console.WriteLine(oranges.Where(x => HitHouse(s,t,b,x)).Count());

With the comparison function:

static bool HitHouse(int houseStart, int houseEnd, int treeLoc, int objectLoc) { int loc = treeLoc + objectLoc; return !(loc < houseStart || loc > houseEnd); }

calegria + 1 comment You are making additions and comparisons in HitHouse.

anon117 + 1 comment I said that it doesn't do uneeded ones. Not that it doesn't do them at all. Many of the solutions here (like querty's) do two additions per comparison instead of caching one.

calegria + 1 comment Oh I see. Sorry about that.

Nevertheless, I still do not see how you are saving uneeded comparisons. Also, I think your solution still does uneeded additions. Check this C++ code.

`std::cout << count_fruits(apples, s - a, t - a) << std::endl << count_fruits(oranges, s - b, t - b);`

Where the function count_fruits is like this:

`int count_fruits (vector<int>& fruits, int s, int t) { return std::accumulate( fruits.begin(), fruits.end(), 0, [&] (int v, int f) { return v + (s <= f && f <= t ? 1 : 0); }); };`

anon117 + 0 comments Looking back on it, yes it makes much more sense to do the subtraction upfront to prevent an extra math operation per iteration. Also using LINQ Aggregate would be a better solution overall based on the what the solution requires.

amylokh + 0 comments I love python man!

geekysoham + 0 comments I used your method but im getting 12 test cases failed.Can u explain why??

lorsem + 0 comments In a functional way: (using Python3)

filter(lambda x: x+a in range(s,t+1), apples))

Exploiting the fact that checking on a range has O(1) complexity when checking integers against integer bounds and using the built-in filter function. What filter does is basically "let through" only those elements of the iterable (

*apples*) that satisfy the predicate (in this case the*lambda*function). The resulting filter object will result in a list that has only the apples fallen on the house, whose lenght is the answer. Therefore,result = len(list(filter(lambda x: x+a in range(s,t+1), apples))))

EthanHunt1104 + 0 comments // Complete the countApplesAndOranges function below. function countApplesAndOranges(s, t, a, b, apples, oranges) { let appleCount = apples.filter(val => val + a >= s && val+a <= t).length; let orangeCount = oranges.filter(val => val + b >= s && val + b <= t).length; console.log(`${appleCount} ${orangeCount} `); }

1616410257_cs3e + 0 comments GREAT WAY!!!!! python way@@@@@

sourabhcharlie11 + 0 comments print(sum([1 for x in apple if (x+a) in range(s,t+1)])) print(sum([1 for x in orange if (x+b) in range (a,t+1)])) even simpler

mahender933 + 0 comments inclusiverange = range(s,t+1)

ap = sum(1 for apple in apples if apple + a in inclusiverange)

on = sum(1 for orange in oranges if orange + b in inclusiverange)

print(ap)

print(on)

calegria + 0 comments C++ way

`auto count_fruits = [] (vector<int>& fruits, int s, int t) -> int { return std::accumulate( fruits.begin(), fruits.end(), 0, [&] (int v, int f) { return v + (s <= f && f <= t ? 1 : 0); }); }; std::cout << count_fruits(apples, s - a, t - a) << std::endl << count_fruits(oranges, s - b, t - b);`

}

vishalvlc01 + 0 comments why 1 is return before for

itaim918 + 0 comments not very efficient though... worst case if there are 10^5 apples and oranges that all fall within the house, then you are just creating and recreating (twice- once for each fruit) an array that is being extended by one cell one at a time (or by some random buffer decided on by the python sdk) 10^5 times instead of just immediately incrementing a single value without any memory allocations. I would expect this to ime out on longer inputs.

pamuditha_i + 0 comments If you are a beginner and don't know much about comprehensions, here's the basic code without the use of comperhensions. It's basically the same thing! :p

ain=oin=0 for i in range (len(apples)): apples[i]=apples[i]+a if apples[i]<=t and apples[i]>=s: ain=ain+1 else: ain=ain for i in range (len(oranges)): oranges[i]=oranges[i]+b if oranges[i]<=t and oranges[i]>=s: oin=oin+1 else: oin=oin print(ain) print(oin)

shoaibmalek21 + 0 comments Great....

mihirbosemj + 0 comments `def countApplesAndOranges(s, t, a, b, apples, oranges): house_range = range(s,t+1) valid_apples, valid_oranges = 0,0 for i in apples: if i + a in house_range: valid_apples += 1 for j in oranges: if j + b in house_range: valid_oranges += 1 print valid_apples print valid_oranges`

Why is using for loop like this so much slower than the solution presented by @navjotahuja92? It is also using for loop and an if condition within it.

utkarshGG + 0 comments print(len([e for e in list(map(lambda dis: dis + a, apples)) if e >= s and e <= t]))

mine is a bit longer I guess.

mohamedjohnson31 + 0 comments Good but you don't really need to print it as a list Check this:

#!/bin/python3

`def countApplesAndOranges(s, t, a, b, apples, oranges): print (sum(1 for fruit in apples if (fruit + a) >= s and (fruit + a) <= t)) print (sum(1 for fruit in oranges if (fruit + b) >= s and (fruit + b) <= t))`

Or simply count of the True and false doing this:

`print(sum(s <= a + fruit <= t for fruit in apples)) print(sum(s <= b + fruit <= t for fruit in oranges))`

junaidshk + 0 comments typo: apple->apples, orange->oranges. still best solution. gud goin.

russomariod + 1 comment Faster way would be to use the len() function instead of sum()

mohamedjohnson31 + 0 comments Can you develop please

865771354c + 0 comments great!! wonderful solution

samuelonyeukwu2 + 0 comments Lol I actually dont understand whats going on here, could anyone explain

priti_jha + 0 comments This is really great ... I was first adding and then checking on other line.But this can be done in one line.So thanks!!

RodneyShag + 16 comments ### Java solution - passes 100% of test cases

From my HackerRank solutions.

Runtime: O(m + n)

Space Complexity: O(1)Avoid using arrays to store values since that will take O(m + n) space.

import java.util.Scanner; public class Solution { public static void main(String[] args) { /* Read and save input */ Scanner scan = new Scanner(System.in); int s = scan.nextInt(); int t = scan.nextInt(); int a = scan.nextInt(); int b = scan.nextInt(); int m = scan.nextInt(); int n = scan.nextInt(); /* Calculate # of apples that fall on house */ int applesOnHouse = 0; for (int i = 0; i < m; i++) { int applePosition = a + scan.nextInt(); if (applePosition >= s && applePosition <= t) { applesOnHouse++; } } System.out.println(applesOnHouse); /* Calculate # of oranges that fall on house */ int orangesOnHouse = 0; for (int i = 0; i < n; i++) { int orangePosition = b + scan.nextInt(); if (orangePosition >= s && orangePosition <= t) { orangesOnHouse++; } } System.out.println(orangesOnHouse); scan.close(); } }

Let me know if you have any questions.

jathavedas + 1 comment Nice... I was using arrays and test results were failing for a few use cases. Thank you

RodneyShag + 1 comment You're very welcome.

HarishTati + 1 comment do you have answer using arrays?

sirlacky + 0 comments Here you go:

`int applesOnHouse = 0; for (int i = 0; i < apples.length; i++) { int applePosition = a + apples[i]; if (applePosition >= s && applePosition <= t) { applesOnHouse++; } } System.out.println(applesOnHouse); int orangesOnHouse = 0; for (int i = 0; i < oranges.length; i++) { int orangePosition = b + oranges[i]; if (orangePosition >= s && orangePosition <= t) { orangesOnHouse++; } } System.out.println(orangesOnHouse);`

darpan_dodiya + 1 comment Liked your variable name conventions!

RodneyShag + 0 comments Thanks :)

sanjugodara13 + 1 comment Done in the same way but it is not passing some of the test cases

RodneyShag + 1 comment Hi. Try to compare your code to mine line by line to see what we have done differently. Or, try to use portions of my code in your code to narrow down where the bug may be.

sanjugodara13 + 0 comments Thanks but i had sorted out the bug at the same day .

sanjugodara13 + 0 comments [deleted]KhateebXtreme + 0 comments after seeing your code ..i found the bug..why my memory stack was hitting the bar of 50 kb ...thanks

thecodeavenger + 1 comment Can you explain why the code fails if it is done using arrays?

RodneyShag + 1 comment I am assuming you want 1 array for apples, and another for oranges. This would take O(n+m) space. Using arrays in this way would require more space, since we would be saving positions of all the fruit in the function.

I think the code fails since HackerRank sets on the amount of memory/space they let you use in this challenge.

jp_makka + 1 comment do u know how to rectify that???

RodneyShag + 0 comments I don't think you can change the space limitations they set.

priyankap1022 + 1 comment Hey!! Can you once explain why does some cases fail when using arrays?

KhateebXtreme + 0 comments its all about space time complexity...duh most of those failing testcases due to timeout occurs due to this

pandeysdr16 + 1 comment can u plz explain this line?

int applePosition = a + scan.nextInt(); if (applePosition >= s && applePosition <= t)

RodneyShag + 1 comment int applePosition = a + scan.nextInt();

The above line calcalates the apple's position by adding the variables

**a**and**d**(where d is read from input). The problem has a picture that shows what these correspond to.if (applePosition >= s && applePosition <= t)

The above line checks to see if the apple's position is in between

**s**and**t**. These 2 variables are also depicted in the problem's picture.pandeysdr16 + 0 comments ok , got it. Thank you.

ajayshakya + 1 comment please can u explain this code: int orangePosition = b + scan.nextInt();

LePetitRenard + 0 comments Basically the

**positionOfFallenOrange**equals the**positionOfOrangeTree**plus the**distanceFromTheOrangeTree****orangePosition**=**b**+**scan.nextInt()**;Hope it makes sense :)

tomcollier94 + 0 comments I did it the same way, however I left the arrays as getting rid of them didn't even cross my mind!

**-Thank You!**sudheera_nv + 0 comments wow, this is gread solution. something to lern as well

alfredooctavio + 2 comments I did it in the same way but I include more code for constraints. My code passes 100% test cases too. I saw that you does not include code for constraints. It is weird that your code passes 100% test cases, may be the test cases not include the constraints validation. Well congratulations your code is great.

Let me share my code, any comment is welcome:

public static void main(String[] args) { Scanner in = new Scanner(System.in); int s = in.nextInt(); int t = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int m = in.nextInt(); int n = in.nextInt(); int[] datas = {s,t,a,b,m,n}; int apples = 0, oranges = 0; for(int data:datas){ if( (data <=1) && (data >= Math.pow(10,5)) ){ System.err.println("Data out of range."); System.exit(-1); } } if( (a > s) && (s > t) && (t > b )){ System.err.println("the data does not meet the requirements."); System.exit(-1); } int[] apple = new int[m]; for(int apple_i=0; apple_i < m; apple_i++){ apple[apple_i] = in.nextInt(); if( apple[apple_i] >= Math.pow(-10,5) && apple[apple_i] <= Math.pow(10,5)){ if( ( (a + apple[apple_i]) >= s) && ( (a + apple[apple_i]) <= t) ) apples++; } else{ System.err.println("Apple: Distance out of the range."+apple[apple_i]); System.exit(-1); } } int[] orange = new int[n]; for(int orange_i=0; orange_i < n; orange_i++){ orange[orange_i] = in.nextInt(); if( orange[orange_i] >= Math.pow(-10,5) && orange[orange_i] <= Math.pow(10,5)){ if( ( (b + orange[orange_i]) >= s) && ( (b + orange[orange_i]) <= t) ) oranges++; } else{ System.err.println("Orange: Distance out of the range."+orange[orange_i]); System.exit(-1); } } System.out.println(apples); System.out.println(oranges); }

RodneyShag + 1 comment Good job. You don't need to account for constraints. By listing constraints in the problem statement, HackerRank ensures that the data they pass to your program will be within those constraints.

alfredooctavio + 0 comments Thank you for your comment I'll keep it in mind.

code__raider + 0 comments great job, man !!!

zakiralig184 + 0 comments Nice! U r careful about space complexity. Go on your discussion.Thanks

drashti1712 + 1 comment This is a much better solution.. I tried to compare the distances and it took way too long for the program to compile... Can you tell how to think of a time efficient approach?

RodneyShag + 0 comments "Cracking the Coding Interview" is good at explaining runtime complexities to create time efficient solutions. I usually find a working solution first then see where I can optimize it.

adityakapoor1001 + 1 comment Just wanted to know, if this question were in competitive programming,which technique would have been better? the way you or I did it or the one using streams or others few solved cases?

RodneyShag + 0 comments Not sure. I've never done competitive programming.

vtu10370 + 0 comments thank u nice logic really mindblowing. i also use array.

good job sir.

DavidODW + 3 comments javascript way :)

var apple_count = apple.filter(value => value + a >= s && value + a <= t).length; var orange_count = orange.filter(value => value + b >= s && value + b <= t).length;

vityavv + 0 comments That way might be quicker than mine but I think mine looks nicer

function appleAndOrange(s, t, a, b, apple, orange) { return [ apple.map(p => p + a).filter(p => p >= s && p <= t).length, orange.map(p => p + b).filter(p => p >= s && p <= t).length ] }

jasper_brumter + 3 comments `var i; var countApples = 0; var countOranges = 0; for (i = 0; i < apples.length; i++) { if (a + apples[i] >= s && a + apples[i] <= t) { countApples += 1; } } for (i = 0; i < oranges.length; i++) { if (b + oranges[i] >= s && b + oranges[i] <= t) { countOranges += 1; } } console.log(countApples); console.log(countOranges);`

What do you guys think?

arninho + 1 comment I also used this method. As a beginner, I think it is easier to understand then those oneliner.

function countApplesAndOranges(s, t, a, b, apples, oranges) { let totalApples = 0; let totalOranges = 0; for (let i = 0; i <= apples.length; i++) { if (a + apples[i] >= s && a + apples[i] <= t) { totalApples += 1; } } for (let i = 0; i <= oranges.length; i++) { if (b + oranges[i] >= s && b + oranges[i] <= t) { totalOranges += 1; } } console.log(totalApples); console.log(totalOranges); }

mshahid85 + 0 comments clean code.

js428118 + 0 comments [deleted]apolo4pena + 0 comments I did about the same but used some methods in the function for easy refactoring just in case the sub-logic ever needed to be used for another purpose or more fruit types needed to be added

function countApplesAndOranges(s, t, a, b, apples, oranges) { const fLoc = function (treeLoc, arr2d) { return arr2d.map(fruitLoc => (treeLoc + fruitLoc)); } const fRange = function (s, t, arr2d) { let a, b; a = 0; b = 0; arr2d.forEach((f, i) => { if (i === 0) { // apple count f.forEach(loc => s <= loc && loc <= t ? a++ : null); } if (i === 1) { // orange count f.forEach(loc => s <= loc && loc <= t ? b++ : null); } }); return [a, b]; } console.log(fRange(s, t, [fLoc(a, apples), fLoc(b, oranges)]) .join('\n')); }

michael_tandio + 0 comments `console.log(apples.filter(apple => a + apple >= s && a + apple <= t).length); console.log(oranges.filter(orange => b + orange >= s && b + orange <= t).length);`

Exactly the same as mine :)

rcgonzalezf + 1 comment You don't even have to store the array, you can do the counting inline while reading the input:

int apples = 0; for(int i=0; i < m; ++i){ long d = in.nextLong(); long p = d+a; if ( p >= s && p <= t ) ++apples; }

piyush14031 + 2 comments I think my solution is similar, but doesn't work for all input cases, any idea why?

//header files bla bla int main() { unsigned int s, t, a, b, m, n; cin>>s>>t; long long int house = (t-s); cin>>a>>b; cin>>m>>n; long long int d; long long int i,j; int count=0, count1=0; for (i=0;i<m;i++) { cin>>d; long long int x=(a+d); if (x>=s&&x<=t) count++; } for(j=0;j<n;j++) { cin>>d; long long int y=(b-d); if (y>=s && y<=t) count1++; } cout<<count<<endl<<count1; return 0; }

hvkushwaha + 0 comments remove unsigned you are just neglecting negative numbers, make it long long instead of unsigned

vbackk + 0 comments Change the sign in **long long int y=(b-d); ** do it + then it will work.

gabrielbb0306 + 0 comments I see everybody posted solutions with 2 for loops. I did mine with just one in Java:

// Complete the countApplesAndOranges function below. static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) { int appleCount = 0; int orangeCount = 0; for(int i = 0; i < Math.max(apples.length, oranges.length); i++) { appleCount += isFruitInRange(apples, i, s, t, a); orangeCount += isFruitInRange(oranges, i, s, t, b); } System.out.println(appleCount); System.out.println(orangeCount); } private static int isFruitInRange(int fruits[], int i, int s, int t, int treePos) { return i < fruits.length && (treePos + fruits[i]) >= s && (treePos + fruits[i]) <= t ? 1 : 0; }

marinskiy + 0 comments Here is

**Python 3**solution from my HackerrankPractice repository:s, t, a, b, m, n = map(int, input().split() + input().split() + input().split()) apple = list(map(int, input().split())) orange = list(map(int, input().split())) print(sum(s <= a + i <= t for i in apple)) print(sum(s <= b + i <= t for i in orange))

Feel free to ask if you have any questions :)

kakyoin01 + 0 comments Slight inconsistency in problem output instructions. The problem description says to output "

*2 space-separated integers*" e.g.:**on a line**: Larryâ€™s score followed by Robâ€™s score1 1

...but expected output for base test case when I tested this with JavaScript (NodeJS) is:

1 1

AjaySenthu13 + 1 comment *** // Swift Way***`print(apples.filter({s...t ~= $0 + a}).count) print(oranges.filter({s...t ~= $0 + b}).count)`

marsi9inin + 0 comments brilliant!!

julianztz + 0 comments I don't understand what is this question trying to test... It is like high school math problem.

Ellijah + 1 comment Was able to run only 3 test cases and could not figure out the defect in the code

void countApplesAndOranges(int s, int t, int a, int b, int apples_count, int* apples, int oranges_count, int* oranges) { int aple=0,orng=0,num; for(num=0;num<apples_count;num++){ if((a+apples[num])>=s) aple++; } for(num=0;num<oranges_count;num++){ if((b+oranges[num])<=t) orng++; } printf("%d\n%d",aple,orng); }

Sort 1010 Discussions, By:

Please Login in order to post a comment