fix #5 loop optimization
fixed arguments modifying bug added samples and samplebooks w/tests
This commit is contained in:
1 parent
53eb1bc5e7
commit
512dda5984
14 files changed
+311
-53
No files matched your search
@@ -0,0 +1,44 @@
|
||||
# Sample combinatorics calculations
|
||||
|
||||
The trivial to start with, the factorialorial calculation:
|
||||
|
||||
fun factorial(n) {
|
||||
if( n < 1 )
|
||||
1
|
||||
else {
|
||||
var result = 1
|
||||
var cnt = 2
|
||||
while( cnt <= n ) result = result * cnt++
|
||||
}
|
||||
}
|
||||
|
||||
Let's test it:
|
||||
|
||||
assert(factorial(2) == 2)
|
||||
assert(factorial(3) == 6)
|
||||
assert(factorial(4) == 24)
|
||||
assert(factorial(5) == 120)
|
||||
|
||||
Now let's calculate _combination_, or the polynomial coefficient $C^n_k$. It is trivial also, the formulae is:
|
||||
|
||||
$$C^n_k = \frac {n!} {k! (n-k)!} $$
|
||||
|
||||
We can simplify it a little, as $ n ≥ k $, we can remove $k!$ from the fraction:
|
||||
|
||||
$$C^n_k = \frac {(k+1)(k+1)...n} { (n-k)!} $$
|
||||
|
||||
Now the code is much more effective:
|
||||
|
||||
fun C(n,k) {
|
||||
var result = k+1
|
||||
var ck = result + 1
|
||||
while( ck <= n ) result *= ck++
|
||||
result / factorial(n-k)
|
||||
}
|
||||
|
||||
println(C(10,3))
|
||||
assert( C(10, 3) == 120 )
|
||||
|
||||
to be continued...
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Count "happy tickets": 6-digit numbers where sum of first three
|
||||
digits is equal to those of last three. Just to demonstrate and
|
||||
test the Lyng way. It is not meant to be effective.
|
||||
*/
|
||||
|
||||
fun naiveCountHappyNumbers() {
|
||||
var count = 0
|
||||
for( n1 in 0..9 )
|
||||
for( n2 in 0..9 )
|
||||
for( n3 in 0..9 )
|
||||
for( n4 in 0..9 )
|
||||
for( n5 in 0..9 )
|
||||
for( n6 in 0..9 )
|
||||
if( n1 + n2 + n3 == n4 + n5 + n6 ) count++
|
||||
count
|
||||
}
|
||||
|
||||
assert( naiveCountHappyNumbers() == 55252 )
|
||||
@@ -2,6 +2,7 @@
|
||||
gitea: none
|
||||
include_toc: true
|
||||
---
|
||||
|
||||
# Lyng tutorial
|
||||
|
||||
Lyng is a very simple language, where we take only most important and popular features from
|
||||
|
||||
Reference in new issue
Block a user