0% found this document useful (0 votes)
97 views19 pages

Java Most Completed 8kyu Only

This document provides code examples for solving various 8kyu kata problems on Codewars in Java. It lists the problem name and provides the author's solution and what they identify as the best solution. For each problem, it explains the approaches taken in both solutions. Some best solutions use more advanced techniques like streams, ternary operators, or StringBuilder. Overall, the document aims to showcase different ways to programmatically solve common programming challenges in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views19 pages

Java Most Completed 8kyu Only

This document provides code examples for solving various 8kyu kata problems on Codewars in Java. It lists the problem name and provides the author's solution and what they identify as the best solution. For each problem, it explains the approaches taken in both solutions. Some best solutions use more advanced techniques like streams, ternary operators, or StringBuilder. Overall, the document aims to showcase different ways to programmatically solve common programming challenges in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Codewars Java Kata in order of Most Completed 8kyu

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";
}
}

This solution uses ternary operator, where

result = testCondition ? value1 : value2;

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.

Ignore opposite number :


return –n;
Find the smallest integer in the array:
My solution:
import java.util.Arrays;
public class SmallestIntegerFinder {
public static int findSmallestInt(int[] args) {
Arrays.sort(args);
return args[0];
}
}

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;

public class SmallestIntegerFinder {


public static int findSmallestInt(int[] args) {
return IntStream.of(args).min().getAsInt();
}
}

Will find out speed difference.

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();

for (int i = 0; i < repeat; i++) {


sb.append(string);
}

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;

public class Kata {


public static int makeNegative(final int x) {
return -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.

Convert Boolean values to strings ‘Yes’ or ‘No’


My Solution:
class YesOrNo
{
public static String boolToWord(boolean b)
{
return b ? "Yes" : "No";
}
}
I use ternary operator, returns “Yes” if true else “No”
Best solution:
Mine is best

Convert a Number to a String!


My Solution:
class Kata {
public static String numberToString(int num) {
return Integer.toString(num);
}
}
Used toString Method.
Best Solution:
class Kata {
public static String numberToString(int num) {
return String.valueOf(num);
}
}
Used String.valueOf() method
Remove First and Last Character
My Solution:
public class RemoveChars {
public static String remove(String str) {
return str.substring(1, str.length() - 1);
}
}
I use the substring method to return a substring consisting of index 1 to length-1
Best Solution:
Mine is best

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;
}
}

Remove String Spaces


My Solution:
class Kata {
static String noSpace(final String x) {
return x.replace(" ", "");
}
}
Best Solution:
Mine is best

Reversed Strings
My Solution:
public class Kata {

public static String solution(String str) {


char[] arr = new char[str.length()];
for (int i=0; i < str.length(); i++){
arr[i] = str.charAt(str.length()-i-1);
}
return new String(arr);
}

}
Best Solution:
public class Kata {

public static String solution(String str) {


return new StringBuilder(str).reverse().toString();
}

}
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;
}
}

Jenny’s secret message


My solution:
public class Greeter {
public static String greet(String name) {
if(name.equals("Johnny")){
return "Hello, my love!";
} else {
return String.format("Hello, %s!", name);
}
}
}
Best solution:
public class Greeter {
public static String greet(String name) {
if(name.equals("Johnny")){
return "Hello, my love!";
} else {
return String.format("Hello, %s!", name);
}
}
}
Grasshopper - Summation
My solution:
public class GrassHopper {
public static int summation(int n) {
int tot=0;
for(int i=1; i<n+1;i++) tot+=i;
return tot;
}
}
Best solution:
public class GrassHopper {
public static int summation(int n) {
return n*(n+1)/2;
}
}
https://math.stackexchange.com/questions/2260/proof-for-formula-for-sum-of-sequence-123-ldotsn

A Needle in the Haystack


My solution:
import java.util.Arrays;
public class Kata {
public static String findNeedle(Object[] haystack) {
for (int i=0; i<haystack.length; i++) {
if (haystack[i] == "needle") return "found the needle at position
"+Integer.toString(i);
}
return "";
}
}
Best solution:
public class Kata {
public static String findNeedle(Object[] haystack) {
return String.format("found the needle at position %d",
java.util.Arrays.asList(haystack).indexOf("needle"));
}
}
Use asList for finding an index of an string

Function 1- hello world


My solution:
public class HelloWorld {
public static String greet() {
return "hello world!";
}
}
Best solution:
public class HelloWorld {
public static String greet() {
return "hello world!";
}
}
Count of positives/sum of negatives
My solution:
public class Kata
{
public static int[] countPositivesSumNegatives(int[] input)
{
if (input == null || input.length == 0) return new int[0];
int count = 0;
int sum = 0;
for (int i : input) {
if (i > 0) count++;
else sum+= i;
}
return new int[]{count,sum};
}
}
Best solution:
public class Kata
{
public static int[] countPositivesSumNegatives(int[] input)
{
if (input == null || input.length == 0) return new int[] {};
int count = 0,sum = 0;
for (int i : input) {
if (i > 0) count ++;
if (i < 0) sum += i;
}
return new int[] {count,sum};
}
}

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();
}
}

Convert a String to a Number!


My solution:
public class StringToNumber {
public static int stringToNumber(String str) {
return Integer.parseInt(str);
}
}
Best solution:
public class StringToNumber {
public static int stringToNumber(String str) {
return Integer.parseInt(str);
}
}

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();
}
}

Sum without highest and lowest number


My solution:
import java.util.stream.IntStream;
import java.util.Arrays;
public class Kata {
public static int sum(int[] numbers) {
if (numbers == null || numbers.length <= 1)return 0;
int sum = IntStream.of(numbers) // int stream using array
.boxed() // boxes each element to an integer
.sorted() // sorts stream
.mapToInt(i -> i) // makes each element an int
.skip(1) // to remove first
.limit(numbers.length-2) // to remove last
.sum(); // to sum numbers
return (int)sum;
}
}
InStream leaves the original array unaltered
Best solution:
import static java.util.stream.IntStream.of;

public class Kata {

public static int sum(int[] numbers) {


return (numbers == null || numbers.length <= 2) ? 0 : of(numbers).sum() -
of(numbers).max().getAsInt() - of(numbers).min().getAsInt();
}
}
Find Maximum and Minimum Values of a List
My solution:
import java.util.stream.IntStream;
public class Kata {
public int min(int[] list) {
return IntStream.of(list).min().getAsInt();
}
public int max(int[] list) {
return IntStream.of(list).max().getAsInt();
}
}
Best solution:
import java.util.stream.IntStream;
public class Kata {
public int min(int[] list) {
return IntStream.of(list).min().getAsInt();
}
public int max(int[] list) {
return IntStream.of(list).max().getAsInt();
}
}

Century From Year


My solution:
public class Solution {
public static int century(int number) {
return (number + 99) / 100;
}
}
Best solution:
public class Solution {
public static int century(int number) {
return (number + 99) / 100;
}
}

You Can’t Code Under Pressure #1


My solution:
class Java {
public static int doubleInteger(int i) {
return i*2;
}
}
Best solution:
class Java {
public static int doubleInteger(int i) {
return i*2;
}
}
DNA to RNA Conversion
My solution:
public class Bio{
public String dnaToRna(String dna){
return dna.replace("T", "U");
}
}
Best solution:
public class Bio{
public String dnaToRna(String dna){
return dna.replace("T", "U");
}
}

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);
}
}

Abbreviate a Two Word Name


My solution:
public class AbbreviateTwoWords {
public static String abbrevName(String name) {
String[] arr = name.toUpperCase().split(" ");
return arr[0].charAt(0) + "." + arr[1].charAt(0);
}
}
Best solution:
public class AbbreviateTwoWords {
public static String abbrevName(String name) {
return name.toUpperCase().replaceAll("(.).*\\s(.).*", "$1.$2");
}
}
Uses regex

Function 3-multiplying two numbers


My solution:
public class Kata {
public static int multiply(int num1, int num2) {
return num1*num2;
}
}
Best solution:
public class Kata {
public static int multiply(int num1, int num2) {
return num1*num2;
}
}
Reversed Words
My solution:
import java.util.*;
public class ReverseWords{
public static String reverseWords(String str){
List Words = Arrays.asList(str.split(" "));
Collections.reverse(Words);
return String.join(" ", Words);
}
}
Best solution:
Mine is best

Convert a Boolean to a String


My solution:
public class BooleanToString {
public static String convert(boolean b){
return b ? "true" : "false";
}
}
Best solution:
Mine is best

Rock Paper Scissors!


My solution:
import java.util.*;
public class Kata {
public static String rps(String p1, String p2) {
List<String> lis = Arrays.asList(new String[] {"rockscissors","scissorspaper",
"paperrock"}); // list of when p1 wins
return (p1 == p2) ? "Draw!" :
((lis.contains(p1+p2)) ? "Player 1 won!" : "Player 2 won!");
}
}
Best solution:
public class Kata {
public static String rps(String p1, String p2) {
if(p1 == p2) return "Draw!";
int p = (p1 + p2).equals("scissorspaper") || (p1 + p2).equals("rockscissors") ||
(p1 + p2).equals("paperrock") ? 1 : 2;
return "Player " + p + " won!";
}
}

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();
}
}

Remove exclamation marks


My solution:
class Solution {
static String removeExclamationMarks(String s) {
return s.replaceAll("!", "");
}
}
Best solution:
Mine is best

Unfinished Loop – Bug Fixing #1


My solution:
import java.util.*;
class Kata {
public static List CreateList(int number)
{
List list = new ArrayList<>();
for(int count = 1; count <= number; count++)
{
list.add(count);
}
return list;
}
}
Best solution:
Mine is best

Parse nice int from char problem


My solution:
public class CharProblem {
public static int howOld(final String herOld) {
return Integer.parseInt(Character.toString(herOld.charAt(0)));
}
}
Best solution:
public class CharProblem {
public static int howOld(final String herOld) {
return Character.getNumericValue(herOld.charAt(0));
}
}
Beginner – Lost Without a Map
My solution:
import java.util.stream.IntStream;
public class Maps {
public static int[] map(int[] arr) {
return IntStream.of(arr).map(i -> i*2).toArray();
}
}
Best solution:
import java.util.*;
public class Maps {
public static int[] map(int[] arr) {
return Arrays.stream(arr).map(x -> x*2).toArray();
}
}

Beginner – Reduce but Grow


My solution:
import java.util.Arrays;
public class Kata{
public static int grow(int[] x){
return Arrays.stream(x).reduce(1, (a, b) -> a * b);
}
}
Best solution:
import java.util.stream.IntStream;
public class Kata{
public static int grow(int[] x){
return IntStream.of(x).reduce(1, (a, b) -> a * b);
}
}

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;
}
}

The Feast of Many Beasts


My solution:
public class Kata {
public static boolean feast(String beast, String dish) {
return beast.charAt(0)==dish.charAt(0) && beast.charAt(beast.length()-1) ==
dish.charAt(dish.length()-1);
}
}
Best solution:
Mine is best

Get the mean of an array


My solution:
import java.util.stream.IntStream;
public class School{
public static int getAverage(int[] marks){
return IntStream.of(marks).sum()/marks.length;
}
}
Best solution:
Mine is best
You only need one - Beginner
My solution:

Best solution:

A
My solution:

Best solution:

https://www.youtube.com/watch?v=X-zZrchuDYQ

You might also like