--- a/progs/lecture3.scala Fri Nov 17 14:11:58 2017 +0000
+++ b/progs/lecture3.scala Tue Nov 21 16:31:11 2017 +0000
@@ -1,6 +1,55 @@
// Scala Lecture 3
//=================
+// adding two binary strings very, very lazy manner
+
+def badd(s1: String, s2: String) : String =
+ (BigInt(s1, 2) + BigInt(s2, 2)).toString(2)
+
+
+// collatz function on binary numbers
+
+def bcollatz(s: String) : Long = (s.dropRight(1), s.last) match {
+ case ("", '1') => 1 // we reached 1
+ case (rest, '0') => 1 + bcollatz(rest) // even number => divide by two
+ case (rest, '1') => 1 + bcollatz(badd(s + '1', s)) // odd number => s + '1' is 2 * s + 1
+ // add another s gives 3 * s + 1
+}
+
+bcollatz(9.toBinaryString)
+bcollatz(837799.toBinaryString)
+bcollatz(100000000000000000L.toBinaryString)
+bcollatz(BigInt("1000000000000000000000000000000000000000000000000000000000000000000000000000").toString(2))
+
+def conv(c: Char) : Int = c match {
+ case '0' => 0
+ case '1' => 1
+}
+
+def badds(s1: String, s2: String, carry: Int) : String = (s1, s2, carry) match {
+ case ("", "", 1) => "1"
+ case ("", "", 0) => ""
+ case (cs1, cs2, carry) => (conv(cs1.last) + conv(cs2.last) + carry) match {
+ case 3 => badds(cs1.dropRight(1), cs2.dropRight(1), 1) + '1'
+ case 2 => badds(cs1.dropRight(1), cs2.dropRight(1), 1) + '0'
+ case 1 => badds(cs1.dropRight(1), cs2.dropRight(1), 0) + '1'
+ case 0 => badds(cs1.dropRight(1), cs2.dropRight(1), 0) + '0'
+ }
+}
+
+def bcollatz2(s: String) : Long = (s.dropRight(1), s.last) match {
+ case ("", '1') => 1 // we reached 1
+ case (rest, '0') => 1 + bcollatz2(rest) // even number => divide by two
+ case (rest, '1') => 1 + bcollatz2(badds(s + '1', '0' + s, 0)) // odd number => s + '1' is 2 * s + 1
+ // add another s gives 3 * s + 1
+}
+
+bcollatz2(9.toBinaryString)
+bcollatz2(837799.toBinaryString)
+bcollatz2(100000000000000000L.toBinaryString)
+bcollatz2(BigInt("1000000000000000000000000000000000000000000000000000000000000000000000000000").toString(2))
+
+
// One of only two places where I conceded to mutable
// data structures: The following function generates