Scala tail recursive method has an divide and remainder error - scala

I'm currently computing the binomial coefficient of two natural numbers by write a tail recursion in Scala. But my code has something wrong with the dividing numbers, integer division by k like I did as that will give you a non-zero remainder and hence introduce rounding errors. So could anyone help me figure it out, how to fix it ?
def binom(n: Int, k: Int): Int = {
require(0 <= k && k <= n)
def binomtail(n: Int, k: Int, ac: Int): Int = {
if (n == k || k == 0) ac
else binomtail(n - 1, k - 1, (n*ac)/k)
}
binomtail(n,k,1)
}

In general, it holds:
binom(n, k) = if (k == 0 || k == n) 1 else binom(n - 1, k - 1) * n / k
If you want to compute it in linear time, then you have to make sure that each intermediate result is an integer. Now,
binom(n - k + 1, 1)
is certainly an integer (it's just n - k + 1). Starting with this number, and incrementing both arguments by one, you can arrive at binom(n, k) with the following intermediate steps:
binom(n - k + 1, 1)
binom(n - k + 2, 2)
...
binom(n - 2, k - 2)
binom(n - 1, k - 1)
binom(n, k)
It means that you have to "accumulate" in the right order, from 1 up to k, not from k down to 1 - then it is guaranteed that all intermediate results correspond to actual binomial coefficients, and are therefore integers (not fractions). Here is what it looks like as tail-recursive function:
def binom(n: Int, k: Int): Int = {
require(0 <= k && k <= n)
#annotation.tailrec
def binomtail(nIter: Int, kIter: Int, ac: Int): Int = {
if (kIter > k) ac
else binomtail(nIter + 1, kIter + 1, (nIter * ac) / kIter)
}
if (k == 0 || k == n) 1
else binomtail(n - k + 1, 1, 1)
}
Little visual test:
val n = 12
for (i <- 0 to n) {
print(" " * ((n - i) * 2))
for (j <- 0 to i) {
printf(" %3d", binom(i, j))
}
println()
}
prints:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
Looks ok, compare it with this, if you want.

Andrey Tyukin's excellent example will fail with larger n, say binom(10000, 2), but can be easily adapted to use BigInt.
def binom(n: Int, k: Int): BigInt = {
require(0 <= k && k <= n)
#annotation.tailrec
def binomtail(nIter: Int, kIter: Int, ac: BigInt): BigInt = {
if (kIter > k) ac
else binomtail(nIter + 1, kIter + 1, (nIter * ac) / kIter)
}
if (k == 0 || k == n) 1
else binomtail(n - k + 1, 1, BigInt(1))
}

Related

how to solve subscript out of range in qbasic

I am in big problem in solving a code essential for me, and I need the solution as soon as possible
in fact, I have little knowledge of programming in basic
I have a problem with this code.
I have an equation, and I use this code to solve this equation
when I run the program
this error appears
subscript out of range
is there any solution to this problem
0 Print "******** impact *******"
20 Print "____________"
30 Print "this programs is used to solve impact integral"
40 Print "equation of simply supported slab to "
50 Print "optain the following"
60 Print " (1) force _time history"
70 Print " (2) central deflection - time history"
80 Print "-----------------"
90 Print "input data:"
100 Print " (1) FUNDAMENTAL NATURAL FREQUANCY (RAD/SEC)--- W1"
110 Print " (2) STRIKER MASS (KG.) ----- Mst"
120 Print " (3) MASS OF SLAB (KG)---- Ms"
130 Print " (4) hertz constant (n/m^1.5)----k"
140 Print " (5) STRICKER VELOCITY (M/S)----Vo"
150 Print " (6) NUMBER OF MODES----N"
160 Print "_________"
170 Input " W11, MST, MS, K, VO, N", W11, MST, MS, K, VO, N
180 Print "W1="; W11; "RAD/SEC"
190 Print "MST="; MST; "KG"
200 Print "MS="; MS; "KG"
210
220 Print " K = "; K; "N/M^1.5"
230 Print STANDARD
240 Print "VO="; VO; "M/S"
241 Print " N = "; N
250 Print
260 Print
270 K1 = K
280 V = VO
290 W1 = W11 / 2
300 TINF = 2.94 * (MST / (.8 * K1 * V ^ .5)) ^ .4 * 1000
310 DT = TINF / 10
320 M = 20
330 DT = PROUND(DT, 0)
340 DT = DT / 1000
350 M = 20
360 Option Base 1
370 Dim W(11, 11), Z(11, 11), F(30), D(30), BM(30), SH(30), A(30), T(30), DF(30), S(11, 11, 30), C(11, 11, 30)
380 ReDim W(N, N), Z(N, N)
390 For I = 1 To N Step 2
400 For K = 1 To N Step 2
410 W(K, I) = W1 * (I ^ 2 + K ^ 2)
420 Z(K, I) = W(K, I) * DT
430 Next K
440 Next I
450 ReDim F(M), D(M), A(M), T(M), DF(M), BM(M), SH(M), S(N, N, M), C(N, N, M)
460 F(1) = D(1) = A(1) = T(1) = 0
470 For I = 1 To N Step 2
480 For K = 1 To N Step 2
490 S(K, I, 1) = C(K, I, 1) = 0
500 Next K
510 Next I
520 B1 = 0
530 For I = 1 To N Step 2
540 For K = 1 To N Step 2
550 B1 = B1 + (1 - Sin(Z(K, I)) / Z(K, I)) / W(K, I) ^ 2
560 Next K
570 Next I
580 B = -DT ^ 2 / (6 * MST) - 4 * B1 / MS
590 VE = 0
600 For I = 2 To M
610 T(I) = (I - 1) * DT
620 GM = 0
630 If VE = 1 Then 970
640 For J = 2 To I
650 GM = GM + F(J - 1)
660 Next J
670 AA = 0
680 For J = 1 To N Step 2
690 For K = 1 To N Step 2
700 FF = F(I - 1) * (Sin(Z(K, J)) / Z(K, J) - Cos(Z(K, J))) / W(K, J)
710 AA = AA + 4 * (Cos(Z(K, J)) * S(K, J, I - 1) + Sin(Z(K, J)) * C(K, J, I - 1) + FF) / (MS * W(K, J))
720 Next K
730 Next J
740 A(I - 1) = V * (I - 1) * DT - (D(I - 1) + DT ^ 2 * (GM - F(I - 1) / 6)) / MST - AA
750 F = F(I - 1)
760 If A(I - 1) + B * F < 0 Then 840
770 F1 = (A(I - 1) + B * F) ^ 1.5 * K1
780 X = Abs(F1 - F)
790 If X < 10 Then 820
800 F = F1
810 GoTo 770
820 F(I) = F1
830 GoTo 850
840 F(I) = 0
850 D(I) = D(I - 1) + DT ^ 2 * (GM + (F(I) - F(I - 1)) / 6)
860 For J = 1 To N Step 2
870 For K = 1 To N Step 2
880 S(K, J, I) = Cos(Z(K, J)) * S(K, J, I - 1) + Sin(Z(K, J)) * C(K, J, I - 1) + (1 - Sin(Z(K, J)) / Z(K, J)) * (F(I) - F(I - 1)) / W(K, J) + (1 - Cos(Z(K, J))) * F(I - 1) / W(K, J)
890 C(K, J, I) = Cos(Z(K, J)) * C(K, J, I - 1) - Sin(Z(K, J)) * S(K, J, I - 1) + (1 - Cos(Z(K, J))) / Z(K, J) * (F(I) - F(I - 1)) / W(K, J) + Sin(Z(K, J)) * F(I - 1) / W(K, J)
900 Next K
910 Next J
920 DF = 0
930 For J = 1 To N Step 2
940 For K = 1 To N Step 2
950 DF = DF + 4 * S(K, J, I) / W(K, J) / MS
960 Next K
970 Next J
980 DF(I) = DF
990 If F(I) = 0 Then 1010
1000 Next I
1010 Print "----------------------------------------------------------"
1020 Print "{TIME (MS)},{FORCE (KN)},{DEFLECTION(MM)}"
1030 Print "----------------------------------------------------------"
1040 II = I
1050 For O = 1 To II
1060
1070 Print Tab(1); ":"; Tab(5); T(0) * 1000; Tab(18); ":"; Tab(22); F(O) / 1000; Tab(34); ":"; Tab(42); DF(O) * 1000; Tab(56); ":"
1080 Print "-----------------------------------------------------------"
1090 Next O
1100 End

Minizinc constraint against recursive function

I want to use a function like this:
function int: nextr(var int: n)
if n <= 1
2
elseif n <= 8
n + 5
elseif n <= 68
n + 13
elseif n <= 509
n + 34
elseif n <= 3611
n + 89
else n + 233
in a constraint that variable must satisfy any value in nextr(n), nextr(nextr(n)), nextr(next(nextr(n))), and so on.
Is there a way to specify such constraint in minizinc? If not possible generally, I'm OK with explicit recursion limit, but without tedious enumeration of all the steps?
Example:
The value of y is constrained to be equal
next(x) \/ next(next(x)) \/ ...
up to K levels of nesting.
function var int: nextr(var int: n) =
if n <= 1 then
2
elseif n <= 8 then
n + 5
elseif n <= 68 then
n + 13
elseif n <= 509 then
n + 34
elseif n <= 3611 then
n + 89
else
n + 233
endif;
int: K = 10;
var int: x;
var int: y;
array[1..K] of var int: rec_up_to_k;
constraint forall (i in 1..K) (
if i == 1 then
rec_up_to_k[i] = nextr(x)
else
rec_up_to_k[i] = nextr(rec_up_to_k[i-1])
endif
);
constraint exists (i in 1..K) (
y = rec_up_to_k[i]
);
constraint x >= 0;
solve satisfy;
outputs:
x = 3612;
y = 3845;
rec_up_to_k = array1d(1..10, [3845, 4078, 4311, 4544, 4777, 5010, 5243, 5476, 5709, 5942]);
----------

How to resolve variable increment issue in a recursive function

Trying to create a pascals triangle using recursive function. Returning value is always zero.
I'm new to Scala programming and not sure if the declaring the value variable in the code is the right way. Appreciate any help with the right approach. Thanks
object Main {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
}
var value: Int = 0
def pascal(c: Int, r: Int): Int = {
if (c ==0) 1
else if (c == r ) 1
else
for (col <- c-1 to c) {
value += pascal(col, r - 1)
}
value
}
}
Actual Result
Pascal's Triangle
0
0 0
0 0 0
0 0 0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
Expected Result
Pascal's Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
Scala style tries to avoid mutable data (i.e. var).
def pascalTriangle(height :Int) :Unit =
Iterator.iterate(Vector(1))(v => (0+:v:+0).sliding(2).map(_.sum).toVector)
.take(height) //take only as many as needed
.map(_.mkString(" ")) //turn Vector into space separated String
.foreach(println) //force the calculations
Here we create an infinite collection of Vectors, each one longer than the previous. Each Vector is processed to create the required sums, but none of that happens until the foreach() because an Iterator is lazy.
You should avoid using var. In this case, you don't need it. Avoid var, use val. Such is good functional programming practice.
object Pascal {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
}
def pascal(c: Int, r: Int): Int = {
if (c ==0) 1
else if (c == r ) 1
else {
val intermediate = for (col <- c - 1 to c) yield pascal(col, r - 1)
intermediate.sum
}
}
}

Interleaving iterators

I wrote the following code, expecting the last print method to show the elements of both iterators combined. Instead it only shows the elements of perfectSquares. Can someone explain this to me?
object Fuge {
def main(args: Array[String]) : Unit = {
perfectSquares.takeWhile(_ < 100).foreach(square => print(square + " "))
println()
triangles.takeWhile(_ < 100).foreach(triangle => print(triangle + " "))
println()
(perfectSquares++triangles).takeWhile(_ < 100).foreach(combine => print(combine + " "))
}
def perfectSquares : Iterator[Int] = {
Iterator.from(1).map(x => x * x)
}
def triangles : Iterator[Int] = {
Iterator.from(1).map(n => (n * (n + 1)/2))
}
}
OUTPUT:
1 4 9 16 25 36 49 64 81
1 3 6 10 15 21 28 36 45 55 66 78 91
1 4 9 16 25 36 49 64 81
From the documentation on takeWhile:
/** Takes longest prefix of values produced by this iterator that satisfy a predicate.
*
* #param p The predicate used to test elements.
* #return An iterator returning the values produced by this iterator, until
* this iterator produces a value that does not satisfy
* the predicate `p`.
* #note Reuse: $consumesAndProducesIterator
*/
What this means is that the iterator stops at that juncture. What you've created is an iterator that goes far past 100 and then, at some point, starts off at 1 again. But takeWhile won't go that far because it's already run into a number higher than 100. See:
object Fuge {
def main(args: Array[String]) : Unit = {
perfectSquares.takeWhile(_ < 100).foreach(square => print(square + " "))
println()
triangles.takeWhile(_ < 100).foreach(triangle => print(triangle + " "))
println()
def interleave (a: Iterator[Int], b: Iterator[Int]): Stream[Int] = {
if (a.isEmpty || b.isEmpty) { Stream.empty }
else {
a.next() #:: b.next() #:: interleave(a, b)
}
}
lazy val interleaved = interleave(perfectSquares, triangles)
interleaved.takeWhile(_ < 100).foreach(combine => print(combine + " "))
}
def perfectSquares : Iterator[Int] = {
Iterator.from(1).map(x => x * x)
}
def triangles : Iterator[Int] = {
Iterator.from(1).map(n => (n * (n + 1)/2))
}
}
Here I'm using a stream to lazily evaluate the sequence of integers. In this way we can ensure interleaving. Note that this is just interleaved, not sorted.
This yields:
1 4 9 16 25 36 49 64 81
1 3 6 10 15 21 28 36 45 55 66 78 91
1 1 4 3 9 6 16 10 25 15 36 21 49 28 64 36 81 45
To sort during a stream, you need a BufferedIterator and to change up the interleave function a bit. This is because calling next() advances the iterator - you can't go back. And you also can't know how many items you need from list a before you need an item from list b, and vice versa. But BufferedIterator allows you to call head, which is a 'peek' and does not advance the iterator. Now the code becomes:
object Fuge {
def main(args: Array[String]) : Unit = {
perfectSquares.takeWhile(_ < 100).foreach(square => print(square + " "))
println()
triangles.takeWhile(_ < 100).foreach(triangle => print(triangle + " "))
println()
def interleave (a: BufferedIterator[Int], b: BufferedIterator[Int]): Stream[Int] = {
if (a.isEmpty || b.isEmpty) { Stream.empty }
else if (a.head <= b.head){
a.next() #:: interleave(a, b)
} else {
b.next() #:: interleave(a, b)
}
}
lazy val interleaved = interleave(perfectSquares.buffered, triangles.buffered)
interleaved.takeWhile(_ < 100).foreach(combine => print(combine + " "))
}
def perfectSquares : Iterator[Int] = {
Iterator.from(1).map(x => x * x)
}
def triangles : Iterator[Int] = {
Iterator.from(1).map(n => (n * (n + 1)/2))
}
}
And the output is:
1 4 9 16 25 36 49 64 81
1 3 6 10 15 21 28 36 45 55 66 78 91
1 1 3 4 6 9 10 15 16 21 25 28 36 36 45 49 55 64 66 78 81 91
The problems with using Streams here is that they cache all the previous data. I'd rather interleave iterators as is, without involving streams.
Something like this:
class InterleavingIterator[X, X1 <: X, X2 <: X](
iterator1: Iterator[X1],
iterator2: Iterator[X2]) extends Iterator[X] {
private var i2: (Iterator[X], Iterator[X]) = (iterator1, iterator2)
def hasNext: Boolean = iterator1.hasNext || iterator2.hasNext
def next: X = {
i2 = i2.swap
if (i2._1.hasNext) i2._1.next else i2._2.next
}
}

Octal number equations

So I'm reading a book on how binary bits are converted into octal numbers.
When trying to explain the concept, they give this equation
N= S(...((d8)2^8+(d7)2^7+(d6)2^6)+((d5)2^5+(d4)2^4+(d3)2^3)+((d2)2^2+(d1)2^1+d0))
or
N= S(...((d8)2^2 +(d7)2+(d6))2^6 + ((d5)2^2 +(d4)2^1 + (d3))2^3 + ((d2)2^2+(d1)2^1+d0))
d represents the digit found within the bit, e.g. if the least significant bit was 1, then (d0) would be 1.
I understand all of this, but they elaborate further saying that the parenthesized expressions ((d8)2^2 +(d7)2+(d6)) are coefficients of base 8 digits, N=S((d2)8^2+(d1)*8+(d0)).
Can someone explain what they mean by the parenthesized expressions being coefficients of base8 digits?
The digits di are the binary digits of the number. We can compute the number from its binary digits like this:
n = ∑ i 2i di = 20 d0 + 21 d1 + 22 d2 + ⋯
(This is in fact what defines “binary”, if we add the condition that the digits are integers and 0 ≤ di < 2 for all i.)
Suppose we name the octal digits of the number oj. We can compute the number from its octal digits like this:
n = ∑ j 8j oj = 80 o0 + 81 o1 + 82 o2 + ⋯
(This is what defines “octal”, if we add the condition that the digits are integers and 0 ≤ oj < 8 for all j.)
Now let's look back at the binary equation. The first step is the trickiest. We will change the way the subscript is used so that each term of the summation uses three binary digits:
n = ∑ j 23 j + 0 d3 j + 0 + 23 j + 1 d3 j + 1 + 23 j + 2 d3 j + 2
Convince yourself that that equation computes the same n as the first equation I gave.
I assume you know that xa + b = xa xb. So we can separate those 23 j + b coefficients like this:
n = ∑ j (23 j 20) d3 j + 0 + (23 j 21) d3 j + 1 + (23 j 22) d3 j + 2
Then we can factor out the 23 j term like this:
n = ∑ j 23 j (20 d3 j + 0 + 21 d3 j + 1 + 22 d3 j + 2)
I assume you also know that xa b = (xa)b. So we can split the 23 j term like this:
n = ∑ j (23)j (20 d3 j + 0 + 21 d3 j + 1 + 22 d3 j + 2)
And we can simplify 23 to 8:
n = ∑ j 8j (20 d3 j + 0 + 21 d3 j + 1 + 22 d3 j + 2)
Compare this to the formula for computing the number from its octal digits, which I repeat here:
n = ∑ j 8j oj
So we can conclude this:
oj = 20 d3 j + 0 + 21 d3 j + 1 + 22 d3 j + 2
For example, let's take j = 2:
o2 = 20 d3×2 + 0 + 21 d3×2 + 1 + 22 d3×2 + 2 = 20 d6 + 21 d7 + 22 d8