Skip to content

Will there be Enough Space in Java

The challenge

Bob is working as a bus driver. However, he has become extremely popular amongst the city’s residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not having enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.

The task:

You have to write a function that accepts three parameters:

  • cap is the amount of people the bus can hold excluding the driver.
  • on is the number of people on the bus excluding the driver.
  • wait is the number of people waiting to get on to the bus excluding the driver.

If there is enough space, return 0, and if there isn’t, return the number of passengers he can’t take.

Examples:

cap = 10, on = 5, wait = 5 --> # He can fit all 5 passengers cap = 100, on = 60, wait = 50 --> 10 # He can't fit 10 of the 50 waiting
Code language: PHP (php)

The solution in Java code

Option 1:

public class Bob { public static int enough(int cap, int on, int wait){ return Math.max(, on + wait - cap); } }
Code language: Java (java)

Option 2:

public class Bob { public static int enough(int cap, int on, int wait){ return (cap-on-wait>=)? : on+wait-cap; } }
Code language: Java (java)

Option 3:

public class Bob { public static int enough(int cap, int on, int wait){ int pusto = cap-on; if(wait==pusto || wait<pusto) return ; else return wait-pusto; } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testBob() { assertEquals("Should return 0.", , Bob.enough(10, 5, 5)); assertEquals("Should return 10.", 10, Bob.enough(100, 60, 50)); assertEquals("Should return 0.", , Bob.enough(20, 5, 5)); } }
Code language: Java (java)

See also  How to Clone a Graph in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x