identification division.
program-id. solution.
data division.
linkage section.
01 n pic 9.
01 r pic 9.
procedure division using n r.
display 'solution'
* 'nested2' cannot be called here
call 'nested2'
on exception display 'cannot call nested2'
end-call
move n to r
goback.
end program solution.
identification division.
program-id. tests.
data division.
working-storage section.
01 expected pic 9.
01 result pic 9.
01 n pic 9.
procedure division.
move 3 to n expected
perform dotest
end tests.
dotest.
call 'nested1'
call 'solution' using n result
expect result to be expected.
.
program-id. nested1.
procedure division.
display 'nested1'
call 'nested2'.
end program nested1.
program-id. nested2 common.
procedure division.
display 'nested2'.
end program nested2.
end program tests.
The evaluation order may be different from the left-to-right order if the pipe operator is present.
The generated code for this example is similar to the following code:
Caml_obj.caml_equal(Caml_array.caml_array_get(a.sort(), 0), Caml_array.caml_array_get($$Array.copy(a), 0));
let f = (a: array(int)): int => a[0]
open Jest;
open Expect;
open Solution;
describe("test", () => {
let refSol = (a: array(int)): int => Js.Array.sortInPlaceWith((-), a)[0];
test("[| 3, 1, 2 |]", () => {
let a = [| 3, 1, 2 |];
// let c = Array.copy(a);
expect(f(Array.copy(a))) |> toBe(refSol(a))
})
});
section .text global max ; declare max function max: ; long max(long a, long b) mov rax, rsi ; default to b cmp rax, rdi cmovl rax, rdi ret
- section .text
- global max ; declare max function
- max: ; long max(long a, long b)
- mov rax, rsi ; default to b
sub rsi, rdisar rsi, 63 ; get signxor rdi, raxand rsi, rdixor rax, rsi ; rax is now the maxxor rsi, rax ; rsi is reset - not sure if this is importantxor rdi, rsi ; rdi is reset - not sure if this is importantret ; i wasted three sheets of paper trying to figure this solution out- cmp rax, rdi
- cmovl rax, rdi
- ret
Algorithms
Logic
Arrays
Data Types
Mathematics
Numbers
import java.util.stream.IntStream; public class ArrayFactorial{ public static int factorial(int n, int k) { return IntStream.rangeClosed(1, Math.min(k, n - k)) .reduce(1, (r, i) -> r * (n - i + 1) / i); } }
import java. math. BigInteger;import java. util. stream. *;- import java.util.stream.IntStream;
- public class ArrayFactorial{
public static int factorial( int n, int k){int lower= Math. min( k, n- k);int higher= Math. max( k, n- k);return IntStream. range( 2, lower+ 1). mapToObj( BigInteger:: valueOf). reduce( IntStream. range( higher+ 1, n+ 1). mapToObj( BigInteger:: valueOf). reduce( BigInteger. ONE, ( a, b)-> a. multiply( b)), ( a, b) -> a. divide( b)). intValue( );- public static int factorial(int n, int k) {
- return IntStream.rangeClosed(1, Math.min(k, n - k))
- .reduce(1, (r, i) -> r * (n - i + 1) / i);
- }
- }
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 BasicTests() { assertEquals(3, ArrayFactorial.factorial(3, 2)); assertEquals(10, ArrayFactorial.factorial(5, 2)); assertEquals(15, ArrayFactorial.factorial(6, 4)); } @Test public void LargerTests() { assertEquals(1365, ArrayFactorial.factorial(15, 4)); assertEquals(19448, ArrayFactorial.factorial(17, 7)); } }
- 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 BasicTests() {
assertEquals(3, ArrayFactorial.factorial(3, 1));- assertEquals(3, ArrayFactorial.factorial(3, 2));
- assertEquals(10, ArrayFactorial.factorial(5, 2));
- assertEquals(15, ArrayFactorial.factorial(6, 4));
- }
- @Test
- public void LargerTests() {
- assertEquals(1365, ArrayFactorial.factorial(15, 4));
- assertEquals(19448, ArrayFactorial.factorial(17, 7));
- }
- }
import codewars_test as test import random # 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(e(1), 0) test.assert_equals(e(2), 2) test.assert_equals(e(6), 6) test.assert_equals(e(9), 8) @test.describe("Random tests") def tests(): for i in range(10): n = random.randint(1, 100) expected = n - n % 2 test.assert_equals(e(n), expected)
- import codewars_test as test
- import random
- # 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(e(1), 0)
- test.assert_equals(e(2), 2)
- test.assert_equals(e(6), 6)
test.assert_equals(e(9), 8)- test.assert_equals(e(9), 8)
- @test.describe("Random tests")
- def tests():
- for i in range(10):
- n = random.randint(1, 100)
- expected = n - n % 2
- test.assert_equals(e(n), expected)
import analysis.special_functions.trigonometric
#check complex.continuous_cos
import Solution
theorem submission_cos : 1 + 1 = 2 := rfl
#print axioms submission_cos
Large factorials with Num
.
Require Solution. From CW Require Loader. Require Extraction. CWStopOnFailure 0. CWGroup "tests". CWTest "type". CWAssert Solution.factorial : (nat -> nat). CWEndTest. CWTest "anti-cheats". CWFile Does Not Match "Extract". CWEndTest. CWTest "extraction". Extract Constant mult => "Num.mult_num". Extract Inductive nat => "Num.num" [ "(Num.Int 0)" "Num.succ_num" ] "(fun zero succ n -> if Num.sign_num n = 0 then zero () else succ (Num.pred_num n))". Extraction "factorial.ml" Solution.factorial. CWCompileAndRun "nums.cma" "factorial.mli" "factorial.ml" Options Driver " open Factorial open Num let () = assert (factorial (Int 0) = (Int 1)); assert (string_of_num (factorial (Int 30)) = ""265252859812191058636308480000000"") ". CWEndTest. CWEndGroup.
- Require Solution.
- From CW Require Loader.
- Require Extraction.
- CWStopOnFailure 0.
- CWGroup "tests".
- CWTest "type".
- CWAssert Solution.factorial : (nat -> nat).
- CWEndTest.
- CWTest "anti-cheats".
- CWFile Does Not Match "Extract".
- CWEndTest.
- CWTest "extraction".
Extract Constant mult => "( * )".Extract Inductive nat => "int"[ "0" "(fun x -> x + 1)" ]"(fun zero succ n -> if n = 0 then zero () else succ (n - 1))".- Extract Constant mult => "Num.mult_num".
- Extract Inductive nat => "Num.num"
- [ "(Num.Int 0)" "Num.succ_num" ]
- "(fun zero succ n -> if Num.sign_num n = 0 then zero () else succ (Num.pred_num n))".
- Extraction "factorial.ml" Solution.factorial.
CWCompileAndRun "factorial.mli" "factorial.ml" Options Driver "- CWCompileAndRun "nums.cma" "factorial.mli" "factorial.ml" Options Driver "
- open Factorial
- open Num
- let () =
assert (factorial 0 = 1);assert (factorial 1 = 1);assert (factorial 5 = 120)- assert (factorial (Int 0) = (Int 1));
- assert (string_of_num (factorial (Int 30)) = ""265252859812191058636308480000000"")
- ".
- CWEndTest.
- CWEndGroup.
Fixpoint factorial (n : nat) :=
match n with
| O => 1
| S n' => n * factorial n'
end.
Require Solution.
From CW Require Loader.
Require Extraction.
CWStopOnFailure 0.
CWGroup "tests".
CWTest "type".
CWAssert Solution.factorial : (nat -> nat).
CWEndTest.
CWTest "extraction".
Extract Constant mult => "( * )".
Extract Inductive nat => "int"
[ "0" "(fun x -> x + 1)" ]
"(fun zero succ n -> if n = 0 then zero () else succ (n - 1))".
Extraction "factorial.ml" Solution.factorial.
CWCompileAndRun "factorial.mli" "factorial.ml" Options Driver "
open Factorial
let () =
assert (factorial 0 = 1);
assert (factorial 1 = 1);
assert (factorial 5 = 120)
".
CWEndTest.
CWEndGroup.
dividedByThree=n=> (n * -1431655765 + 715827882 >>> 0) < 1431655765;
// i assume this is an allowed use of "/" :)dividedByThree=n=>/^-?0*(0*1(01*0)*1)*0*$/.test(n.toString(2))- dividedByThree=n=> (n * -1431655765 + 715827882 >>> 0) < 1431655765;
Test.assertEquals(dividedByThree(3),true) Test.assertEquals(dividedByThree(12),true) Test.assertEquals(dividedByThree(13),false) Test.assertEquals(dividedByThree(0),true) Test.assertEquals(dividedByThree(-12),true) for (let i = 0; i < 100; i++) { const n = -1000000 + Math.random() * 2000000 | 0; Test.assertEquals(dividedByThree(n), n % 3 === 0, `n = ${n}`); }
- Test.assertEquals(dividedByThree(3),true)
- Test.assertEquals(dividedByThree(12),true)
- Test.assertEquals(dividedByThree(13),false)
- Test.assertEquals(dividedByThree(0),true)
Test.assertEquals(dividedByThree(-12),true)- Test.assertEquals(dividedByThree(-12),true)
- for (let i = 0; i < 100; i++) {
- const n = -1000000 + Math.random() * 2000000 | 0;
- Test.assertEquals(dividedByThree(n), n % 3 === 0, `n = ${n}`);
- }
Advanced Language Features
Fundamentals
Theorem Proving
interleave
using Equations
.
From Coq Require Import Lists.List omega.Omega. Import ListNotations. From Equations Require Import Equations. Equations interleave {A} (l1 l2 : list A) : list A by wf (length (l1 ++ l2)) lt := interleave [] l2 := l2; interleave (x :: xs) l2 := x :: interleave l2 xs. Next Obligation. rewrite !app_length; omega. Qed. Example test_interleave1: interleave [1;2;3] [4;5;6] = [1;4;2;5;3;6]. Proof. reflexivity. Qed. Example test_interleave2: interleave [1] [4;5;6] = [1;4;5;6]. Proof. reflexivity. Qed. Example test_interleave3: interleave [1;2;3] [4] = [1;4;2;3]. Proof. reflexivity. Qed. Example test_interleave4: interleave [] [20;30] = [20;30]. Proof. reflexivity. Qed.
- From Coq Require Import Lists.List omega.Omega.
- Import ListNotations.
Fail Fixpoint interleave {A} (l1 l2 : list A) : list A :=match l1 with| [] => l2| x :: xs => x :: interleave l2 xsend.- From Equations Require Import Equations.
Require Import Recdef.Fail Function interleave {A} (l1 l2 : list A) {measure length (l1 ++ l2)} : list A :=match l1 with| [] => l2| x :: xs => x :: interleave l2 xsend.From Coq Require Import Program.Wf.Program Fixpoint interleave {A} (l1 l2 : list A) {measure (length (l1 ++ l2))} : list A :=match l1 with| [] => l2| x :: xs => x :: interleave l2 xsend.Fail Compute (interleave [1;2;3] [4;5;6]).Next Obligation.simpl.repeat rewrite app_length.omega.Qed.Compute (interleave [1;2;3] [4;5;6]).- Equations interleave {A} (l1 l2 : list A) : list A by wf (length (l1 ++ l2)) lt :=
- interleave [] l2 := l2;
- interleave (x :: xs) l2 := x :: interleave l2 xs.
- Next Obligation. rewrite !app_length; omega. Qed.
- Example test_interleave1:
- interleave [1;2;3] [4;5;6] = [1;4;2;5;3;6].
- Proof. reflexivity. Qed.
- Example test_interleave2:
- interleave [1] [4;5;6] = [1;4;5;6].
- Proof. reflexivity. Qed.
- Example test_interleave3:
- interleave [1;2;3] [4] = [1;4;2;3].
- Proof. reflexivity. Qed.
- Example test_interleave4:
- interleave [] [20;30] = [20;30].
- Proof. reflexivity. Qed.
open Preloaded; let fib = (n) => { let rec fib_aux = (n, a, b) => if (n <= 0) { a; } else { fib_aux(n - 1, b, a +@ b); } fib_aux(n, big_int_of_int(0), big_int_of_int(1)) |> string_of_big_int; }; let fib64 = (n) => { // Open Int64 locally open Int64; let rec fib_aux = (n, a, b) => if (n <= 0) { a; } else { fib_aux(n - 1, b, add(a, b)); } fib_aux(n, zero, one) |> to_string; };
- open Preloaded;
- let fib = (n) => {
- let rec fib_aux = (n, a, b) =>
- if (n <= 0) { a; }
- else { fib_aux(n - 1, b, a +@ b); }
- fib_aux(n, big_int_of_int(0), big_int_of_int(1))
- |> string_of_big_int;
- };
- let fib64 = (n) => {
- // Open Int64 locally
- open Int64;
- let rec fib_aux = (n, a, b) =>
- if (n <= 0) { a; }
- else { fib_aux(n - 1, b, add(a, b)); }
- fib_aux(n, zero, one)
- |> to_string;
- };
open Jest; describe("fib", () => { open Expect; test("n = 1", () => expect(Solution.fib(1)) |> toBe("1")); test("n = 10", () => expect(Solution.fib(10)) |> toBe("55")); test("n = 100", () => expect(Solution.fib(100)) |> toBe("354224848179261915075")); test("n = 200", () => expect(Solution.fib(200)) |> toBe("280571172992510140037611932413038677189525")); test("n = 1", () => expect(Solution.fib64(1)) |> toBe("1")); test("n = 10", () => expect(Solution.fib64(10)) |> toBe("55")); test("n = 90", () => expect(Solution.fib64(90)) |> toBe("2880067194370816120")); test("n = 92", () => expect(Solution.fib64(92)) |> toBe("7540113804746346429")); // n = 93 fails // test("n = 93", () => // expect(Solution.fib64(93)) |> toBe("12200160415121876738")); });
- open Jest;
- describe("fib", () => {
- open Expect;
- test("n = 1", () =>
- expect(Solution.fib(1)) |> toBe("1"));
- test("n = 10", () =>
- expect(Solution.fib(10)) |> toBe("55"));
- test("n = 100", () =>
- expect(Solution.fib(100)) |> toBe("354224848179261915075"));
- test("n = 200", () =>
- expect(Solution.fib(200)) |> toBe("280571172992510140037611932413038677189525"));
- test("n = 1", () =>
- expect(Solution.fib64(1)) |> toBe("1"));
- test("n = 10", () =>
- expect(Solution.fib64(10)) |> toBe("55"));
- test("n = 90", () =>
- expect(Solution.fib64(90)) |> toBe("2880067194370816120"));
- test("n = 92", () =>
- expect(Solution.fib64(92)) |> toBe("7540113804746346429"));
- // n = 93 fails
- // test("n = 93", () =>
- // expect(Solution.fib64(93)) |> toBe("12200160415121876738"));
- });
open Preloaded;
let fib = (n) => {
let rec fib_aux = (n, a, b) =>
if (n <= 0) { a; }
else { fib_aux(n - 1, b, a +@ b); }
fib_aux(n, big_int_of_int(0), big_int_of_int(1))
|> string_of_big_int;
};
open Jest;
describe("fib", () => {
open Expect;
test("n = 1", () =>
expect(Solution.fib(1)) |> toBe("1"));
test("n = 10", () =>
expect(Solution.fib(10)) |> toBe("55"));
test("n = 100", () =>
expect(Solution.fib(100)) |> toBe("354224848179261915075"));
test("n = 200", () =>
expect(Solution.fib(200)) |> toBe("280571172992510140037611932413038677189525"));
});