Basic Java: Finding the Greatest Common Factor - java

I need to create a program that finds the greatest common factor of two user entered numbers using this formula:
gcd(x, y) = gcd(x – y, y) if x >= y and gcd(x, y) = gcd(x,y-x) if x < y.
For example:
gcd(72, 54) = gcd(72 – 54, 54) = gcd(18, 54)Since 72 > 54, we replace 72 with 72 – 54 = 18 and continue the loop with the new values
Iteration 2: gcd(18, 54) = gcd(18, 54 – 18) = gcd(18, 36)
Since 18 < 54, we replace 54 with 54 – 18 = 36 and continue the loop with the new values
Iteration 3: gcd(18, 36) = gcd(18, 36 – 18) = gcd(18, 18)
Since 18 < 36, we replace 36 with 36 – 18 = 18 and continue the loop with the new values
Iteration 4: gcd(18, 18) = gcd(18 – 18, 18) = gcd(0, 18) = 18
Since 18 >= 18, we replace the first 18 with 18 – 18 = 0
Since one of the values is 0 we do not continue the loop
The nonzero value, 18, is the gcd.
Here's of the code I have so far:
I'm getting the error "Illegal start of expression."

First of all in your logic here:
do {
int gcd1 = (num1-num2);
System.out.println(gcd1 + "," + num2);
}
while (num1 != 0 && num2 != 0);
return
}
You are just printing out gcd1 and num2 without updating num1 and num2.
Also think how you can use recursion to tackle this problem.
If you insist on using a loop, here's the while loop logic:
public static int greatestCommon(int a, int b)
{
while (a != 0 && b != 0)
{
if (a >= b)
{
a = a - b;
}
else
b = b - a;
}
if (a == 0) return b;
else return a;
}
note that you do not need to use a do-while loop since there are situations when you do not need the substraction (if one or both of them are 0).

Use
Math.Max(num1, num2) - Math.Min(num1,num2)
instead of num1-num2

You've already stated the answer (the algorithm) in your first sentence:
gcd(x, y) = gcd(x – y, y) if x >= y and gcd(x, y) = gcd(x,y-x) if x < y.
So how to translate that into code? The left-hand side of the equation is your method prototype, and the right-hand side is your method body:
public static int gcd(x, y) // doesn't HAVE to be public or static
{
gcd(x – y, y) if x >= y and gcd(x, y) = gcd(x,y-x) if x < y
}
but that code in the body doesn't compile, so you need to rewrite the body. Note that "and gcd(x, y) = ..." is a repetition of the method prototype and thus removed:
public static int gcd(x, y)
{
if (x >= y)
{
return ... // you fill this in
}
else if (x < y)
{
return ... // you fill this in
}
}
Note that the final "else-if" check really isn't necessary, but you teacher likely wants to see it there.
EDIT:
Since this likely a classroom exercise in recursion, consider this working example taken from javax.swing.table.DefaultTableModel:
private static int gcd(int i, int j)
{
return (j == 0) ? i : gcd(j, i%j);
}
SIDENOTE: Don't turn this in, as it obviously is not derived from the algorithm given to you, and your teacher will likely mark it wrong.
Since you may not have learned the ternary operator syntax, I'll rewrite it as:
private static int gcd(int i, int j)
{
if (j == 0)
return i;
else
return gcd(j, i%j);
}
This is an example of recursion, where under certain circumstances we can return a known value, but otherwise the method has to call itself again with a different set of parameters.
EDIT 2:
Since an interative approach is needed in lieu of a recursive one, remember that all recursive methods can be rewritten using iteration (i.e., via loops).
Further reading:
Refactoring: Replace Recursion With Iteration

Related

ArrayIndexOutOfBoundsException - Scoreboard with images

I am trying to make a scoreboard with images in processing, with images from 0 to 9, but any number greater than 9 does not make changes
It should be something like this: 10, 11, 12, ..., 99
but it only changes the number on the left, try using a counter, converting it to a String and then to a Char[] to get the first digit of two numbers; for example: 25, it would have to be 2
when passing that number to the array, it sends "ArrayIndexOutOfBoundsException"
char[] digits;
PImage [] prueba = new PImage[10];
int contadorPrueba2 = 0;
int aa = 0;
void setup () {
size (781, 470);
tablero = loadImage("tablero.png");
flechaRight = loadImage("flechaRight.png");
flechaLeft = loadImage("flechaLeft.png");
for (int i = 0; i < prueba.length; i++) {
prueba[i] = loadImage("numero_" + i + ".jpg");
}
}
void draw () {
//flechas
image(flechaRight, x, y);
image(flechaLeft, x2, y);
image(prueba[0], x3, 50);
//cambiar de numeros
image(prueba[contadorPrueba2], x4, 50);
image(prueba[aa], x3, 50);
}
boolean isMouseOver (int x, int y, int w, int h) {
if (mouseX>x && mouseX <x+w && mouseY>y && mouseY <y+h) {
return true;
}
return false;
}
void mousePressed () {
if (isMouseOver (x, y, w, h) == true) {
contadorPrueba2++;
//image(uno, x3, 50);
} else if (isMouseOver (x2, y, w, h) == true) {
contadorPrueba2--;
}
if (contadorPrueba2 >= prueba.length)
contadorPrueba2 = 0;
count = String.valueOf(contadorPrueba2);
digits = count.toCharArray();
for (int i = 0; i < digits.length; i++) {
if (contadorPrueba2 >= 10) {
//aa = digits[0];
println(digits[i]);
aa = digits[i];
//aa = digits[i];
//print("pp" + aa);
if (i == 0) {
print("ksk" + digits[i]);
}
}
}
}
Chars aren't exactly the best way to keep track of a score, which can make for some headache at times. I strongly suggest that you keep track of the score with an integer number unless you really have no choice on the matter.
Now, to translate an integer into a bunch of index numbers associated with images of said numbers, things can also become complicated, but I got your back! In fact, you can use MATH and solve this quite easily. Are you familiar with the modulo operator? If you're not, read about it because it's a programmer's best friend. Long story short, it's a division that returns only the leftover numbers after the division. As an example, if I write:
10 / 3 == 3.333333 // as a division this makes sense
10 % 3 == 1 // modulo only keeps what's left when the division stops being an integer
because: 10 == [3+3+3] + 1
Ok, you probably already knew this, but if you didn't, now you do. Here's how I use this knowledge to simplify your issue with a commented example:
PImage[] digits = new PImage[10];
int score = 4780; // you can change this number for whatever integer number
void setup () {
size(200, 200);
for (int i = 0; i < digits.length; i++) {
digits[i] = loadImage(i + ".png"); // these 10 images are 10x10 pixels for easier handling
}
}
void draw () {
int i=1;
int j = 160; // arbitrary number: this is where i start drawing the score (the rightest number)
// oooh! This is a good opportunity to use a do...while(); loop! I don't have that many of those.
// This is because we have to show at least ONE digit even if the score is zero, but I coded this so you can have a score higher than 99 without issue
do {
i*=10; // using multiples of 10 with the modulo operator
// as we use base 10 in real life, multiples of 10 help isolate digits of interests
image(digits[(score%i)/(i/10)], j, 90); // j is the x coordinate of the current digit, 90 is an arbitrary y coordinate
// 'digits[(score%i)/(i/10)]' deserves an explanation:
// 'score%i' removes every unit besides the current digit of interests, as an example if we're looking for the hundreds digit of 3456 it'll be 400
// '/(i/10)' removes the unwanted zero (in the 3456 example it would leave only the number 4 instead of 400)
j-=10; // updating j for the next digit
} while(i<score);
}
I know I didn't tell you why you get ArrayIndexOutOfBoundsException and it's kinda on purpose: this is a very common error and although I have no trouble guessing why you get it, it's just more efficient to fix by improving the method than by meddling with the code. There are many articles on SO about why this error happens and I encourage you to read at least one, as it'll be something that you'll see again in the future. Yet, for now, you can just avoid it by switching to this method.
I hope this helps. Have fun!

How Do I Optimize This Algorithm To Handle Large Integers?

I have two integers x and y.
Rule:
If x > y : x = x - y and y = 2 * y;
If y > x : y = y - x and x = 2 * x;
If y == x : not infinite loop
The question is, will the two integers be an infinite loop or not?
Here is my code:
private static boolean IsPairLoop(int first, int second)
{
boolean loop = false;
HashMap<Integer, Integer> round_record = new HashMap<>();
int[] first_round = new int[]{first, second};
while ((first_round[0] != -1 && first_round[1] != -1))
{
if (round_record.containsKey(first_round[0]))
{
loop = true;
break;
}
round_record.put(first_round[0], first_round[1]);
PlayRound(first_round);
}
return loop;
}
private static void PlayRound(int[] round)
{
if (round[0] > round[1])
{
round[0] -= round[1];
round[1] += round[1];
}
else if (round[0] < round[1])
{
round[1] -= round[0];
round[0] += round[0];
}
else
{
round[0] = -1;
round[1] = -1;
}
}
This works fine for small integers. However, this is painfully slow when the integer difference is really large. Integer range is 1 to 2^30 for both x and y. What can I do to make this fast even when the integers difference is large?
In this problem, the sum x + y is invariant, and if it is odd, x == y is impossible.
Then if x and y have the same parity, after one iteration they become both even and remain so, and the problem is unchanged if you divide both by 2.
Hence the "instantaneous" solution:
while (x + y) & 1 == 0:
if x == y:
print "Not infinite"
break
if x > y:
x= (x - y) / 2
else:
y= (y - x) / 2
else:
print "Infinite"
As one of the arguments loses at least one bit on every iteration, there are never more than 64 iterations for 32 bits integers (and in practice much less, most of the time 0 !).
A variant is possible and can make sense for bignumbers:
if x == y, conclude finite.
if x and y have a different number of trailing zeroes, conclude infinite.
otherwise, discard the trailing zeroes and perform the reduction according to x > y or y > x and loop.
Instead of using a hashmap, use Floyd's cycle detection algorithm. Not only will this avoid large memory use, it will also avoid costly boxing and unboxing between int and Integer.
A second optimisation is to re-write the recurrence relations via a change of variables:
s = x+y
t = x-y
Then the recurrence relations become:
if t=0, stop
if t>0, s'=s, t'=2t-s
if t<0, s'=s, t'=2t+s
Note in this formulation, only the t variable changes.
The code (untested) will look something like this:
private static int step(int s, int t) {
if (t>0) return 2*t - s;
if (t<0) return 2*t + s;
return 0;
}
private static boolean IsPairLoop(int first, int second) {
int s = first+second;
int t_slow = first-second;
int t_fast = t_slow;
while(t_slow != t_fast) {
t_slow = step(s, t_slow);
t_fast = step(s, step(s, s_fast));
}
return t_slow != 0;
}
You may need to replace int with long if first+second can overflow.
I think, given the preconditions, you never get a t that goes off to infinity (since it's always true that |t| < s). But you may wish to double-check, perhaps adding some sort of assertion into your code.
Let’s work backwards a bit. What can produce x == y? The difference between the previous x and y has to be equal to twice the smaller of the two, i.e. the larger has to be three times the smaller. Things that don’t loop infinitely so far:
{n, n}
{n, 3n}
Where can {n, 3n} come from? Either
n is a difference a − b for some a > b, and 3n = 2b
3(a − b) = 2b
3a − 3b = 2b
3a = 5b
a = 5/3 b
A pair {m, 5/3 m} is something that produces {n, 3n} on the next step. (m has to be divisible by 3, but that’s okay.)
3n is a difference a − b for some a > b, and n = 2b
(a − b)/3 = 2b
a − b = 6b
a = 7b
A pair {m, 7m} is the only other thing that can produce {n, 3n} on the next step.
An updated list:
{n, n}
{n, 3n}
{n, 7n}
{n, 5/3 n}
Seems like a good time to generalize those last steps.
{n, qn} happens when:
n is a difference a − b for some a > b, and qn = 2b
q(a − b) = 2b
qa − qb = 2b
qa = (2 + q)b
a = (2 + q)/q b
or qn is a difference a − b for some a > b, and n = 2b
(a − b)/q = 2b
a − b = 2qb
a = (2q + 1)b
So if q = m/n is in the list, these are also in the list:
(2n + m)/m
(2m + n)/n
q = 1 generates:
(2 + 1)/1 = 3
2×1 + 1 = 3
q = 3 generates:
3
(2 + 3)/3 = 5/3
2×3 + 1 = 7
q = 5/3 generates:
3
5/3
7
(2 + 5/3)/(5/3) = (6 + 5)/5 = 11/5
(2×5/3) + 1 = 10/3 + 1 = 13/3
q = 7 generates:
3
5/3
7
11/5
13/3
(2 + 7)/7 = 9/7
2×7 + 1 = 15
Hmm… that’s pretty interesting. Let’s sort the list by the numerator:
3/1
5/3
7/1
9/7
11/5
13/3
15/1
Based on that pattern, I’d expect 17/15 to come next. Generating a list sorted by denominator with a computer:
3/1
7/1
15/1
31/1
63/1
5/3
13/3
29/3
61/3
11/5
27/5
59/5
9/7
25/7
57/7
23/9
55/9
21/11
53/11
19/13
51/13
17/15
49/15
47/17
45/19
43/21
41/23
39/25
37/27
35/29
33/31
Looks an awful lot like m/n where n is odd, m > n, and m + n is a power of two. So one way to optimize your algorithm would be:
private static boolean isPairLoop(int first, int second)
{
if (first == second) return false;
if (first > second) return isPairLoop(second, first);
if (first == 0) return true;
int d = gcd(first, second);
return Integer.bitCount(first / d + second / d) != 1;
}
private static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
Takes quadratic time on the number of digits on bigints.
Now you just have to prove that it works. I hope it works.

How to write a LessThan method without using the operator

How would you recursively write a method that checks if a number is less than the other without using the '<' operator?
You can only use the plus, minus, times, and equals operators.
It must be recursive
x and y will always be 0 or greater
Should return boolean
If needed, you can make other methods but they must follow rules above.
Cove I've got so far:
public static boolean isLessThan(int x, int y) {
if(x == y - 1) return true;
if(x == y + 1) return false;
if(x == y) return false;
return isLessThan((x), (y-1)) || isLessThan((x-1), y);
}
Because you have made a good-faith attempt by writing your own code, and because I see this is a kind of puzzle, I'm offering you below code which has only a single recursive call rather than having two recursive calls like in your code.
I think this is as simple as it gets while satisfying the constraints.
What it does: it counts down both numbers to zero, and checks which one reaches zero first. If both reach zero at the same time, the result should be false, but simply checking whether y is zero already includes that check.
public static boolean isLessThan(int x, int y) {
if (y == 0) {
return false;
}
if (x == 0) {
return true;
}
return isLessThan(x - 1, y - 1);
}
#Andreas' answer is more efficient than the above. My aim initially was for a short, clean answer.
I've tried to create a shorter bitshift approach.
Although harder to grasp than the counting example, it has a better complexity and it has an equal amount of lines as the above code (I'm not counting that constant as I could include it inside the code at the expense of readability).
Note that this code shifts left rather than right and - it checks the most significant bit first.
public static final int HIGH_BIT = 1 << 31;
public static boolean isLessThan(int x, int y) {
if (x == y) {
return false;
}
if ((x & HIGH_BIT) != (y & HIGH_BIT)) {
return (y & HIGH_BIT) == HIGH_BIT;
}
return isLessThan(x << 1, y << 1);
}
Note: if != is disallowed, you can change the second if statement to:
if (((x ^ y) & HIGH_BIT) == HIGH_BIT)
Also note that the complexity is really O(1) as, although the algorithm is theoretically O(log n), Java ints are 32 bits so the upper bounds is O(32) which is the same as O(1).
You could do it like the answer to this question:
Bitwise operations equivalent of greater than operator
However that doesn't honor rule 2: It must be recursive.
According to comment, rule 1 should be:
You can only use plus, minus, multiply, equals, and bitwise operators.
With the use of the right-shift operator, we can get a solution in O(log n) time, unlike answer by Erwin Bolwidt, which is O(n) time, and likely to cause StackOverflowError.
public static boolean isLessThan(int x, int y) {
return compare(x, y) == -1;
}
private static int compare(int x, int y) {
if (x == y)
return 0; // x == y
if (x == 0)
return -1; // x < y
if (y == 0)
return 1; // x > y
// Compare higher bits. If different, then that is result
int cmp = compare(x >> 1, y >> 1);
if (cmp != 0)
return cmp;
// Only bit 0 differs, so two choices:
// x0 == 1 && y0 == 0 -> return 1
// x0 == 0 && y0 == 1 -> return -1
return (x & 1) - (y & 1);
}
If != is not allowed, code can be changed to:
// same code up to and including recursive call
if (cmp == 0)
return (x & 1) - (y & 1);
return cmp;

Optimisation advice (HashMap)

I have a big list of coordinates (this form):
if(x == 1055 && y == 63 && z == 1117)
return blackwood;
if(x == 1053 && y == 63 && z == 1117)
return blackwood;
if(x == 1049 && y == 64 && z == 1113)
return blackwood;
if(x == 1054 && y == 63 && z == 1112)
return blackwood;
if(x == 1058 && y == 63 && z == 1112)
return blackwood;
if(x == 1062 && y == 64 && z == 1117)
return blackwood;
if(x == 1050 && y == 64 && z == 1117)
return blackwood;
if(x == 1062 && y == 64 && z == 1118)
return glass;
if(x == 1050 && y == 64 && z == 1118)
return andesite;
(Much longer than that)
But, when I call the method that execute these instructions, I have a lag (Not very long, but enough to have a freeze impression in-game).
So, my question is, how can I optimize this?
I was thinking about stocking these in a HashMap and use HashMap.get(key), but, does HashMap.get(key) iterate the list to find it out?
You could indeed use a Map with as key a custom class that uses as component value these 3 data : x, y and z.
With a fair implementation of the hashCode() method, it should be a constant time [O(1)] or very close to.
If you have to recreate the map as often as you need to request it, using a map could be helpless as from one side you could loose what you gain from another side.
So, create this custom class and override hashCode() and equals() by taking these 3 fields into consideration :
public class Coordinate {
private int x;
private int y;
private int z;
public Coordinate(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Coordinate))
return false;
Coordinate other = (Coordinate) obj;
if (x == other.x && y == other.y && z == other.z)
return true;
return false;
}
}
Then you could initialize the map with expected key-values :
Map<Coordinate, MyValue> mapValuesByCoord = new HashMap<>();
mapValuesByCoord.put(new Coordinate(1055,63,1117), blackwood);
mapValuesByCoord.put(new Coordinate(1053,63,1117), blackwood);
mapValuesByCoord.put(new Coordinate(1062, 64, 1118), glass);
...
And use the map in this way :
MyValue value = mapValuesByCoord.get(new Coordinate(1055,63,1117));
There's an issue here with the common use of the word "map", as in a piece of paper showing a miniature representation of a piece of land, versus the programmer or mathematician's use of "map", in which values are associated with other values.
If pretty much every 3D coordinate has a corresponding return value, you would be better off having a direct lookup table. You could do this with a 3D array, i.e. an array-of-arrays-of-arrays:
Rock[][][] rockMap = ... // Google for guidance on initialising a 3D array
...
rockMap[1054][63][1112] = blackwood;
// etc.
Here "rockMap" is closer to the common use of the word "map". If you drew that 3D array, it would be your "world map".
Then your lookup is:
return rockMap[x][y][z];
Alternatively you could use a 1D array and calculate an index from x, y, z:
Rock[] rockMap = new Rock[SIZE_X * SIZE_Y * SIZE_Z];
rockMap[1054 * SIZE_Y * SIZE_Z + 63 * SIZE_Z + 1112] = blackwood;
Lookup is similar to assignment:
return rockMap[x * SIZE_Y * SIZE_Z + y * SIZE_Z + z];
If you don't have a rock for every coordinate, this approach would still work (you'd just have a null, or some other absence marker, in all the empty slots). But it would be a bit wasteful of space.
In this case it could be more efficient to create a Coordinate type, and construct a Map<Coordinate>.
Map<Coordinate> rockMap = ...;
rockMap.put(new Coordinate(x,y,z), blackwood);
...
return rockMap.get(new Coordinate(x,y,z));
You should do your own tests to find out what type of Map works best in your program -- HashMap? TreeMap? Test them.
For these to work, Coordinate needs to implement certain methods -- check the Javadoc and make sure it does.
HashMap rarely iterates to get an element from its structure. Proper implementations iterate so rarely that people usually don't bother mentioning that part exists. Hence the O(1) complexity.
Imagine a table of your elements (every element has a key). Ideally HashMap will put every one of your elements in a unique row (so only 1 element per row). When given a key to get an element, HashMap will calculate a hash (int) of the key and find out in which row is its appropriate value located. Multiple elements in one row can occur because sometimes two different keys can have same hashes and then you iterate that row to find your element.
I think you could use a HashMap on your problem to speed it up a bit (where x, y and z should be unique keys).
I would create blackwood, glass and andesite object that have check(x, y, z) method.
Edit:
Maybe I should have also added that to make it more efficient you can implement blackwood.check(x, y, z) like this:
public boolean check(int x, int y, int z){
if ( y == 63 || y == 64){
if (z == 1117 || z == 1113 || z == 1112){
if (x == 1055 || x == 1053 || x == 1049 || x = 1054 ||
x == 1058 || x == 1062 || x == 1050){
return true;
}
}
}
return false;
}
What you will gain from this:
1) The logic for each type is encapsulated into separate classes and you wont have one huge method with long "ifs". And it will be easy to add a new type.
2) By moving the "y" check to top you will do a quick exit if its not 63 or 64. Same applies to z. Since "or" check in Java will not check the rest you will buy some performance by not checking all "x" values if x is 1055 for example.
3) Using Map or Set approach you have to create X, Y, Z wrapper key object on each call to your method. With the method being called very frequently you might have issues with garbage collector not being able to clean them up fast enough.

increasing code performance of codility

today i heard about this website called codility where a user can give various programming test to check their code's performance.
When I started, they presented me with this sample test,
Task description A small frog wants to get to the other side of the
road. The frog is currently located at position X and wants to get to
a position greater than or equal to Y. The small frog always jumps a
fixed distance, D. Count the minimal number of jumps that the small
frog must perform to reach its target.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example,
given:
X = 10
Y = 85
D = 30 the function should return 3,
because the frog will be positioned as follows:
after the first jump,
at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that: X, Y and D are integers within the range
[1..1,000,000,000]; X ≤ Y. Complexity: expected worst-case time
complexity is O(1); expected worst-case space complexity is O(1).
The question was pretty straight forward and it took me like 2 minutes to write the solution, which is following,
class Solution {
public int solution(int X, int Y, int D) {
int p = 0;
while (X < Y){
p++;
X = X + D;
}
return p;
}
}
However, the test result shows that the performance of my code is just 20% and I scored just 55%,
Here is the link to result, https://codility.com/demo/results/demo66WP2H-K25/
That was so simple code, where I have just used a single while loop, how could it possibly be make much faster ?
Basic math:
X + nD >= Y
nD >= Y - X
n >= (Y - X) / D
The minimum value for n will be the result of rounding up the division of (Y - X) by D.
Big O analysis for this operation:
Complexity: O(1). It's a difference, a division and a round up
Worst-case space complexity is O(1): you can have at most 3 more variables:
Difference for Y - X, let's assign this into Z.
Division between Z by D, let's assign this into E.
Rounding E up, let's assign this into R (from result).
Java(One Line), Correctness 100%, Performance 100%, Task score 100%
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
return (int) Math.ceil((double) (Y - X) / (double) D);
}
}
Here is the 100% total score Python solution:
def solution(X, Y, D):
# write your code in Python 3.6
s = (Y-X)/D
return int(-(-s // 1))
class Solution {
public int solution(int x, int y, int d) {
return (y - x + d - 1) / d;
}
}
class Solution {
public int solution(int x, int y, int d) {
// write your code in Java SE 8
System.out.println("this is a debug message"+(y-x)%d);
if((y-x)%d == 0)
return ((y-x)/d);
else
return (((y-x)/d)+1);
}
}
C# got 100 out of 100 points
using System;
// you can also use other imports, for example:
// using System.Collections.Generic;
// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
int Len= Y-X;
if (Len%D==0)
{
return Len/D;
}
else
{
return (Len/D)+1;
}
}
}
Here's Scala solution:
def solution(X: Int, Y: Int, D: Int): Int = {
//divide distance (Y-X) with fixed jump distance. If there is reminder then add 1 to result to
// cover that part with one jump
val jumps = (Y-X) / D + (if(((Y-X) % D) >0 ) 1 else 0)
jumps
}
Performance: https://codility.com/demo/results/trainingTQS547-ZQW/
Javascript solution, 100/100, and shorter than the existing answer:
function solution(Y, Y, D) {
return Math.ceil((Y - X) / D);
}
Here is a solution that brings the test performance to 100%
class Solution {
public int solution(int X, int Y, int D) {
if (X >= Y) return 0;
if (D == 0) return -1;
int minJump = 0;
if ((Y - X) % D == 0) {
minJump = (Y - X) / D;
} else minJump= (Y - X) / D +1;
return minJump;
}
}
JavaScript solution 100/100
function solution (x,y,d) {
if ((y-x) % d === 0) {
return (y-x)/d;
} else {
return Math.ceil((y-x)/d);
}
}
Using Java perfect code
100 score code in Java
public int solution(int X, int Y, int D) {
if(X<0 && Y<0)
return 0;
if(X==Y)
return 0;
if((Y-X)%D==0)
return (Y-X)/D;
else
return (((Y-X)/D)+1);
}
this is corrected code using java giving 91% pass
int solution(int A[]) {
int len = A.length;
if (len == 2) {
return Math.abs(A[1] - A[0]);
}
int[] sumArray = new int[A.length];
int sum = 0;
for (int j = 0; j < A.length; j++) {
sum = sum + A[j];
sumArray[j] = sum;
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < sumArray.length; j++) {
int difference = Math.abs(sum - 2 * sumArray[j]);
// System.out.println(difference);
if (difference < min)
min = difference;
}
return min;
}
This is my solution with 100% (C#):
int result = 0;
if (y <= x || d == 0)
{
result = 0;
}
else
{
result = (y - x + d - 1) / d;
}
return result;
Here is my solution in PHP, 100% performance.
function solution($X, $Y, $D) {
return (int)ceil(($Y-$X)/$D); //ceils returns a float and so we cast (int)
}
Y-X gives you the actual distance object has to be travel ,if that distance is directly divsible by object jump(D) then ans will be (sum/D) if some decimal value is there then we have to add 1 more into it i.e(sum/D)+1
int sum=Y-X;
if(X!=Y && X<Y){
if(sum%D==0){
return (int )(sum/D);
}
else{
return ((int)(sum/D)+1);
}}
else{
return 0;
}
I like all the rest of the solutions, especially "(y - x + d - 1) / d". That was awesome. This is what I came up with.
public int solution(int X, int Y, int D) {
if (X == Y || X > Y || D == 0) {
return 0;
}
int total = (Y - X) / D;
int left = (Y - X) - (D * total);
if (left > 0) {
total++;
}
return total;
}
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(X, Y, D) {
let jumps = 0
//If 0 -> 100 with 2 step
// Answer would be 100/2 = 50
//If 10 -> 100 with 2 step
//Answer would be (100 - 10) / 2 = 45
jumps = Math.ceil((Y - X) / D)
return jumps
}
swift solution 100% PASS - O(1) complexity
import Foundation
import Glibc
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
if X == Y {
return 0
}
var jumps = (Y-X)/D
if jumps * D + X < Y {
jumps += 1
}
return jumps
}
import math
def solution(X, Y, D):
if (X >= Y): return 0
if (D == 0): return -1
minJump = 0
#if ((Y - X) % D == 0):
minJump = math.ceil((Y - X) / D)
#else:
#minJump = math.ceil((Y - X) / D) +1
return minJump
This solution worked for me in Java 11:
public int solution(int X, int Y, int D) {
return X == Y ? 0 : (Y - X - 1) / D + 1;
}
Correctness 100%, Performance 100%, Task score 100%
#Test
void solution() {
assertThat(task1.solution(0, 0, 30)).isEqualTo(0);
assertThat(task1.solution(10, 10, 10)).isEqualTo(0);
assertThat(task1.solution(10, 10, 30)).isEqualTo(0);
assertThat(task1.solution(10, 30, 30)).isEqualTo(1);
assertThat(task1.solution(10, 40, 30)).isEqualTo(1);
assertThat(task1.solution(10, 45, 30)).isEqualTo(2);
assertThat(task1.solution(10, 70, 30)).isEqualTo(2);
assertThat(task1.solution(10, 75, 30)).isEqualTo(3);
assertThat(task1.solution(10, 80, 30)).isEqualTo(3);
assertThat(task1.solution(10, 85, 30)).isEqualTo(3);
assertThat(task1.solution(10, 100, 30)).isEqualTo(3);
assertThat(task1.solution(10, 101, 30)).isEqualTo(4);
assertThat(task1.solution(10, 105, 30)).isEqualTo(4);
assertThat(task1.solution(10, 110, 30)).isEqualTo(4);
}
Here is the JS implementation
function frogJumbs(x, y, d) {
if ((y - x) % d == 0) {
return Math.floor((y - x) / d);
}
return Math.floor((y - x) / d + 1);
}
console.log(frogJumbs(0, 150, 30));
100% C# solution:
public int solution(int X, int Y, int D)
{
var result = Math.Ceiling((double)(Y - X) / D);
return Convert.ToInt32(result);
}
It divides the total distance by length of a jump and rounds up the result. It came after multiple attempts and some web searches.
Here is the solution in Python giving a score of 100 on Codility:
import math
return math.ceil((Y-X)/D)

Categories