Java Most Completed 8kyu Only
Java Most Completed 8kyu Only
only:
All of the following are 8kyu, I will skip ones that are very easy and simple
Ignore Multiply:
return a * b;
Even or Odd:
My solution:
public class EvenOrOdd {
public static String even_or_odd(int n) {
if (n%2==0) {return "Even";}
else {return "Odd";}
}
}
Standard If statement
Best solution:
public class EvenOrOdd {
public static String even_or_odd(int number) {
return (number%2 == 0) ? "Even" : "Odd";
}
}
The result is equal to value1 if the testCondition is true, else value2 is assigned.
Neither Is faster, however the ternary operator is much more readable compared to standard if
statements. This is important as it is best practice to use shorter code whenever possible without
detrimental effects, as it focuses on the relevant parts rather than on incidental effects.
I imported java.util.Arrays to get the Arrays.sort() method and then returned just the first element
of the sorted array as it should be the smallest.
Best solution:
import java.util.stream.IntStream;
https://javarevisited.blogspot.com/2012/04/how-to-measure-elapsed-execution-time.html
Sum of positive
My solution:
public class Positive{
public static int sum(int[] arr){
int sum = 0;
for (int i:arr){
if (i>0){sum+=i;}
}
return sum;
}
}
My solution initiates an integer variable to hold the sum of all the positive numbers in the array.
Then it goes through the array using an enhanced for loop and determines if the number is
positive. If it is positive than that number is added onto the sum variable. Once completed the sum
of all positive numbers is returned.
Best solution:
import java.util.Arrays;
public class Positive{
public static int sum(int[] arr){
return Arrays.stream(arr).filter(v -> v > 0).sum();
}
}
This uses util.Arrays for the stream function so it can filter out elements that are not positive. It
then sums the result. Arrays.stream(int[] arr) returns a sequential IntStream with the specified
array as its source. The methods filter and sum can then be used on the IntStream.
String repeat:
My solution:
public class Solution {
public static String repeatStr(final int repeat, final String string) {
return repeat < 1 ? "" : new String(new char[repeat]).replace("\0", string);
}
}
I used a ternary operator to test if the number of repeats is 0 or negative. If it is less than one then
an empty string it returned. Otherwise I create a new string consisting of an array of characters of
count equal to the amount of repeats. The char array is empty and contains only a number of null,
“\0” values. So I then use the replace method to replace each null value with the string to repeat.
Then the new string is returned.
Best solution:
public class Solution {
public static String repeatStr(final int repeat, final String string) {
StringBuilder sb = new StringBuilder();
return sb.toString();
}
}
This solution uses StringBuilder. It then appends the string to the StringBuilder object a certain
amount of times. It then converts the StringBuilder object to a string and returns it.
one trick) Default constructor StringBuilder() constructs a string builder with no characters in it and
an initial capacity of 16 characters. When those 16 characters are filled, sb automatically
increases it's size and copies the data into it. So, if possible, it's better to define the expected size
of your StringBuilder with this constructor StringBuilder(int capacity). So your code will be more
effective.)
Return Negative
My solution:
public class Kata {
public static int makeNegative(final int x) {
return 0 - Math.abs(x);
}
}
Convert to absolute number, which is the distance of the number from 0, and is always positive.
Then minus that number to get the absolute negative.
Best solution, which is basically the same:
import static java.lang.Math.abs;
Counting sheep
My solution:
My solution is cheat as you can’t complete otherwise
Best solution:
public class Counter {
public int countSheeps(Boolean[] arrayOfSheeps) {
int count = 0;
for (Boolean b : arrayOfSheeps) if (b) count++;
return count;
}
}
Reversed Strings
My Solution:
public class Kata {
}
Best Solution:
public class Kata {
}
Uses String Builder so can use methods reverse and toString()
Basic Mathematical Operations
My solution:
public class BasicOperations{
public static Integer basicMath(String op, int v1, int v2){
switch (op){
case "+": return v1+v2;
case "-": return v1-v2;
case "*": return v1*v2;
case "/": return v1/v2;
}
return 0;
}
}
Best solution:
public class BasicOperations{
public static Integer basicMath(String symbol, int x, int y){
switch (symbol){
case "+": return x+y;
case "-": return x-y;
case "*": return x*y;
case "/": return x/y;
}
return 0;
}
}
Keep Hydrated!
My solution:
public class KeepHydrated {
public int Liters(double time) {
return (int) (time * 0.5);
}
}
Best solution:
public class KeepHydrated {
public int Liters(double time) {
return (int)(time / 2);
}
}
Convert number to reversed array of digits
My solution:
public class Kata {
public static int[] digitize(long n) {
int[] digits = new int[Long.toString(n).length()];
int c=0;
while(n>0){
digits[c] = (int)(n%10);
n /= 10;
c++;
}
return digits;
}
}
Best solution: (uses string builder)
public class Kata {
public static int[] digitize(long n) {
return new StringBuilder().append(n)
.reverse()
.chars()
.map(Character::getNumericValue)
.toArray();
}
}
Calculate average
My solution:
public class Kata{
public static double find_average(int[] array){
double total = 0.0;
for (int i:array) {
total += i;
}
return total/array.length;
}
}
Best solution:
import java.util.Arrays;
public class Kata{
public static double find_average(int[] array){
return Arrays.stream(array).average().orElse(0);
}
}
Are You Playing Banjo?
My solution:
public class Banjo {
public static String areYouPlayingBanjo(String name) {
return (Character.toLowerCase(name.charAt(0)) == 'r' ?
name + " plays banjo" :
name + " does not play banjo");
}
}
Best solution:
Mine is best
Invert values
My solution:
public class Kata {
public static int[] invert(int[] array) {
return java.util.Arrays.stream(array).map(i -> -i).toArray();
}
}
Best solution:
public class Kata {
public static int[] invert(int[] array) {
return java.util.Arrays.stream(array).map(i -> -i).toArray();
}
}
Is n divisible by x and y?
My solution:
public class DivisibleNb {
public static Boolean isDivisible(long n, long x, long y) {
return (n%x ==0) && (n%y ==0);
}
}
Best solution:
public class DivisibleNb {
public static Boolean isDivisible(long n, long x, long y) {
return (n%x ==0) && (n%y ==0);
}
}
Do I get a bonus?
My solution:
public class Kata{
public static String bonusTime(final int salary, final boolean bonus) {
return bonus ? "£" + salary*10 : "£" + salary;
}
}
Best solution:
public class Kata{
public static String bonusTime(final int salary, final boolean bonus) {
return bonus ? "£" + salary*10 : "£" + salary;
}
}
Transportation on vacation
My solution:
public class Kata {
public static int rentalCarCost(int d) {
return d < 7 ? d*40 - 20*((d/3>=1)?1:0): d*40 - 50*((d/7>=1)?1:0);
}
}
Best solution:
public class Kata {
public static int rentalCarCost(int d) {
return d < 7 ? d*40 - 20*((d/3>=1)?1:0): d*40 - 50*((d/7>=1)?1:0);
}
}
Volume of a Cuboid
My solution:
public class Kata {
public static double getVolumeOfCuboid(final double length, final double width, final
double height) {
return length * width * height;
}
}
Best solution:
public class Kata {
public static double getVolumeOfCuboid(final double length, final double width, final
double height) {
return length * width * height;
}
}
Sentence Smash
My solution:
public class SmashWords {
public static String smash(String... words) {
return String.join(" ", words);
}
}
Best solution:
public class SmashWords {
public static String smash(String... words) {
return String.join(" ", words);
}
}
Fake Binary
My solution:
public class FakeBinary {
public static String fakeBin(String numberString) {
return numberString.replaceAll("[0-4]", "0").replaceAll("[5-9]", "1");
}
}
Best solution:
Mine is best
Reversed sequence
My solution:
import java.util.stream.IntStream;
public class Sequence{
public static int[] reverse(int n){
return IntStream.range(1,n+1).map(i->n+1-i).toArray();
// range 1 to n+1, map to n+1-i to reverse, convert to array
}
}
Best solution:
import java.util.stream.IntStream;
public class Sequence{
public static int[] reverse(int n){
return IntStream.range(-n, 0).map(Math::abs).toArray();
}
}
Opposites Attract
My solution:
public class OppositesAttract {
public static boolean isLove(final int x, final int y) {
return x%2!=y%2;
}
}
Best solution:
Mine is best
altERnaTIng cAsE <=> ALTerNAtiNG CaSe
My solution:
public class StringUtils {
public static String toAlternativeString(String string) {
char[] c = new char[string.length()];
for (int i=0; i<string.length(); i++){
char sc = string.charAt(i);
if (Character.isUpperCase(sc)){
sc = Character.toLowerCase(sc);
} else {
sc = Character.toUpperCase(sc);
}
c[i] = sc;
}
return String.valueOf(c);
}
}
Best solution:
public class StringUtils {
public static String toAlternativeString(String string) {
String result = "";
for (char c : string.toCharArray()) {
if(Character.isUpperCase(c)) {
result += Character.toLowerCase(c);
} else {
result += Character.toUpperCase(c);
}
}
return result;
}
}
Best solution:
A
My solution:
Best solution:
https://www.youtube.com/watch?v=X-zZrchuDYQ