def riddle _;/#{?\\+??}/=~_ end
def riddle(word):return word.rindex("?")- def riddle _;/#{?\\+??}/=~_ end
# From Ruby 3.0, RSpec is used under the hood. # See https://rspec.info/ # Defaults to the global `describe` for backwards compatibility, but `RSpec.desribe` works as well. describe "Example" do it "Finds index of '?'" do expect(riddle("Two?")).to eq(3) expect(riddle("Ten?")).to eq(3) expect(riddle("Three?")).to eq(5) # The following is still supported, but new tests should now use them. # Test.assert_equals(add(1, 1), 2) end end
test.assert_equals(riddle("Two?"), 3)test.assert_equals(riddle("Ten?"), 3)test.assert_equals(riddle("Three?"), 5)- # From Ruby 3.0, RSpec is used under the hood.
- # See https://rspec.info/
- # Defaults to the global `describe` for backwards compatibility, but `RSpec.desribe` works as well.
- describe "Example" do
- it "Finds index of '?'" do
- expect(riddle("Two?")).to eq(3)
- expect(riddle("Ten?")).to eq(3)
- expect(riddle("Three?")).to eq(5)
- # The following is still supported, but new tests should now use them.
- # Test.assert_equals(add(1, 1), 2)
- end
- end
O(1) solution.
Now returns None
for cases where it is impossible to meet constraints.
def optimal_gifts(gifts: int, recipients: int) -> int: if recipients > gifts or gifts == 4 and recipients == 1: return None if gifts >= recipients * 8: return recipients if gifts == recipients * 8 - 4 or gifts == (recipients - 1) * 8: return recipients - 2 return gifts // 8
- def optimal_gifts(gifts: int, recipients: int) -> int:
kids = [1 for _ in range(gifts)]gifts -= recipientsfor i in range(recipients):while (gifts > 0 and kids[i] < 8):kids[i] += 1gifts -= 1eigths = sum([1 if kid == 8 else 0 for kid in kids])if 4 in kids:eigths -= 1return eigths- if recipients > gifts or gifts == 4 and recipients == 1:
- return None
- if gifts >= recipients * 8:
- return recipients
- if gifts == recipients * 8 - 4 or gifts == (recipients - 1) * 8:
- return recipients - 2
- return gifts // 8
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Examples") def test_group(): @test.it("Example 1") def test_case1(): test.assert_equals(optimal_gifts(8, 2), 0) @test.it("Example 2") def test_case2(): test.assert_equals(optimal_gifts(12, 2), 0) @test.it("Example 3") def test_case3(): test.assert_equals(optimal_gifts(8, 1), 1) @test.it("Example 4") def test_case4(): test.assert_equals(optimal_gifts(24, 2), 2) @test.it("Example 5") def test_case5(): test.assert_equals(optimal_gifts(24, 3), 3) @test.it("Example 6") def test_case6(): test.assert_equals(optimal_gifts(24, 4), 2) @test.it("Example 7") def test_case7(): test.assert_equals(optimal_gifts(1, 2), None) @test.it("Example 8") def test_case8(): test.assert_equals(optimal_gifts(4, 1), None)
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Examples")
- def test_group():
- @test.it("Example 1")
- def test_case1():
- test.assert_equals(optimal_gifts(8, 2), 0)
- @test.it("Example 2")
def test_case1():- def test_case2():
- test.assert_equals(optimal_gifts(12, 2), 0)
- @test.it("Example 3")
def test_case1():- def test_case3():
- test.assert_equals(optimal_gifts(8, 1), 1)
- @test.it("Example 4")
def test_case1():- def test_case4():
- test.assert_equals(optimal_gifts(24, 2), 2)
- @test.it("Example 5")
def test_case1():- def test_case5():
- test.assert_equals(optimal_gifts(24, 3), 3)
- @test.it("Example 6")
def test_case1():- def test_case6():
- test.assert_equals(optimal_gifts(24, 4), 2)
- @test.it("Example 7")
- def test_case7():
- test.assert_equals(optimal_gifts(1, 2), None)
- @test.it("Example 8")
- def test_case8():
- test.assert_equals(optimal_gifts(4, 1), None)
How easy is it to master even-and-odd-ology from a strong foundation of useless program writing?
import java.util.regex.Pattern; import java.math.BigInteger; class StringParity { public static boolean isEvenLength(String str) { return //str.matches("(?s)(..)*") // (?s) enables DOTALL //str.chars().mapToObj(x->0<1).reduce(0<1,(x,_0)->!x) //str.length()<2?str.length()==0:isEvenLength(str.replaceAll("(?s)^..","")) str.length()<1||new BigInteger(Pattern.compile("(?s).").matcher(str).replaceAll(match->""+match.start())).testBit(0) ; } }
- import java.util.regex.Pattern;
- import java.math.BigInteger;
- class StringParity {
- public static boolean isEvenLength(String str) {
return str.replaceAll("(?s)..", "").isEmpty(); // (?s) enables DOTALL- return
- //str.matches("(?s)(..)*") // (?s) enables DOTALL
- //str.chars().mapToObj(x->0<1).reduce(0<1,(x,_0)->!x)
- //str.length()<2?str.length()==0:isEvenLength(str.replaceAll("(?s)^..",""))
- str.length()<1||new BigInteger(Pattern.compile("(?s).").matcher(str).replaceAll(match->""+match.start())).testBit(0)
- ;
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void testSomething() { //System.out.println(StringParity.isEvenLength("even")); assertEquals(true, StringParity.isEvenLength("even")); //System.out.println(StringParity.isEvenLength("odd")); assertEquals(false, StringParity.isEvenLength("odd")); //System.out.println(StringParity.isEvenLength("")); assertEquals(true, StringParity.isEvenLength("")); //System.out.println(StringParity.isEvenLength("Instant Noodles")); assertEquals(false, StringParity.isEvenLength("Instant Noodles")); //System.out.println(StringParity.isEvenLength("\n\n")); assertEquals(true, StringParity.isEvenLength("\n\n")); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- class SolutionTest {
- @Test
- void testSomething() {
- //System.out.println(StringParity.isEvenLength("even"));
- assertEquals(true, StringParity.isEvenLength("even"));
- //System.out.println(StringParity.isEvenLength("odd"));
- assertEquals(false, StringParity.isEvenLength("odd"));
- //System.out.println(StringParity.isEvenLength(""));
- assertEquals(true, StringParity.isEvenLength(""));
- //System.out.println(StringParity.isEvenLength("Instant Noodles"));
- assertEquals(false, StringParity.isEvenLength("Instant Noodles"));
- //System.out.println(StringParity.isEvenLength("\n\n"));
- assertEquals(true, StringParity.isEvenLength("\n\n"));
- }
- }
def generate_binary_list(a, b, c, d): (a, b) = (a, b, a)[d&1:][:2] return [*((a, b)*(c-d>>1)), *(a,)[:c>d][:c-d&1]]
- def generate_binary_list(a, b, c, d):
(a, b) = ((a, b), (b, a))[d&1]return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]- (a, b) = (a, b, a)[d&1:][:2]
- return [*((a, b)*(c-d>>1)), *(a,)[:c>d][:c-d&1]]
def generate_binary_list(a, b, c, d): (a, b) = ((a, b), (b, a))[d&1] return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]
def generate_binay_list(first_number,second_number,elements_on_list,range_begins_at):return [first_number if x%2==0 else second_number for x in range(range_begins_at, elements_on_list)]- def generate_binary_list(a, b, c, d):
- (a, b) = ((a, b), (b, a))[d&1]
- return [*((a, b)*(c-d>>1)), *((), (a,))[c>d][:c-d&1]]
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) test_classes=[] class test_class(): def __init__(self,first_number,second_number,elements_on_list,range_begins_at,expected): self.first_number=first_number self.second_number=second_number self.elements_on_list=elements_on_list self.range_begins_at=range_begins_at self.expected=expected test_classes.append(test_class(2,5,10,0,[2, 5, 2, 5, 2, 5, 2, 5, 2, 5])) test_classes.append(test_class(10,7,23,0,[10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10])) test_classes.append(test_class(0,0,0,0,[])) test_classes.append(test_class(-7,14,-3,0,[])) test_classes.append(test_class(-7,14,-3,-7,[14, -7, 14, -7])) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): for obj in test_classes: result=generate_binary_list(obj.first_number,obj.second_number,obj.elements_on_list,obj.range_begins_at) test.assert_equals(result,obj.expected)
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- test_classes=[]
- class test_class():
- def __init__(self,first_number,second_number,elements_on_list,range_begins_at,expected):
- self.first_number=first_number
- self.second_number=second_number
- self.elements_on_list=elements_on_list
- self.range_begins_at=range_begins_at
- self.expected=expected
- test_classes.append(test_class(2,5,10,0,[2, 5, 2, 5, 2, 5, 2, 5, 2, 5]))
- test_classes.append(test_class(10,7,23,0,[10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10, 7, 10]))
- test_classes.append(test_class(0,0,0,0,[]))
- test_classes.append(test_class(-7,14,-3,0,[]))
- test_classes.append(test_class(-7,14,-3,-7,[14, -7, 14, -7]))
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
- for obj in test_classes:
result=generate_binay_list(obj.first_number,obj.second_number,obj.elements_on_list,obj.range_begins_at)- result=generate_binary_list(obj.first_number,obj.second_number,obj.elements_on_list,obj.range_begins_at)
- test.assert_equals(result,obj.expected)
export function transform(source: any) { const target = {}; Object.entries(source).forEach(function ([k, v]) { k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) { return node[element] ??= {}; }, target)[k.slice(k.lastIndexOf("_") + 1)] = v; }); return target; }
export function transform(obj: any) {const _RegEx = new RegExp(/_/);const underscoredProp = Object.keys(obj).find(key =>_RegEx.test(key)) || '';const value = obj[underscoredProp];const propertList = underscoredProp.split('_').reverse();let toAdd = {};propertList.map((prop,index) => {toAdd = index==0 ?{[prop]:value} : {[prop]:toAdd}})return toAdd;- export function transform(source: any) {
- const target = {};
- Object.entries(source).forEach(function ([k, v]) {
- k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) {
- return node[element] ??= {};
- }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
- });
- return target;
- }
Nice profile picture.
Regex, modulo alternative solution.
defmodule Rot13 do def encode(str) do Regex.replace( ~r/[A-Z]/i, str, fn x -> # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3 <<x::utf8>> = x if x < 97 do rem(x, 26) + 65 else rem(x - 6, 26) + 97 end end ) end end
- defmodule Rot13 do
def rotate({k, v}) docond dov in ?A..?M ->k + 13v in ?N..?Z ->k - 13true ->kendend- def encode(str) do
List.zip([str|> String.to_charlist(),str|> String.upcase()|> String.to_charlist()])|> Enum.map(&rotate/1)|> List.to_string()- Regex.replace(
- ~r/[A-Z]/i,
- str,
- fn x ->
- # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3
- <<x::utf8>> = x
- if x < 97 do
- rem(x, 26) + 65
- else
- rem(x - 6, 26) + 97
- end
- end
- )
- end
- end
# TODO: Replace examples and use TDD by writing your own tests defmodule TestSolution do use ExUnit.Case import Rot13, only: [encode: 1] test "some test description" do assert encode("NOWHERE abjurer") == "ABJURER nowhere" assert encode(" stuff ") == " fghss " assert encode("123 mirë u pafshim абв") == "123 zveë h cnsfuvz абв" assert encode("rknzcyrf") == "examples" assert encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" end end
- # TODO: Replace examples and use TDD by writing your own tests
- defmodule TestSolution do
- use ExUnit.Case
- import Rot13, only: [encode: 1]
- test "some test description" do
- assert encode("NOWHERE abjurer") == "ABJURER nowhere"
- assert encode(" stuff ") == " fghss "
- assert encode("123 mirë u pafshim абв") == "123 zveë h cnsfuvz абв"
- assert encode("rknzcyrf") == "examples"
- assert encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
- end
- end
Obligatory Python golf solution. Don't really like the final version I ended up on.
I don't know APL, but this problem almost felt designed for it. The shortest solution I could think of was {s r c←⍵⋄k←+/q←c⍷s⋄(({⍵'0'[' '=⍵]}¨(-k)↑⍕r)@(k↑⍒q))s}
, I'm sure it can be greatly improved by somebody who knows what they're doing though. (index origin is 0 btw
# exponential time - fast enough when first testcase is commented out f=lambda s,r,c:s and(f(z:=s[:-1],r,c)+s[-1],f(z,r//10,c)+str(r%10))[c==s[-1]] # linear recursive f=lambda s,r,c:s and(c!=s[-1]and f(s[:-1],r,c)+s[-1]or f(s[:-1],r//10,c)+str(r%10)) f=lambda s,r,c:"".join(x==c and[str(r%10),r:=r//10][0]or x for x in s[::-1])[::-1]
using System;using System.Linq;using System.Collections.Generic;- # exponential time - fast enough when first testcase is commented out
- f=lambda s,r,c:s and(f(z:=s[:-1],r,c)+s[-1],f(z,r//10,c)+str(r%10))[c==s[-1]]
- # linear recursive
- f=lambda s,r,c:s and(c!=s[-1]and f(s[:-1],r,c)+s[-1]or f(s[:-1],r//10,c)+str(r%10))
public class Test{static void Main(){Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));}}public class Replacer{public static string sValueReplacer(string source, int index, char char_to_replace){string res = source;try{if (!string.IsNullOrEmpty(char_to_replace.ToString())){if (res.Contains(char_to_replace.ToString())){// Get ALL Indexes position of charactervar Indexes = GetIndexes(res, char_to_replace.ToString());int max = GetMaxValue(Indexes.Count);while (index >= max){index -= max;}var new_value = index.ToString().PadLeft(Indexes.Count, '0');for (int i = 0; i < Indexes.Count; i++){res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());}}}}catch (Exception){res = source;}return res;}private static List<int> GetIndexes(string mainString, string toFind){var Indexes = new List<int>();for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1)){// for loop end when i=-1 (line.counter not found)Indexes.Add(i);}return Indexes;}private static int GetMaxValue(int numIndexes){int max = 0;for (int i = 0; i < numIndexes; i++){if (i == 0)max = 9;elsemax = max * 10 + 9;}return max;}}- f=lambda s,r,c:"".join(x==c and[str(r%10),r:=r//10][0]or x for x in s[::-1])[::-1]
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(f("0000##81#059671####=1811", 3, '#'), "0000008100596710003=1811") test.assert_equals(f("9182 7391238 91$$$$", 3, '$'), "9182 7391238 910003") test.assert_equals(f("The counter is ---", 11, '-'), "The counter is 011")
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
- test.assert_equals(f("0000##81#059671####=1811", 3, '#'), "0000008100596710003=1811")
- test.assert_equals(f("9182 7391238 91$$$$", 3, '$'), "9182 7391238 910003")
- test.assert_equals(f("The counter is ---", 11, '-'), "The counter is 011")
Line 9 is maybe an anti-pattern, but it's the most sensible way to do it I could figure out.
using System.Linq; public class Replacer { public static string sValueReplacer(string s, int z, char x) { var q = Enumerable.Range(0, s.Length).Where((i) => (s[i] == x)); char[] r = s.ToCharArray(); q.Zip(z.ToString().PadLeft(q.Count(), '0'), (i, e) => r[i] = e).Count(); return new string(r); } }
using System;- using System.Linq;
using System.Collections.Generic;public class Test{static void Main(){Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));}}public class Replacer{public static string sValueReplacer(string source, int index, char char_to_replace)- public class Replacer
- {
- public static string sValueReplacer(string s, int z, char x)
- {
string res = source;try{if (!string.IsNullOrEmpty(char_to_replace.ToString())){if (res.Contains(char_to_replace.ToString())){// Get ALL Indexes position of charactervar Indexes = GetIndexes(res, char_to_replace.ToString());int max = GetMaxValue(Indexes.Count);while (index >= max){index -= max;}var new_value = index.ToString().PadLeft(Indexes.Count, '0');for (int i = 0; i < Indexes.Count; i++){res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());}}}}catch (Exception){res = source;}return res;- var q = Enumerable.Range(0, s.Length).Where((i) => (s[i] == x));
- char[] r = s.ToCharArray();
- q.Zip(z.ToString().PadLeft(q.Count(), '0'), (i, e) => r[i] = e).Count();
- return new string(r);
- }
private static List<int> GetIndexes(string mainString, string toFind){var Indexes = new List<int>();for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1)){// for loop end when i=-1 (line.counter not found)Indexes.Add(i);}return Indexes;}private static int GetMaxValue(int numIndexes){int max = 0;for (int i = 0; i < numIndexes; i++){if (i == 0)max = 9;elsemax = max * 10 + 9;}return max;}- }
namespace Solution { using NUnit.Framework; using System; // TODO: Replace examples and use TDD by writing your own tests [TestFixture] public class SolutionTest { [Test] public void MyTest() { Assert.AreEqual("0000008100596710003=1811", Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#')); Assert.AreEqual("9182 7391238 910003", Replacer.sValueReplacer("9182 7391238 91$$$$", 3, '$')); Assert.AreEqual("The counter is 011", Replacer.sValueReplacer("The counter is ---", 11, '-')); } } }
- namespace Solution {
- using NUnit.Framework;
- using System;
- // TODO: Replace examples and use TDD by writing your own tests
- [TestFixture]
- public class SolutionTest
- {
- [Test]
- public void MyTest()
- {
- Assert.AreEqual("0000008100596710003=1811", Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
- Assert.AreEqual("9182 7391238 910003", Replacer.sValueReplacer("9182 7391238 91$$$$", 3, '$'));
- Assert.AreEqual("The counter is 011", Replacer.sValueReplacer("The counter is ---", 11, '-'));
- }
- }
- }
Many wasted division operations, but this looks elegant.
public class Replacer { public static string sValueReplacer(string source, int new_text, char old_char) { char[] intermediate = source.ToCharArray(); for (int i = intermediate.Length - 1; i >= 0; --i) { if (intermediate[i] == old_char) { intermediate[i] = (char) (0x30 | new_text % 10); new_text /= 10; } } return new string(intermediate); } }
using System;using System.Linq;using System.Collections.Generic;public class Test{static void Main(){Console.WriteLine(Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));}}public class Replacer{public static string sValueReplacer(string source, int index, char char_to_replace){string res = source;try{if (!string.IsNullOrEmpty(char_to_replace.ToString())){if (res.Contains(char_to_replace.ToString())){// Get ALL Indexes position of charactervar Indexes = GetIndexes(res, char_to_replace.ToString());int max = GetMaxValue(Indexes.Count);while (index >= max){index -= max;}var new_value = index.ToString().PadLeft(Indexes.Count, '0');for (int i = 0; i < Indexes.Count; i++){res = res.Remove(Indexes[i], 1).Insert(Indexes[i], new_value[i].ToString());}}}}catch (Exception){res = source;}return res;}private static List<int> GetIndexes(string mainString, string toFind)- public class Replacer
- {
- public static string sValueReplacer(string source, int new_text, char old_char)
- {
var Indexes = new List<int>();for (int i = mainString.IndexOf(toFind); i > -1; i = mainString.IndexOf(toFind, i + 1))- char[] intermediate = source.ToCharArray();
- for (int i = intermediate.Length - 1; i >= 0; --i)
- {
// for loop end when i=-1 (line.counter not found)Indexes.Add(i);}return Indexes;}private static int GetMaxValue(int numIndexes){int max = 0;for (int i = 0; i < numIndexes; i++)- if (intermediate[i] == old_char)
- {
if (i == 0)max = 9;elsemax = max * 10 + 9;- intermediate[i] = (char) (0x30 | new_text % 10);
- new_text /= 10;
- }
return max;- }
- return new string(intermediate);
- }
- }
namespace Solution { using NUnit.Framework; using System; // TODO: Replace examples and use TDD by writing your own tests [TestFixture] public class SolutionTest { [Test] public void MyTest() { Assert.AreEqual("0000008100596710003=1811", Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#')); Assert.AreEqual("9182 7391238 910003", Replacer.sValueReplacer("9182 7391238 91$$$$", 3, '$')); Assert.AreEqual("The counter is 011", Replacer.sValueReplacer("The counter is ---", 11, '-')); } } }
- namespace Solution {
- using NUnit.Framework;
- using System;
- // TODO: Replace examples and use TDD by writing your own tests
- [TestFixture]
- public class SolutionTest
- {
- [Test]
- public void MyTest()
- {
- Assert.AreEqual("0000008100596710003=1811", Replacer.sValueReplacer("0000##81#059671####=1811", 3, '#'));
- Assert.AreEqual("9182 7391238 910003", Replacer.sValueReplacer("9182 7391238 91$$$$", 3, '$'));
- Assert.AreEqual("The counter is 011", Replacer.sValueReplacer("The counter is ---", 11, '-'));
- }
- }
- }
Floyd's
let is_happy h = let rec succ n = match n with | 0 -> 0 | _ -> let n' = n mod 10 in n' * n' + succ (n / 10) in let rec floyd's tortoise hare = match hare |> succ |> succ with | 1 -> true | hare' -> let tortoise' = succ tortoise in tortoise' <> hare' && floyd's tortoise' hare' in floyd's h h ;;
def is_happy(h: int) -> bool:"""Returns `True` if `h` is happy, `False` otherwise."""seen = set()while h > 1 and h not in seen:seen.add(h)tot = 0while h > 0:tot += pow(h % 10, 2)h //= 10h = totreturn h == 1- let is_happy h =
- let rec succ n =
- match n with
- | 0 -> 0
- | _ -> let n' = n mod 10 in n' * n' + succ (n / 10)
- in
- let rec floyd's tortoise hare =
- match hare |> succ |> succ with
- | 1 -> true
- | hare' ->
- let tortoise' = succ tortoise in
- tortoise' <> hare' && floyd's tortoise' hare'
- in
- floyd's h h
- ;;
(* TODO: replace with your own tests, these are just how-to examples. * OUnit Spec example: * See http://ounit.forge.ocamlcore.org/api-ounit-2.0.0 for documentation *) module Tests = struct open OUnit let suite = [ "Suite Name" >::: [ "Test Name" >:: (fun _ -> assert_equal (is_happy 3) false ); "Test Name" >:: (fun _ -> assert_equal (is_happy 4) false ); "Test Name" >:: (fun _ -> assert_equal (is_happy 7) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 19) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 103) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 487) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 1663) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 1665) false ); "Test Name" >:: (fun _ -> assert_equal (is_happy 1000000000) true ); "Test Name" >:: (fun _ -> assert_equal (is_happy 10000000001) false ) ] ] ;; end
import codewars_test as testfrom solution import is_happy- (* TODO: replace with your own tests, these are just how-to examples.
- * OUnit Spec example:
- * See http://ounit.forge.ocamlcore.org/api-ounit-2.0.0 for documentation
- *)
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(is_happy(3), False)test.assert_equals(is_happy(4), False)test.assert_equals(is_happy(7), True)test.assert_equals(is_happy(19), True)test.assert_equals(is_happy(103), True)test.assert_equals(is_happy(487), True)test.assert_equals(is_happy(1663), True)test.assert_equals(is_happy(1665), False)test.assert_equals(is_happy(1000000000), True)test.assert_equals(is_happy(10000000001), False)# test.assert_equals(is_happy(), True)- module Tests = struct
- open OUnit
- let suite = [
- "Suite Name" >:::
- [
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 3) false
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 4) false
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 7) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 19) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 103) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 487) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 1663) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 1665) false
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 1000000000) true
- );
- "Test Name" >:: (fun _ ->
- assert_equal (is_happy 10000000001) false
- )
- ]
- ]
- ;;
- end
Be careful! You were previously implicitly defining a global fact
when you really should not have done that. A lot of these problems can be solved by including that "use strict";
at the start of a function, which is especially important when you're starting out.
Also, factorial of 0 is 1, and factorial of negatives is undefined. It's also nice to have proper indentation to make programs a little easier to read.
function factorial (n) { "use strict"; if (n < 0) { return NaN } let i, fact i = fact = 1 while (i <= n) { fact *= i i++ } return fact }
- function factorial (n) {
if (n <= 0) return 0let i = fact = 1- "use strict";
- if (n < 0) {
- return NaN
- }
- let i, fact
- i = fact = 1
- while (i <= n) {
fact *= ii++- fact *= i
- i++
- }
- return fact
- }
const chai = require("chai"); const assert = chai.assert; describe("Solution", function() { it("should test for something", function() { assert(factorial(0), 1); assert(factorial(1), 1); assert(factorial(5), 120); assert(factorial(8),40320); assert(factorial(15),1307674368000); }); });
- const chai = require("chai");
- const assert = chai.assert;
- describe("Solution", function() {
- it("should test for something", function() {
- assert(factorial(0), 1);
- assert(factorial(1), 1);
- assert(factorial(5), 120);
- assert(factorial(8),40320);
- assert(factorial(15),1307674368000);
- });
- });
What's [Z
?
public class Kata { private static Object[] root = {null, new Object[][]{null, null, null, null, null, null, null, null, null, null, {new Boolean(true)}}, null, null, null, null, null, null, null, null, new Object[]{new Boolean(false)} }; public static boolean isHappy(long current) { Boolean[] result = {false}; outer: for (; ; ) { long next = 0; Object[] node = root; while (current > 0) { int remainder = (int) (current % 10); current /= 10; next += remainder * remainder; if (node[remainder] == null) { node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]); while (current > 0) { remainder = (int) (current % 10); current /= 10; next += remainder * remainder; node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]); } node[10] = result; current = next; continue outer; } node = (Object[]) node[remainder]; } if (node[10] != null) { return result[0] = (Boolean) ((Object[]) node[10])[0]; } node[10] = result; current = next; } } }
def is_happy(h: int) -> bool:"""Returns `True` if `h` is happy, `False` otherwise."""seen = set()while h > 1 and h not in seen:seen.add(h)tot = 0while h > 0:tot += pow(h % 10, 2)h //= 10h = totreturn h == 1- public class Kata {
- private static Object[] root = {null,
- new Object[][]{null, null, null, null, null, null, null, null, null, null, {new Boolean(true)}},
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- new Object[]{new Boolean(false)}
- };
- public static boolean isHappy(long current) {
- Boolean[] result = {false};
- outer:
- for (; ; ) {
- long next = 0;
- Object[] node = root;
- while (current > 0) {
- int remainder = (int) (current % 10);
- current /= 10;
- next += remainder * remainder;
- if (node[remainder] == null) {
- node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
- while (current > 0) {
- remainder = (int) (current % 10);
- current /= 10;
- next += remainder * remainder;
- node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
- }
- node[10] = result;
- current = next;
- continue outer;
- }
- node = (Object[]) node[remainder];
- }
- if (node[10] != null) {
- return result[0] = (Boolean) ((Object[]) node[10])[0];
- }
- node[10] = result;
- current = next;
- }
- }
- }
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; // TODO: Replace examples and use TDD by writing your own tests public class SolutionTest { @Test public void testSomething() { assertEquals(Kata.isHappy(3), false); assertEquals(Kata.isHappy(4), false); assertEquals(Kata.isHappy(7), true); assertEquals(Kata.isHappy(19), true); assertEquals(Kata.isHappy(103), true); assertEquals(Kata.isHappy(487), true); assertEquals(Kata.isHappy(1663), true); assertEquals(Kata.isHappy(1665), false); assertEquals(Kata.isHappy(1000000000), true); assertEquals(Kata.isHappy(10000000001l), false); } }
import codewars_test as testfrom solution import is_happy- import org.junit.Test;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
- // TODO: Replace examples and use TDD by writing your own tests
- public class SolutionTest {
- @Test
- public void testSomething() {
- assertEquals(Kata.isHappy(3), false);
- assertEquals(Kata.isHappy(4), false);
- assertEquals(Kata.isHappy(7), true);
- assertEquals(Kata.isHappy(19), true);
- assertEquals(Kata.isHappy(103), true);
- assertEquals(Kata.isHappy(487), true);
- assertEquals(Kata.isHappy(1663), true);
- assertEquals(Kata.isHappy(1665), false);
- assertEquals(Kata.isHappy(1000000000), true);
- assertEquals(Kata.isHappy(10000000001l), false);
- }
- }
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(is_happy(3), False)test.assert_equals(is_happy(4), False)test.assert_equals(is_happy(7), True)test.assert_equals(is_happy(19), True)test.assert_equals(is_happy(103), True)test.assert_equals(is_happy(487), True)test.assert_equals(is_happy(1663), True)test.assert_equals(is_happy(1665), False)test.assert_equals(is_happy(1000000000), True)test.assert_equals(is_happy(10000000001), False)# test.assert_equals(is_happy(), True)
def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]): a = [False] while True: z = 0 # wasting some operations when x is in _trie. nobody cares though. t = _trie while x: r = x%10 x //= 10 z += r*r if t[r]: t = t[r] else: t[r] = (11-(not r))*[False] t = t[r] while x: r = x%10 x //= 10 z += r*r t[r] = (11-(not r))*[False] t = t[r] break else: if t[10]: a[0] = t[10][0] return a[0] t[10] = a x = z
class ref:def __init__(self, data):self.data = datadef is_happy(x, *, _trie=[False,10*[False]+[ref(True)]]+8*[False]+[ref(False)]):a = ref(False)- def is_happy(x, *, _trie=[False,10*[False]+[[True]]]+8*[False]+[[False]]):
- a = [False]
- while True:
- z = 0 # wasting some operations when x is in _trie. nobody cares though.
- t = _trie
- while x:
- r = x%10
if not t[r]:t[r] = (11-(not r))*[False]t = t[r]- x //= 10
z += r**2if t[-1]:a.data = t[-1].datareturn a.datat[-1] = a- z += r*r
- if t[r]:
- t = t[r]
- else:
- t[r] = (11-(not r))*[False]
- t = t[r]
- while x:
- r = x%10
- x //= 10
- z += r*r
- t[r] = (11-(not r))*[False]
- t = t[r]
- break
- else:
- if t[10]:
- a[0] = t[10][0]
- return a[0]
- t[10] = a
- x = z