I have seen that this question has been asked earlier, this is the link : Apple and Orange HackerRank. I must tell you that my doubt is not like this person, it is just that I've written a code which works fine on for most of the test cases, and fails for some either.
I have checked my code, and I'm fairly confident that my code is something which is working fine.
The question link is : Apple And Orange HackerRank Question
Problem Statement
Given a person house whose house length is between variables s and t, and we have two trees, one is apple other one is orange. Since we have been given some distance of the fallen apple, and oranges respectively, what we have to do is to find those apples, and oranges whose distance falls in between the s and t, or I must say which falls on xyz person's house.
Input Format
The first line contains two space-separated integers denoting the respective values of s and t.
The second line contains two space-separated integers denoting the respective values of a and b.
The third line contains two space-separated integers denoting the respective values of m and n.
The fourth line contains space-separated integers denoting the respective distances that each apple falls from point a.
The fifth line contains space-separated integers denoting the respective distances that each orange falls from point b.
Code
static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
int appleSum=0, orangeSum=0, appleCount=0, orangeCount=0;
for(int i : apples){
appleSum = Math.abs(a+i);
if(appleSum>=s && appleSum<=t)
appleCount++;
}
for(int j : oranges){
orangeSum = Math.abs(b+j);
if(orangeSum>=s && orangeSum<=t)
orangeCount++;
}
System.out.print(appleCount + "\n" + orangeCount);
}
This is my piece of code which works fine on most of the test cases, but this case actually confused to hell. I'm actually writing down the gist of one of the failed test cases, and will give you the link for the same if it works out well for you guys.
Passed Test Case {1}
7 11
5 15
3 2
-2 2 1
5 -6
Passed Test Case {2}
7 10
4 12
3 3
2 3 -4
3 -2 -4
Failed Test Case
37455 87275
35609 89610
73201 77971
19736 19374 -68796 0 -68800 -80005 -88383 -8147 73241 -33256 20227 0
41620 30182 -95883 -88718 93989 44405 66495 87717 100000 -99845 -63634
98450 -63318 23501 -39150 22335 4955 -98587 -13608 -95388 -41752 4959
22375 -20025 -72101 -90667 -41569 94758 -26725 -53444 -8783 -81879
57041 23682 -60064 -23505 2850 96653 18487 -6644 -90710 71994 21513
36066 -65894 -9897 -86990 -97347 89784 88447 93133 12662 61685 -22914
-39075 -96807 -80465 -53820 36851 -51794 -11967 36658 -75592 22004 -961
66645 -93123 -65326 81871 -21785 -48242 -63552 32509 51078 -37656
-14966 4017 -58411 9346 13544 -63028 -93738 93924 68463 55032 -10046
87907 -20967 78972 85338 19584 45460 84382 -34690 -82301 14093 -60802
4170 -90955 92241 -34932 68913 -22262 49469 -45729 7942 65753 17354
-28647 93058 -43811 21411 8543 -44799 -71815 -40743 60445 -66946 -85090
-96873 97385 -15317 54454 -21021 -60256 -41301 -98896 -97184 63098
-60230 41376 42273 45807 58041 54260 21196 -85191 85267 -28305 30220
-76826 82999 72627 7{-truncated-}
Expected Output
89610
19582
There are more to this and the link is here : Test Case Inputs
PLEASE NOTE : I have not asked for the solution actually, my code works but I don't know why this logic fails for the inputs like this.
Any help would be appreciated! Thanks :)
EDITS
I have tried using the long in place of int, in case for the larger value like the one which is there in the failed test case, but again it got failed!
long appleSum=0, orangeSum=0, appleCount=0, orangeCount=0;
This code passed all test cases, what went wrong for you is you are using Math.abs(),you shouldn't do that because there can be negative values of sum as well.
static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
int appleCount = 0;
int orangeCount = 0;
for(int i:apples){
if(s<=i+a && i+a<=t)
appleCount++;
}
for (int j : oranges) {
if (s <= j + b && j+b <= t)
orangeCount++;
}
System.out.println(appleCount);
System.out.println(orangeCount);
}
JavaScript code for countAppleAndOranges function of hacker rank
let applesCount=0, orangesCount=0;
for(let x=0; x<apples.length; x++){
apples[x]=apples[x]+a;
if((apples[x]>=s)&&(apples[x]<=t)){
applesCount++
}
}
for(let x=0; x<oranges.length; x++){
oranges[x]=oranges[x]+b;
if((oranges[x]>=s)&&(oranges[x]<=t)){
orangesCount++;
}
}
console.log(applesCount);
console.log(orangesCount);
The question is too old, but still there may be people who might need this.
abs() is the mistake you made.
See the code
void countApplesAndOranges(int s, int t, int a, int b, vector<int> apples, vector<int> oranges) {
int size_a=apples.size();
int size_o=oranges.size();
int count_a=0,count_o=0;
for(int i=0;i<size_a;i++)
{
if(apples[i]+a>=s&&apples[i]+a<=t)
{
count_a++;
}
}
for(int j=0;j<size_o;j++)
{
if(oranges[j]+b<=t&&oranges[j]+b>=s)
{
count_o++;
}
}
cout<<count_a<<'\n'<<count_o;
}
Related
I have been working on this question, and after submitting my code 7 cases passed, however, 9 cases failed. The question link is here of HackerRank : Electronic Shop
Problem Statement
A girl wants to buy a keyboard, and a USB drive, she want to spend as much as possible but within budget (combining both the items). And if the price of both the items exceeds her budget, return -1 or she can't buy. What is mandatory is that She wants to buy both the items, not a single one.
Example
A range of keyboards is given in the form of an array [40, 50, 60], and USB drives is given as [5,8,12]. Her max budget is 60. Now if we sum up both the things we get two max value of combination :
40 + 12 = 52
50 + 8 = 58
Since 58 one is greater, hence she will get the items worth of 50 and 8.
Input format
The first line contains three space-separated integers b, n, and m, her budget, the number of keyboard models and the number of USB drive models.
The second line contains space-separated integers , the prices of each keyboard model.
The third line contains space-separated integers , the prices of the USB drives.
Output Format
Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
My Algo
1. Take answer variable as 0, and max value initialize it with first element of keyboard + first element of usb drives
2. loop through keyboard, make an inner loop for usb
3. Compare keyboard[i] + drives[j], if greater than b, then return -1.
4. Else find the max value and assign it to answer
5. return answer
My logic is as simple as the requirements, but somehow fails for the cases which has a very large number of elements in the array.
Code
static int getMoneySpent(int[] keyboards, int[] drives, int b) {
int answer = 0, maxAmount = keyboards[0] + drives[0];
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
// Ofcourse if all i+j values will be greater than the max budget then -1
if((i+j) > b)
answer = -1;
else if((i+j) == b){
answer = i+j;
}else{
/*If the value is smaller than the max budget, the finding the max value we get after adding them and comparing with the maxAmount variable */
if((i+j) > maxAmount){
maxAmount = i+j;
answer = maxAmount;
}
}
}
}
return answer;
}
I'm having two cases which failed,, here they are :
Failed Test Case 1
Input =>
539855 818 628
380710 674456 878173 532602 868253 721585 806107 141310 790209 212031
304748 818920 80938 322601 403071 22899 173564 153826 695108 223665
346178 957539 975830 573171 641117 932941 822666 575293 132555 479463
862209 313799 922966 606508 487172 139230 606390 898464 764983 829520
174879 317603 502680 953013 398753 825387 146407 666457 367618 121790
68188 478342 25818 506222 135197 232604 963333 79984 549654 776899
966040 122063 432596 594425 311887 936661 506256 876303 439611 277816
105689 851641 640971 333 216087 17692 619728 602689 650348 364881
152060 386548 61364 564569 780938 191826 459905 211804 58177 484711
995091 754424 57794 619638 695192 297423 983901 430435 239234 170704
142282 74647 121413 782873 303344 265448 101069 177807 692318 691774
62306 618191 509537 633333 996922 228947 814154 232698 615359 220853
306323 173792 624037 655872 527161 848207 426180 724481 130740 792273
886804 404890 449886 654224 194667 354317 367843 525624 414224 481744
827725 176927 733780 387166 769479 964040 1{-truncated-}
Expected Output
539854
For full input data here is the link : Input Array Data Full
Failed Test Case 2
Input =>
374625 797 951
183477 732159 779867 598794 596985 156054 445934 156030 99998 58097
459353 866372 333784 601251 142899 708233 651036 20590 56425 970129
722162 832631 938765 212387 779 181866 992436 183446 617621 304311
611791 524875 7068 432043 23068 291295 524893 611991 399952 139526
46677 292211 973975 366445 232824 456173 90627 785353 618526 199719
382549 514351 983453 592549 466869 46461 860135 607682 680461 170563
450601 65067 13268 949100 942415 965850 563416 808580 385504 304683
15970 97695 230946 684388 241080 440252 683418 122066 610135 495289
833383 34397 173404 909526 391149 258839 182278 662672 755532 311782
425252 520186 207989 546834 567829 184897 31321 969804 842475 775308
449856 939711 395240 895029 926868 598035 727436 922082 326615 88513
570573 196028 520952 45238 961389 325404 844725 388765 747489 271411
539814 828925 586884 356834 965473 280998 607171 542819 276062 140956
296341 802378 165305 74568 15640 987110 423497 772419 394971 198761
293555 5524 14083 815646 198888 707017 711503 729172{-truncated-}
Expected Output
374625
For full input array data for this one follow this link : Failed Test Case 2 Full Input
I'm there almost but somehow I'm confused why my code is not working for long input array elements. Any help would be appreciated, as it will make me learn new thing in my future endeavor.
You misunderstood the question. Answer should be -1 if you can't buy any keyborad+usb. Not if there is one set unaffordable, but if they all are. With your current code, what would it return if the very last set is unaffordable?
Here is a code that should work. And comments to explain:
int answer = -1; // that's the default answer.
int maxAmount = 0; // what if first keyboard + first usb are unaffordable? let's put it to 0
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
if((i+j) > b) {
// do nothing, it's unaffordable (and remove this block)
}else if((i+j) == b){
answer = i+j;
return answer;// it can't be more, stop the loop and return the solution
} else if((i+j) > maxAmount){ // no need to put an else, then an if both conditions are related
maxAmount = i+j;
answer = maxAmount;
}
}
}
Of course, if you remove the first empty ifblock from the above code, you will have to change the last condition in order to check if it's below the max allowed:
if((i+j)>maxAmount && (i+j)<=b)
int getMoneySpent(int keyboards_count, int* keyboards, int drives_count, int* drives, int b) {
int price=-1;
for(int i=0;i<drives_count;i++)
{
for(int j=0;j<keyboards_count;j++)
{
if((drives[i]+keyboards[j]>price) && (drives[i]+keyboards[j]<=b))
{
price=drives[i]+keyboards[j];
}
}
}
return price;
}
Javascript Solution:
function getMoneySpent(keyboards, drives, b) {
const combos = [];
let maxCost = 0
keyboards.forEach(keyboard => {
drives.forEach(drive => {
let currentComboCost = keyboard+drive;
maxCost = ((currentComboCost <= b) && (currentComboCost > maxCost)) ? currentComboCost : maxCost;
})
})
return maxCost || -1;
}
I've got a student studying for the AP CS test (he takes it next week). I was hired mid/end year to basically be a long term sub for the rest of the school year for these IT classes. I don't know enough about java or programming to explain to him why the answer to this practice test problem is B and not A (according to the answer sheet).
I'm hoping this might be a decent place to get an explanation I can take to him...
/** Precondition: arr contains only positive values.
*/
public static void doSome(int[]arr, int lim)
{
int v = 0;
int k = 0;
while (k < arr.length && arr[k] < lim)
{
if (arr[k] > v)
{
v = arr[k]; /* Statement S */
}
k++; /* Statement T */
}
}
Assume that doSome is called and executes without error. Which of the following are possible combinations for the value of lim, the number of times Statement S is executed, and the number of times Statement T is executed?
possible combinations for the value of lim
(A) I only
(B) II only
(C) III only
(D) I and III only
(E) II and III only
III is not a valid combination because you can't execute S more times than you execute T.
From a test-taking perspective: In this problem, this is the most important insight because figuring this out immediately knocks out 3 options and takes you down to a 50/50 shot on a guess.
I is not a valid combination because the array contains only positive values, all of which are > 0, so the conditional if(arr[k]>v) must return true at least once, meaning that S is executed at least once if the while loop body gets executed at least once. In option I, statement T (also in the body of the while loop) is executed 5 times, so S must be executed at least once.
II is a valid combination of values.
From a test-taking perspective: It's not worth taking the time to prove this (e.g. by providing sample inputs that produce this combination), as process of elimination has already taken you down to one answer.
Therefore, option B, II only, is the correct answer.
Props to the AP test question writer.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
Ok so this is my homework assignment, and I am having a heck of a time figuring out how to correctly use overloading to allow for a certain number of terms to print out.
"Create a class that contains a method that accepts an integer from the user to display the next 5 terms in the following pattern: (n-7) * 3.
So, if the user enters 5, the output should be:
-6
-39
-138
-435
-1326
Add an overloaded method so the user can enter how many termss they want to print out in a pattern:
So, the user would enter 5 as the starting number and 3 as the number of terms to print out in the pattern.
The output would be:
-6
-39
-435
Add different method that displays the formula and provides calculation to the formula: (should get starting number from user input) and prints out the next 5 terms.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
Add an overloaded method that displays the formula and the calculation to the formula and takes in how many times it should print: (should get from user input).
For example: User enters 5 as the starting number and print out 4 times.
(5-7) * 3 = -6
(-6-7) * 3= -39
(-39-7) * 3 = -435
(-435-7) * 3 = -1326
Specifics:
You have a separate class that contains all your methods.
You should have 4 methods in this class.
Your main should call these four methods getting user input where appropriate.
"
I'm not asking for anyone to do this for me, I just would appreciate a steer in the right direction.
At the moment trying to collect the number of terms wanted by the user in the main class then pass it to the Numberpattern class and then from their have the program determine which Calc method to use is not working.
Okay i feel dirty for doing your homework for you but i'll get you started
the first method is
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < 5; i ++){
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
The first overload is
public void printPattern(int n, int c){ //this is the overload
public void printPattern(int n){
int prevAnswer = n;
for(int i =0; i < c; i ++){ // i < c to print that many numbers in the sequence
int newAnswer = (prevAnswer - 7) * 3;
System.out.println(newAnswer);
prevAnswer = newAnswer;
}
}
To Overload a method simply provide different parameters and write the extended new functionality
By overloading a method, you are using the same methods with different parameter lists. This allows the program to decide which method is best to be used with only one call of that method name.
It looks like your first method would have a loop of a fixed number and only one parameter (n). Your second method will have the same name, but now allow for two parameters - the (n) and the number of times to loop.
public static void nextTerms (int n) {
Your fixed count loop and print out of n code...
}
public static void nextTerms (int n, int loopCount) {
Your changeable loopCount count loop and print out of n code...
}
To run that nextTerms method, your main Class could either call:
nextTerms(5);
or
nextTerms(5, 3);
The program will then decide which of the two nextTerms methods are appropriate.
For more information, I suggest - http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Cheers!
Chris
I'm training code problems like UvA and I have this one in which I have to, given a set of n exams and k students enrolled in the exams, find whether it is possible to schedule all exams in two time slots.
Input
Several test cases. Each one starts with a line containing 1 < n < 200 of different examinations to be scheduled.
The 2nd line has the number of cases k in which there exist at least 1 student enrolled in 2 examinations. Then, k lines will follow, each containing 2 numbers that specify the pair of examinations for each case above.
(An input with n = 0 will means end of the input and is not to be processed).
Output:
You have to decide whether the examination plan is possible or not for 2 time slots.
Example:
Input:
3
3
0 1
1 2
2 0
9
8
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0
Ouput:
NOT POSSIBLE.
POSSIBLE.
I think the general approach is graph colouring, but I'm really a newb and I may confess that I had some trouble understanding the problem.
Anyway, I'm trying to do it and then submit it.
Could someone please help me doing some code for this problem?
I will have to handle and understand this algo now in order to use it later, over and over.
I prefer C or C++, but if you want, Java is fine to me ;)
Thanks in advance
You are correct that this is a graph coloring problem. Specifically, you need to determine if the graph is 2-colorable. This is trivial: do a DFS on the graph, coloring alternating black and white nodes. If you find a conflict, then the graph is not 2-colorable, and the scheduling is impossible.
possible = true
for all vertex V
color[V] = UNKNOWN
for all vertex V
if color[V] == UNKNOWN
colorify(V, BLACK, WHITE)
procedure colorify(V, C1, C2)
color[V] = C1
for all edge (V, V2)
if color[V2] == C1
possible = false
if color[V2] == UNKNOWN
colorify(V2, C2, C1)
This runs in O(|V| + |E|) with adjacency list.
in practice the question is if you can partition the n examinations into two subsets A and B (two timeslots) such that for every pair in the list of k examination pairs, either a belongs to A and b belongs to B, or a belongs to B and b belongs to A.
You are right that it is a 2-coloring problem; it's a graph with n vertices and there's an undirected arc between vertices a and b iff the pair or appears in the list. Then the question is about the graph's 2-colorability, the two colors denoting the partition to timeslots A and B.
A 2-colorable graph is a "bipartite graph". You can test for bipartiteness easily, see http://en.wikipedia.org/wiki/Bipartite_graph.
I've translated the polygenelubricant's pseudocode to JAVA code, in order to provide a solution for my problem. We have a submission platform (like uva/ACM contests), so I know it passed even in the problem with more and hardest cases.
Here it is:
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
/**
*
* #author newba
*/
public class GraphProblem {
class Edge {
int v1;
int v2;
public Edge(int v1, int v2) {
this.v1 = v1;
this.v2 = v2;
}
}
public GraphProblem () {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
int num_exams = cin.nextInt();
if (num_exams == 0)
break;
int k = cin.nextInt();
Hashtable<Integer,String> exams = new Hashtable<Integer, String>();
ArrayList<Edge> edges = new ArrayList<Edge>();
for (int i = 0; i < k; i++) {
int v1 = cin.nextInt();
int v2 = cin.nextInt();
exams.put(v1,"UNKNOWN");
exams.put(v2,"UNKNOWN");
//add the edge from A->B and B->A
edges.add(new Edge(v1, v2));
edges.add(new Edge(v2, v1));
}
boolean possible = true;
for (Integer key: exams.keySet()){
if (exams.get(key).equals("UNKNOWN")){
if (!colorify(edges, exams,key, "BLACK", "WHITE")){
possible = false;
break;
}
}
}
if (possible)
System.out.println("POSSIBLE.");
else
System.out.println("NOT POSSIBLE.");
}
}
public boolean colorify (ArrayList<Edge> edges,Hashtable<Integer,String> verticesHash,Integer node, String color1, String color2){
verticesHash.put(node,color1);
for (Edge edge : edges){
if (edge.v1 == (int) node) {
if (verticesHash.get(edge.v2).equals(color1)){
return false;
}
if (verticesHash.get(edge.v2).equals("UNKNOWN")){
colorify(edges, verticesHash, edge.v2, color2, color1);
}
}
}
return true;
}
public static void main(String[] args) {
new GraphProblem();
}
}
I didn't optimized yet, I don't have the time right new, but if you want, you/we can discuss it here.
Hope you enjoy it! ;)