You are on page 1of 14

Codewars Java Kata in order of Most Completed:

Multiples of 3 or 5 (6):
Return sum of all the multiples of 3 or 5 below the number passed in. If number is a multiple of
both 3 and 5, count it as one. Bg color: #191A1C (25,26,28)

My Solution:
public class Solution {

public int solution(int n) {


int sum=0;
for (int i=3; i<n; i++) {
if ((i%3==0) ^ (i%5==0)) {
sum+=i;
} else if ((i%3==0)&&(i%5==0)) {
sum+=i;
}
}
return sum;
}
}

My solution has a separate XOR and a AND.

Best Solution:
public class Solution {

public int solution(int number) {


int sum=0;

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


if (i%3==0 || i%5==0){sum+=i;}
}
return sum;
}
}

This solution uses a OR statement inside an if. A multiple of 3 and 5, like 15, will only count as one

Clever solution:
import java.util.stream.IntStream;

public class Solution {


public int solution(int number) {
return IntStream.range(0, number)
.filter(n -> (n % 3 == 0) || (n % 5 == 0))
.sum();
}
}

This uses Java8 Streams. Link. Stream is a new abstract layer introduced in Java 8. Using stream,
you can process data in a declarative way similar to SQL statements.
Vowel count (7):
My solution:
public class Vowels {
public static int getCount(String str) {
int vowelsCount = 0;
for (String c: str.split("(?!^)")) {
if ("aeiou".contains(c) && c!=""){
vowelsCount++;
}
}
return vowelsCount;
}
}

Works by splitting string up and checking if each character is in string “aeiou” and not empty

Best solution:
public class Vowels {
public static int getCount(String str) {
return str.replaceAll("(?i)[^aeiou]", "").length();
}
}

Works by removing all non-vowel characters in the string leaving you with only vowels which you
can then get the length and therefore the count of vowels.
str.replaceAll(‘Regex’,’Replacement’) is a method that replaces all that satisfy a regular
expression. (?i) enables case insensitive matching, so you do not need to lower the case. [^aeiou]
matches any character NOT in the set {‘a’,’e’,’I’,’o’,’u’}. So replaces all non-vowels. .length() just
gets length.

Even or Odd(8):
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.

Get the Middle Character(7)


My solution:
class Kata {
public static String getMiddle(String word) {
if (word.length() < 2){return word;}
int mid = word.length()/2;
return word.length()%2==0 ? (word.substring(mid-1,mid+1)):(word.substring(mid,
mid+1));
}
}
If statement to validate input, if single character or no characters then return word. Identify
midpoint, by dividing integers together, which will give an integer, rounded down(floor). Then use
ternary operator to find out if even or odd word, then return appropriate substring, middle 2 or 1.

Best solution, in my opinion:


class Kata {
public static String getMiddle(String word) {
int length = word.length();
return (length % 2 != 0) ? String.valueOf(word.charAt(length / 2)) :
word.substring(length / 2 - 1, length / 2 + 1);
}
}

Person does not calculate mid and assign to variable, they calculate mid separately in the tertiary
condition, this could be because only one of the two statements will be ran. Length is
precalculated as it is used at least twice, in the test condition and in each value.. Since “A word of
length 0 < str < 1000” from description, zero length needn’t be concerned.

Word.length() is assigned to int length. Ternary operator with test condition is true if var length is
odd. If true then the statement will take the middle character using charAt. This however needs to
be a string so we use String.valueOf() to convert the character to a string. This can convert most
types to a string, like arrays of characters, numbers, Booleans, doubles, txt. See Here.
The substring can get the two middle characters otherwise-returns a new string that begins with
the character at the specified index and extends to end of string, otherwise up to endIndex-1.

Use this to time execution time, then get average


https://stackoverflow.com/questions/2572868/how-to-time-java-program-execution-speed (dont
use nano time, see rhu’s answer)

Ignore opposite number (8)


return –n;
Mumbling(7)
My solution:
public class Accumul {

public static String accum(String s) {


String[] c = s.split(""); //splits stirng into characters
for (int i=0; i<c.length; i++){
c[i] = c[i].toUpperCase() + new String(new char[i]).replace("\0",
c[i].toLowerCase());
}
return String.join("-",c);
}
}

Split string into charcters using split(“”), then assign to array c. Then uses a for loop from 0 to the
length of the array. For each character in the array, it is overridden by a string consisting of the
first character that has been converted to uppercase that has a new string added onto the end.
new String() is the creation of a new string object. We do this so we can perform methods on the
class object. The new char[i] inside of new String() creates a new character array object with i
defining how many characters the array will hold-the length, which is not changeable after
creation. As a string is an array of characters the i defines the length of the string added onto the
Capitalised c. All characters default to ‘\0’ - null character, so after that we can use .replace() to
replace the null characters to the specific lowercase character. See this for more information on
new String() and how they work. Then simply return the joined items of the array with ‘-‘s.

Best solution: In my opinion mine is best

Disemvowel Trolls(7)
My solution:
public class Troll {
public static String disemvowel(String str) {
return str.replaceAll("(?i)[aeiou]","");
}
}

This uses method .replaceAll(old,new). I use Regex characters [aeiou] to select all vowels and use
(?i) at the start to make it all case insensitive. Then replace those with null values.

Best solution: I think mine is best


Find the odd int(6)
My solution:
import java.util.*;
public class FindOdd {
public static int findIt(int[] a) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //create map, to store entities
and count

for(int i = 0; i < a.length; i++){ //iterate through array


if (map.containsKey(a[i])) { //if item is already in map, add 1 to its entitys' count
map.put(a[i],map.get(a[i])+1); //adding 1 to its count
} else { //else create entity to hold it and its count
map.put(a[i],1);
}
}

for (Map.Entry<Integer, Integer> entry : map.entrySet()) { //iterate through map keys and
values
if (entry.getValue() % 2 != 0){return entry.getKey();} //if count is odd then return its key
}
return 1; //to prevent error thing.
}
}

My solution uses hashmap so I need to import java utility. I will then create an empty hashmap
with integers and key and values. The key will be the unique entity and the value will be the count
of that entity. I will then iterate through the array to gather the unique entity’s and their
corresponding counts. I do this through an if statement within a for statement that iterates through
‘a’. The if statement determines whether the item is already contained within the map. If it does
exist then it will add 1 to its count, if it does not exist then it creates an entry for it count defaulting
to 1. When done ‘map’ should contain all unique entities and their counts. We can then iterate
through each key-value pair in the map using a for loop. ‘Map.Entry’ object ‘entry’ is a key and its
value combined into one class which allows us to iterate over Map.entrySet() instead of having to
iterate over Map.keySet(), then getting the value for each key. It has the benefit of being more
convenient to use. We can call methods on the object that allow us to get the value or the key with
.getValue() and .getKey(). Therefore we can identify if the count is odd and therefore return the
unique entity, the key. We don’t need anything else because only one entity repeats an odd
number of times, after that we can end the function.

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

Best solution:

public class FindOdd {


public static int findIt(int[] A) {
int xor = 0;
for (int i = 0; i < A.length; i++) {
xor ^= A[i];
}
return xor;
}
}

‘^=’ Bitwise XOR assignment operator. Iterates through array bitwise XORing all the elements
together. Anyting XORed with itself is 0, and anything XORed with 0 will be itself, so the final result
is the only entry that’s in there an odd number of times. See comments under double2.
You’re a square!(7)
My solution:
public class Square {
public static boolean isSquare(int n) {
return Math.sqrt(n) % 1 == 0;
}
}

I use Math.sqrt() to find the squareroot of the integer, I then use modulo to find the remainder
when divided by 1, if it has remainders then it must be a fraction, not an whole integer. Therefore it
cannot be a square number and returns false, otherwise true.

Best solution: Grouped with best practice, simple, easy to understand, fast.
Highest and Lowest. (7)
My solution:
import java.util.Arrays;
public class Kata {
public static String HighAndLow(String numbers) {
String[] strArray = numbers.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
int max = Arrays.stream(intArray).max().getAsInt();
int min = Arrays.stream(intArray).min().getAsInt();
return max+" "+min;
}
}

util.Arrays are imported for the stream methods. First I split the string of numbers into an array
strArray using .split(“ ”). Then I instantiate a new int[] array intArray to hold the numbers as
integers instead of strings. We use a for loop to iterate through the array and parse the values
from strings to integers and put them in intArray. We can then use the stream method of the utility
class Arrays to give us an IntStream on which we can use the min and max methods. We use
getAsInt to convert the value from OptionalInt to int. We can then store the min and max values in
variables and return them in format required. The IntStream is required to allow us to perform
operations on it like min(), sum(), filter() and more.

Best solution:
import java.util.Arrays;

public class Kata {


public static String HighAndLow(String numbers) {

int min = Arrays.stream(numbers.split(" "))


.mapToInt(i -> Integer.parseInt(i))
.min()
.getAsInt();

int max = Arrays.stream(numbers.split(" "))


.mapToInt(i -> Integer.parseInt(i))
.max()
.getAsInt();

return String.format("%d %d", max, min);


}
}

Like mine this one uses util.Arrays. However as you can see it has duplicated code which means it
will have splitting in tint parsing twice. What could be done is mapToInt() is only done once and
them max and min are done separately. Arrays.stream() gets a sequential stream with the
elements of the array, numbers.split(“ “), passed as a parameter. This allows us to perform
operations on the stream. mapToInt() operation returns an IntStream consisting of the results of
applying the given function to the elements of this stream. Here the function is parsing the split
string array into integers. From this we will have an IntStream that contains all numbers as
integers from String numbers. We then can apply other method such as max() and min() which will
return the value as an OptionalInt. To convert these to an Int we use getAsInt(). Format is useful.
Best solution but without duplicate code:
import java.util.Arrays;
import java.util.stream.IntStream;

public class Kata {


public static String HighAndLow(String numbers) {
IntStream stream = Arrays.stream(numbers.split(" "))
.mapToInt(i -> Integer.parseInt(i));
int min = stream.min()
.getAsInt();
int max = stream.max()
.getAsInt();
return String.format("%d %d",max,min);
}
}

Attempt to run:

Here I attempted to remove duplicated code, however I found out that this way is not possible.
From this I gathered that streams are only supposed to be used once because you don’t have to
store it, which makes it efficient. To re-use the data in my attempt I would have to generate it twice
like in the original. I will need to research more about streams.

SummaryStatistics solution:

https://stackoverflow.com/questions/1484347/finding-the-max-min-value-in-an-array-of-primitives-
using-java
import java.util.Arrays;
import java.util.IntSummaryStatistics;

public class Kata {


public static String HighAndLow(String numbers) {
IntSummaryStatistics stats = Arrays.stream(numbers.split("\\s")).
mapToInt(Integer::parseInt).summaryStatistics();

return String.format("%d %d", stats.getMax(), stats.getMin());


}
}

This solution uses summaryStatistics, which gives better performance. Arrays and
IntSummaryStatistics are imported from utility. A IntSummaryStatistics object called stats is
created. A stream is created using an array which is numbers.split(\\s). This is then converted to
an IntStream by parsing all the string values to int values as seen in mapToInt(Integer::parseInt).
Then finally is turned into a summaryStatistics object. The data values are not stored in memory.
With this object we can use methods getMax and getMin to get the required data.
Jaden Casing Strings(7)
My solution:
public class JadenCase {

public String toJadenCase(String phrase) {


if (phrase==null||phrase.isEmpty()){return null;}
String[] words = phrase.split(" ");
String[] newWords = new String[words.length];
for (int i=0; i < words.length; i++){
newWords[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1);
}
return String.join(" ",newWords);
}
}

For my solution I first identify If the input is null or empty, with the || being OR. I will then split the
string into its words using .split(“ “) and store them in an array. I then instantiate a new array with
its fixed length being the amount of words in the string entered. I then use a for loop to go through
each word in the inputted string. There I will capitalise its first letter using substring, which then
gets the rest of the word added onto the end. substring(1) means to take the 2 nd character and the
rest as a substring. I store this capitalised word in an array. Then I can create the new phrase with
all words capitalised by joining them with spaces using .join(“ ”,array). No imports.

Best solution:
import java.lang.Character;

public class JadenCase {

public String toJadenCase(String phrase) {


if(phrase == null || phrase.equals("")) return null;

char[] array = phrase.toCharArray();

for(int x = 0; x < array.length; x++) {


if(x == 0 || array[x-1] == ' ') {
array[x] = Character.toUpperCase(array[x]);
}
}

return new String(array);


}

This solution first checks for null or empty string. It then creates an array of characters
using .toCharArray(), which converts a string to a new character array. Then it does a for loop
which iterates through the array of characters. For each character it checks whether its index is 0,
so at the start of the sentence, or if the character before it is a space. If either of those is true then
the character is converted to uppercase and overwrites the original character by storing it at its
index. After the for loop the array of characters is converted back into a string and returned.
Complementary DNA(7)
My solution in python:
def DNA_strand(dna):
dic = {"A":"T","T":"A","G":"C","C":"G"}
arr = list(dna)
for i, char in enumerate(arr):
arr[i] = dic[char]
return "".join(arr)
My solution uses a dictionary to mark what letters to switch around. It then splits the sting into an
array of characters. It then uses an for loop to go through characters and use dictionary to make
switch. It then returns joined array.

Best solution:
SOURCE = "ATCG"
REPL = "TAGC"
TABLE = str.maketrans(SOURCE,REPL)

def DNA_strand(dna):
return dna.translate(TABLE)

This solution uses .translate() to translate characters in a string using a table.

My solution in java:

public class DnaStrand {


public static String makeComplement(String dna) {
char[] chars = dna.toCharArray();

for (int i = 0; i < chars.length ; i++) {


if(chars[i] == 'A'){
chars[i] = 'T';
} else if(chars[i] == 'T'){
chars[i] = 'A';
}else if(chars[i] == 'C'){
chars[i] = 'G';
} else if(chars[i] == 'G'){
chars[i] = 'C';
}
}
return new String(chars);
}
}

In my solution I identified that I must split the string up into characters, therefore I
used .toCharArray() to give me an array of the characters. I then used a for loop to iterate through
the array to I could switch the Letters using an if else loop. Then I use String() to create a string
using the array of characters.
Best solution:
public class DnaStrand {
public static String makeComplement(String dna) {
char[] chars = dna.toCharArray();
for(int i = 0; i < chars.length; i++) {
chars[i] = getComplement(chars[i]);
}

return new String(chars);


}

private static char getComplement(char c) {


switch(c) {
case 'A': return 'T';
case 'T': return 'A';
case 'C': return 'G';
case 'G': return 'C';
}
return c;
}
}

This solution also starts off by converting the string into an array of characters. It then iterates
through each character and calls the method getComplement, a private static method that returns
char type while taking in a char. Private means the method is only available to the class, and static
means the method belongs to the class rather than the object of the class. This allows it to be
invoke without the need for creating an instance of a class. Inside of this method is a switch
statement that returns a specific character depending on the value entered. After iterating through
the array it returns a new string object using the array of modified characters.

Exes and Ohs(7)


My solution in python:
import re
def xo(s):
xcount = len(re.sub("[^x]","",s.lower()))
ocount = len(re.sub("[^o]","",s.lower()))
return xcount == ocount

I went for regex as I was thinking about how I could do it in java. Replace all characters other than
required to get count, then compare.

Best solution:

def xo(s):
s = s.lower()
return s.count('x') == s.count('o')

Much more simpler


My solution in java:

public class XO {
public static boolean getXO (String str) {
int x = str.toLowerCase().replaceAll("[^x]", "").length();
int o = str.toLowerCase().replaceAll("[^o]", "").length();
return (x == o);
}
}

Same as python code

Best solution:
public class XO {

public static boolean getXO (String str) {


str = str.toLowerCase();
return str.replace("o","").length() == str.replace("x","").length();

}
}

Converts string to lowercase, then compares length of string with o and x removed. Returns
Boolean comparison. Quite similar to mine.
Square Every Digit (7)
My solution:
public class SquareDigit {

public int squareDigits(int n) {


String[] digits = (Integer.toString(n)).split("");
String comp = "";
for (int i=0; i<digits.length;i++){
int digit = Integer.parseInt(digits[i]);
comp += Integer.toString(digit*digit);
}
return Integer.parseInt(comp);
}

For my solution I converted the integer to a string and split it into an array. I then initialised a new
string comp to hold my squared digit integer. I used an for loop to iterate through the array and
converted the single digit string into an integer. I then squared that integer and converted it back
into a string and added it onto the end of the comp string. I then returned the comp string as an
integer.

Best solution:

public class SquareDigit {

public int squareDigits(int n) {


String result = "";

while (n != 0) {
int digit = n % 10 ;
result = digit*digit + result ;
n /= 10 ;
}

return Integer.parseInt(result) ;
}

Creates an empty string result to hold the result. Uses a while loop. The number is modulo by 10
to get the end digit and this is stored in an int variable digit. This digit is then squared and then
concatenated onto the result string. Finally the number is divided by 10 to remove the end digit.
Eventually n == 0 and the while loop ends. Then result should hold the finished number which can
be parsed as an int and returned. This solution is not very efficient the best is the arithmic one.
public class SquareDigit {
private static final int BASE = 10;

public int squareDigits(int n) {


if (n < BASE) {
return squareDigit(n);
}
int digit = n % BASE;
int squaredDigit = squareDigit(digit);
return squaredDigit + (squaredDigit < BASE ? BASE : BASE * BASE) *
squareDigits(n / BASE);
}

private int squareDigit(int n) {


return n * n;
}
}

This one uses pure arithmetic. Uses recursion to get the answer.

Descending Order (7)

You might also like