How to count number of digits? - scheme

(CountDigits n) takes a positive integer n, and returns the number of digits it contains. e.g.,
(CountDigits 1) → 1
(CountDigits 10) → 2
(CountDigits 100) → 3
(CountDigits 1000) → 4
(CountDigits 65536) → 5
I think I'm supposed to use the remainder of the number and something else but other then that im really lost. what i tried first was dividing the number by 10 then seeing if the number was less then 1. if it was then it has 1 digit. if it doesnt then divide by 100 and so on and so forth. but im not really sure how to extend that to any number so i scrapped that idea
(define (num-digits number digit)
(if (= number digit 0)
1

Stumbled across this and had to provide the log-based answer:
(define (length n)
(+ 1 (floor (/ (log n) (log 10))))
)
Edit for clarity: This is an O(1) solution that doesn't use recursion. For example, given
(define (fact n)
(cond
[(= n 1) 1]
[else (* n (fact (- n 1)))]
)
)
(define (length n)
(+ 1 (floor (/ (log n) (log 10))))
)
Running (time (length (fact 10000))) produces
cpu time: 78 real time: 79 gc time: 47
35660.0
Indicating that 10000! produces an answer consisting of 35660 digits.

After some discussion in the comments, we figured out how to take a number n with x digits and to get a number with x-1 digits: divide by 10 (using integer division, i.e., we ignore the remainder). We can check whether a number only has one digit by checking whether it's less than 10. Now we just need a way to express the total number of digits in a number as a (recursive) function. There are two cases:
(base case) a number n less than 10 has 1 digit. So CountDigits(n) = 1.
(recursive case) a number n greater than 10 has CountDigits(n) = 1+CountDigits(n/10).
Now it's just a matter of coding this up. This sounds like homework, so I don't want to give everything away. You'll still need to figure out how to write the condition "n < 10" in Scheme, as well as "n/10" (just the quotient part), but the general structure is:
(define (CountDigits n) ; 1
(if [n is less than 10] ; 2
1 ; 3
(+ 1 (CountDigits [n divided by 10])))) ; 4
An explanation of those lines, one at a time:
(define (CountDigits n) begins the definition of a function called CountDigits that's called like (CountDigits n).
In Racket, if is used to evaluate one expression, called the test, or the condition, and then to evaluate and return the value of one of the two remaining expressions. (if test X Y) evaluates test, and if test produces true, then X is evaluated and the result is returned, but otherwise Y is evaluated and the result is returned.
1 is the value that you want to return when n is less than 10 (the base case above).
1+CountDigits(n/10) is the value that you want to return otherwise, and in Racket (and Scheme, and Lisp in general) it's written as (+ 1 (CountDigits [n divided by 10])).
It will be a good idea to familiarize with the style of the Racket documentation, so I will point you to the appropriate chapter: 3.2.2 Generic Numerics. The functions you'll need should be in there, and the documentation should provide enough examples for you to figure out how to write the missing bits.

I know this is old but for future reference to anyone who finds this personally I'd write it like this:
(define (count-digits n acc)
(if (< n 10)
(+ acc 1)
(count-digits (/ n 10) (+ acc 1))))
The difference being that this one is tail-recursive and will essentially be equivalent to an iterative function(and internally Racket's iterative forms actually exploit this fact.)
Using trace illustrates the difference:
(count-digits-taylor 5000000)
>(count-digits-taylor 5000000)
> (count-digits-taylor 500000)
> >(count-digits-taylor 50000)
> > (count-digits-taylor 5000)
> > >(count-digits-taylor 500)
> > > (count-digits-taylor 50)
> > > >(count-digits-taylor 5)
< < < <1
< < < 2
< < <3
< < 4
< <5
< 6
<7
7
(count-digits 5000000 0)
>(count-digits 5000000 0)
>(count-digits 500000 1)
>(count-digits 50000 2)
>(count-digits 5000 3)
>(count-digits 500 4)
>(count-digits 50 5)
>(count-digits 5 6)
<7
7
For this exercise this doesn't matter much, but it's a good style to learn. And of course since the original post asks for a function called CountDigits which only takes one argument (n) you'd just add:
(define (CountDigits n)
(count-digits n 0))

Related

SICP solution to Fibonacci, set `a + b = a`, why not `a + b = b`?

I am reading Tree Recursion of SICP, where fib was computed by a linear recursion.
We can also formulate an iterative process for computing the
Fibonacci numbers. The idea is to use a pair of integers a and b,
initialized to Fib(1) = 1 and Fib(0) = 0, and to repeatedly apply the
simultaneous transformations
It is not hard to show that, after applying this transformation n
times, a and b will be equal, respectively, to Fib(n + 1) and Fib(n).
Thus, we can compute Fibonacci numbers iteratively using the procedure
(rewrite by Emacs Lisp substitute for Scheme)
#+begin_src emacs-lisp :session sicp
(defun fib-iter (a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
(defun fib (n)
(fib-iter 1 0 n))
(fib 4)
#+end_src
"Set a + b = a and b = a", it's hard to wrap my mind around it.
The general idea to find a fib is simple:
Suppose a completed Fibonacci number table, search X in the table by jumping step by step from 0 to X.
The solution is barely intuitive.
It's reasonably to set a + b = b, a = b:
(defun fib-iter (a b count)
(if (= count 0)
a
(fib-iter b (+ a b) (- count 1))
)
)
(defun fib(n)
(fib-iter 0 1 n))
So, the authors' setting seems no more than just anti-intuitively placing b in the head with no special purpose.
However, I surely acknowledge that SICP deserves digging deeper and deeper.
What key points am I missing? Why set a + b = a rather than a + b = b?
As far as I can see your problem is that you don't like it that order of the arguments to fib-iter is not what you think it should be. The answer is that the order of arguments to functions is very often simply arbitrary and/or conventional: it's a choice made by the person writing the function. It does not matter to anyone but the person reading or writing the code: it's a stylistic choice. It doesn't particularly seem more intuitive to me to have fib defined as
(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter next current n)
(if (zero? n)
current
(fib-iter (+ next current) next (- n 1))))
Rather than
(define (fib n)
(fib-iter 0 1 n))
(define (fib-iter current next n)
(if (zero? n)
current
(fib-iter (+ next current) current (- n 1))))
There are instances where this isn't true. For instance Standard Lisp (warning, PDF link) defined mapcar so that the list being mapped over was the first argument with the function being mapped the second. This means you can't extend it in the way it has been extended for more recent dialects, so that it takes any positive number of lists with the function being applied to the
corresponding elements of all the lists.
Similarly I think it would be extremely unintuitive to define the arguments of - or / the other way around.
but in many, many cases it's just a matter of making a choice and sticking to it.
The recurrence is given in an imperative form. For instance, in Common Lisp, we could use parallel assignment in the body of a loop:
(psetf a (+ a b)
b a)
To reduce confusion, we should think about this functionally and give the old and new variables different names:
a = a' + b'
b = a'
This is no longer an assignment but a pair of equalities; we are justified in using the ordinary "=" operator of mathematics instead of the assignment arrow.
The linear recursion does this implicitly, because it avoids assignment. The value of the expression (+ a b) is passed as the parameter a. But that's a fresh instance of a in new scope which uses the same name, not an assignment; the binding just induces the two to be equivalent.
We can see it also like this with the help of a "Fibonacci slide rule":
1 1 2 3 5 8 13
----------------------------- <-- sliding interface
b' a'
b a
As we calculate the sequence, there is a two-number window whose entries we are calling a and b, which slides along the sequence. You can read the equalities at any position directly off the slide rule: look, b = a' = 5 and a = b' + a' = 8.
You may be confused by a referring to the higher position in the sequence. You might be thinking of this labeling:
1 1 2 3 5 8 13
------------------------
a' b'
a b
Indeed, under this naming arrangement, now we have b = a' + b', as you expect, and a = b'.
It's just a matter of which variable is designated as the leading one farther along the sequence, and which is the trailing one.
The "a is leading" convention comes from the idea that a is before b in the alphabet, and so it receives the newer "updates" from the sequence first, which then pass off to b.
This may seem counterintuitive, but such a pattern appears elsewhere in mathematics, such as convolution of functions.

Scheme Function (DrRacket)

So, i'm trying to write the following function in scheme, and to be able to run it on DrRacket. The problem is as follows,
make5 - takes two integers, and returns a 5-digit integer constructed of the rightmost 3 digits of the first input, and the leftmost 2 digits of the second input. For example, (make5 561432 254) would return 43225.
Negative signs on either input number should be ignored - that is, (make5 561432 -254) would also return 43225.
If the first number has less than three digits or the last three digits start with zeros, and/or the second number has less two digits, your
function should return -2. Note: you may want to define some auxiliary functions.
So far this is the function I've been able to write.
(define (make5 x y)
(cond ((< (length x) 3) -2)
((< (length y) 2) -2)
(((modulo (abs(x)) 1000) 0) -2)
(((modulo (abs(y)) 1000) 0) -2)
(else (append (list-tail x 3) (cons (first(y)second(y)))))))
I'm getting the error...
application: not a procedure;
expected a procedure that can be applied to arguments
Any advice would be appreciated. I'm new to scheme and still trying to grasp everything.
Don't wrap your arguments in parentheses - (abs(x)) means "call the procedure x and pass the result to abs.
(cons (first(y)second(y)) means "cons these four things: the value of first; the result of calling the procedure y; the value of second; and the result of calling the procedure y".
(You've called procedures correctly in some places. Stick to the same pattern.)
You're also missing a comparison in a couple of conditions; (= (modulo (abs x) 1000) 0).
The inputs are not lists, they're integers, so you can't apply length, first, or any such things to them.
The result should be an integer, not a list, so you can't construct it using append and cons, you should only use arithmetic.
These facts about integers should get you started:
A number has fewer than five digits if it is smaller than 10000.
The last four digits of a non-negative number n is (modulo n 10000).
If x is 12 and y is 34, x * 100 + y is 1234.
To get the three leftmost digit in an integer, you can divide by 10 repeatedly until you have a number less than 1000.
Also note that the second number only has one condition on its digits while the first has two, and that the note about defining auxiliary functions was not left there as a challenge for you to do without them.
For instance, if you had the auxiliary functions
(left-digits n x), which produces the leftmost n digits of x, and
(right-digits n x), which produces the rightmost n digits of x
you could write (it's also probably not a coincidence that the description uses the words "if" and "or"):
(define (make5 x y)
(if (or ( ... ))
-2
(+ (* 100 (right-digits 3 x)) (left-digits 2 y))))
Since you want to ignore the sign of the numbers, it's convenient to take care of abs once at the start, using let:
(define (make5 signed-x signed-y)
(let ((x (abs signed-x))
(y (abs signed-y)))
(if (or ( ... ))
-2
(+ (* 100 (right-digits 3 x)) (left-digits 2 y)))))
"All" that's left now is filling in the conditions and writing the two digit-extracting functions.

Iterative tree calculation in scheme

I'm trying to implement a function defined as such:
f(n) = n if n < 4
f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) + 4f(n - 4) if n >= 4
The iterative way to do this would be to start at the bottom until I hit n, so if n = 6:
f(4) = (3) + 2(2) + 3(1) + 4(0) | 10
f(5) = f(4) + 2(3) + 3(2) + 4(1) | 10 + 16 = 26
f(6) = f(5) + 2f(4) + 3(3) + 4(2) | 26 + 2(10) + 17 = 63
Implementation attempt:
; m1...m4 | The results of the previous calculations (eg. f(n-1), f(n-2), etc.)
; result | The result thus far
; counter | The current iteration of the loop--starts at 4 and ends at n
(define (fourf-iter n)
(cond [(< n 4) n]
[else
(define (helper m1 m2 m3 m4 result counter)
(cond [(= counter n) result]
[(helper result m1 m2 m3 (+ result m1 (* 2 m2) (* 3 m3) (* 4 m4)) (+ counter 1))]))
(helper 3 2 1 0 10 4)]))
Several problems:
The returned result is one iteration less than what it's supposed to be, because the actual calculations don't take place until the recursive call
Instead of using the defined algorithm to calculate f(4), I'm just putting it right in there that f(4) = 10
Ideally I want to start result at 0 and counter at 3 so that the calculations are applied to m1 through m4 (and so that f(4) will actually be calculated out instead of being preset), but then 0 gets used for m1 in the next iteration when it should be the result of f(4) instead (10)
tl;dr either the result calculation is delayed, or the result itself is delayed. How can I write this properly?
I think the appropriately "Scheme-ish" way to write a function that's defined recursively like that is to use memoization. If a function f is memoized, then when you call f(4) first it looks up 4 in a key-value table and if it finds it, returns the stored value. Otherwise, it simply calculates normally and then stores whatever it calculates in the table. Therefore, f will never evaluate the same computation twice. This is similar to the pattern of making an array of size n and filling in values starting from 0, building up a solution for n. That method is called dynamic programming, and memoization and dynamic programming are really different ways of looking at the same optimization strategy - avoiding computing the same thing twice. Here's a simple Racket function memo that takes a function and returns a memoized version of it:
(define (memo f)
(let ([table (make-hash)])
(lambda args
(hash-ref! table
args
(thunk (apply f args))))))
Now, we can write your function f recursively without having to worry about the performance problems of ever calculating the same result twice, thus going from an exponential time algorithm down to a linear one while keeping the implementation straightforward:
(define f
(memo
(lambda (n)
(if (< n 4)
n
(+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3)))
(* 4 (f (- n 4))))))))
Note that as long as the function f exists, it will keep in memory a table containing the result of every time it's ever been called.
If you want a properly tail-recursive solution, your best approach is probably to use the named let construct. If you do (let name ([id val] ...) body ...) then calling (name val ...) anywhere in body ... will jump back to the beginning of the let with the new values val ... for the bindings. An example:
(define (display-n string n)
(let loop ([i 0])
(when (< i n)
(display string)
(loop (add1 i)))))
Using this makes a tail-recursive solution for your problem much less wordy than defining a helper function and calling it:
(define (f n)
(if (< n 4)
n
(let loop ([a 3] [b 2] [c 1] [d 0] [i 4])
(if (<= i n)
(loop (fn+1 a b c d) a b c (add1 i))
a))))
(define (fn+1 a b c d)
(+ a (* 2 b) (* 3 c) (* 4 d)))
This version of the function keeps track of four values for f, then uses them to compute the next value and ditches the oldest value. This builds up a solution while only keeping four values in memory, and it doesn't keep a huge table stored between calls. The fn+1 helper function is for combining the four previous results of the function into the next result, it's just there for readability. This might be a function to use if you want to optimize for memory usage. Using the memoized version has two advantages however:
The memoized version is much easier to understand, the recursive logic is preserved.
The memoized version stores results between calls, so if you call f(10) and then f(4), the second call will only be a table lookup in constant time because calling f(10) stored all the results for calling f with n from 0 to 10.

Racket - creating a water density function with certain restrictions

I am attempting to solve the following problem:
Lately, Finn has been very curious about buckets of ice water and their properties. He has been reviewing the density of water and ice. It turns out the density of water in both states depends on many factors, including the temperature, atmospheric pressure, and the purity of the water.
As an approximation, Finn has written the following function to determine the density of the water (or ice) in kg/m3 as a function of temperature t in Celsius (−273.15 ≤ t ≤ 100):
water-density(t) = ( 999.97 if t ≥ 0 ;
916.7 if t < 0 )
Write a function water-density that consumes an integer temperature t and produces either 999.97 or 916.7, depending on the value of t. However, you may only use the features of Racket given up to the end of Module 1.
You may use define and mathematical functions, but not cond, if, lists, recursion, Booleans, or other things we’ll get to later in the course. Specifically, you may use any of the functions in section 1.5 of this page: http://docs.racket-lang.org/htdp-langs/beginner.html except for the following functions, which are not allowed: sgn, floor, ceiling, round.
This is what I have so far:
(define (water-density t)
(+ (* (/ (min t 0) (min t -0.000001)) -83.27) 999.97))
This code does definitely work as long as the given temperature is not between -0.000001 and 0, but it will not work for temperatures between that range. What can I do to avoid this problem? Dividing by zero is the biggest problem I have here.
This is a somewhat.... interesting way of going about teaching programming, and I have a feeling this class is going to cause more StackOverflow questions to appear in the future, but you can do it by combining max and min to make a function that returns either 1 or 0 depending on whether its input is negative:
(define (negative->boolint n))
(- 0
(min 0
(max (inexact->exact (floor n))
-1))))
This function takes a number, rounds it down with (inexact->exact (floor n)), then the combination of max and min "bounds" the number to be between -1 and 0, then subtracts that result from 1. Since after conversion to an integer the number can never be between -1 and 0, the bounding just results in 0 for positives and zero and -1 negatives. The subtraction part means the function returns (- 0 0) for all positive numbers and zero and returns (- 1 -1) for all negative numbers. By combining the result of this function with some arithmetic, you can get the behavior you want:
(define (water-density t)
(- 999.97
(* 83.27
(negative->boolint t))))
If t is positive or zero, then the result of (* 83.27 (negative->boolint t)) will just be zero. Otherwise, the difference of the two densities will be subtracted, giving you the correct result.
This works because it's just taking advantage of max and min's built-in conditional functionality to do conditional arithmetic. You could probably achieve the same with some level of hackery for round or abs or other statements that have conditional logic.
EDIT
My apologies, I missed the part of your question about not being able to use the rounding functions. Want you want is still doable however, by using two base functions for simulating conditionals: abs and expt. Getting conditionals from abs is fairly straightforward, you can divide a number by its absolute value to get it's sign. The reason you need expt is because it lets you get around the division by zero issue with abs, because (expt 0 x) is 0 for all positive numbers, 1 for zero, and undefined for negative numbers. We can use this to make a zero->boolint function:
(define (zero->boolint x)
(expt 0 (abs x)))
With this, we can add its result to the numerator and denominator to get around division by zero in (/ x (abs x)). Since this causes the division by zero case to return 1, we now have a nonnegative->boolint function:
(define (nonnegative->boolint x)
(/ (+ 1
(/ (+ (zero->boolint x) x)
(+ (zero->boolint x) (abs x))))
2))
The inner division takes care of dividing a number by its absolute value to return -1 for negatives and 1 for positives and zero. The outer addition by 1 and then division by 2 turns this into 0 for negatives and 1 for positives and zero. In order to get a negative->boolint function, we just need some sort of not operation - which in the case of 1 for true and 0 for false is just subtracting the value from 1. So we can define negative->boolint based on only the conditional logic of abs and expt as:
(define (negative->boolint x)
(- 1 (nonnegative->boolint x))
This works as expected with the definition of water-density. Also, please don't ever do this in real world code. No matter how "clever" it may seem at the time.

how to take apart numbers into integer & fractional part in scheme?

I want a function number->second-pair that accepts a number and returns a pair of integer representing its integer part & fractional part multipled with 1000000.
i.e.:
(number->second-pair 1)
; returns (1 . 0)
; 1 sec -> (1 sec + 0 usec)
(number->second-pair 5.1234)
; returns (5 . 123400)
; 5.1234 sec -> (5 sec + 123400 usec)
It might be easy for you to find a solution, but I've searched many docs and sadly can't find the way to convert numbers to integers. Can someone help me out?
BTW:
Actually I want a preciser alarm(this one) by making use of setitimer, so I want exact integers passed as arguments.
I may be a bit rusty with scheme but I think something like this would work for you,
(define (number->second-pair n)
(cons (inexact->exact (floor n))
(inexact->exact (floor (* 1000000 (- n (floor n)))))))
(number->second-pair 5.1234) returns (5 . 123400)
(number->second-pair 1) returns (1 . 0)

Resources