How to count square matrix represented as vectors in clojure - vector

Assume that a two-dimensional matrix is represented as a vector of
vectors, such that the innermost vectors each represent a row in the
matrix . A two-dimensional matrix is square if the number of rows is equal
to the number of columns.

Why the loop-recur constraint?
If you can assume every row is the same size (regular structure), this would work:
(defn is-square [m]
(= (count m) (count (first m))))
If you want to check every row:
(defn is-square [m]
(apply = (count m) (map count m)))
If you really really want to use loop-recur for some reason:
(defn is-square [m]
(loop [[row & more] m]
(if row
(if (= (count row) (count m))
(recur more)
false)
true)))

Related

Finding Amount of Divisors

I need to write a function in #lang racket that determines the amount of divisors a positive integer has. (Ex: 6 has 4 divisors; 1,2,3,6)
So far I have:
(define (divides a b) (if (= 0 (modulo a b)) #t #f))
I need to use this helper function to write the function (divisors-upto n k) that that computes the number of divisors n has between 1 and k (so it computes the number of divisors of n
up to the value k).
This is easiest done1 with a for loop, in particular for/fold, given that you already have your divides function.
(define (divisors num)
(for/fold ([acc 0]
[n (in-range num)])
(if (divides n num) <acc+1> <acc>)))
Basically, you are looping over the list, and keeping an accumulator, and whenever a number is dividable, increment your accumulator. See if you can fill in the expressions for <acc+1> and <acc> in the code above.
1You could also do this with list length and filter. See if you can figure out how.

Create a list of binary trees with max height n

A node is a
(define-struct node (left right))
A leafy binary tree (LBT) is one of
; - 'leaf
; - (make-node LBT LBT)
I have to design a function that takes in a natural number n and creates a list of all leafy binary trees that have height n.
So for example, a height of 2 should return:
`(list
(make-node 'leaf (make-node 'leaf 'leaf))
(make-node (make-node 'leaf 'leaf) 'leaf)
(make-node (make-node 'leaf 'leaf) (make-node 'leaf 'leaf)))`
I've been stuck on this assignment for days now. The best I could come up with was:
`(define (lbt-list n)
(cond [(= 0 n) 'leaf]
[(= 1 n) (cons (make-node (lbt-list (- n 1)) (lbt-list (- n 1))) empty)]
[else (list (make-node (first (lbt-list (- n 1))) (lbt-list (- n n)))
(make-node (lbt-list (- n n)) (first (lbt-list (- n 1))))
(make-node (first (lbt-list (- n 1))) (first (lbt-list (- n 1)))))]))`
The problem involves recursion and I'm just not sure how to fully code out this function. Any help would be appreciated!
You are trying to make nodes out of lists; the only valid arguments to make-node are leafs and nodes. Instead, you should take the results of lbt-list and use each of its elements to make each of the nodes for the list to be returned.
Also, you never use the rest of any returned lbt-list.
To start, the reason why you're only getting three trees is that your else clause calls list with exactly three instances of make-node. This might be a little easier to see if you make (= n 1) your base case, and explicitly use 'leaf wherever you need it, instead of (lbt-list (- n n)).
I think you'll benefit from stepping back from the code for a second and asking yourself what mathematical products you're trying to generate. In particular, how do you get the n-depth binary trees from the (n-1)-depth binary trees?
It's simplest to break it into three parts. Here are two big hints:
is make-node commutative?
how is the level-on-level generation related to a Cartesian product?
Finally, helper functions are your friend here - they'll go a long way towards dividing the mental burden of generating the list into smaller pieces. I wrote three helper functions when I threw together a solution, but you might be able to make do with two.

How to check if a matrix is upper-triangular in clojure

I want to write a function to compute upper triangular nature of matrix. So lets say a_i_j be the number in the i^th row and j^th column. A matrix is
upper-triangular if a_i_j = 0 for all i > j.
Try this:
(defn is-upper-triangular [m]
(->> (map-indexed vector m)
(mapcat (fn [[r v]] (take r v)))
(every? zero?)))
The above code take 0 element from the first row, 1 element from the second row, and 2 elements from the third rows, etc... and checks that all the taken elements are zero. If all are zero, it is upper triangular.
This code does not check that the given matrix is square. You can add this check if it is necessary.
upper-triangular? isn't in the core.matrix API yet, but if you use vectorz-clj you can get at the function with Java interop:
(def a (array :vectorz [[1 2] [0 4]]))
(.isUpperTriangular a)
=> true
(.isUpperTriangular (transpose a))
=> false

Build lazy-seq by multiplying previous term by constant

I'm starting out with Clojure and, despite having an understanding of recursion, am having trouble thinking of the "right" way to build a lazy-seq for the following function:
I want to build a list of all the frequencies starting from middle C. My first element would be 120 (the frequency of middle C). To get the second element, I'd multiply the first element, 120, by 1.059463 to get 127.13556. To the get the third I'd multiply the second element, 127.13556, by 1.059463, etc etc...
What's the best way to do this in Clojure?
You can use the iterate function for that.
(iterate #(* % 1.059463) 120)
If you are planning to expand this into something more complicated, then you would create a function that recursive calls itself inside a call to lazy-seq. (This is what iterate does internally.)
(defn increasing-frequencies
([] (increasing-frequencies 120))
([freq]
(cons freq (lazy-seq (increasing-frequencies (* freq 1.059463))))))
(nth (increasing-frequencies) 2) ;; => 134.69542180428002
If you start to use this in a tight loop, you may also want to generate a chunked lazy seq. This will pre-calculate the next few elements, instead of one by one.
(defn chunked-increasing-frequencies
([] (chunked-increasing-frequencies 120))
([freq]
(lazy-seq
(let [b (chunk-buffer 32)]
(loop [i freq c 0]
(if (< c 32)
(do
(chunk-append b i)
(recur (* i 1.059463) (inc c)))
(chunk-cons (chunk b) (chunked-increasing-frequencies i))))))))
Note: I would advise against doing this until you have measured a performance problem related to calculating individual elements.
(defn get-frequencies []
(iterate #(* 1.059463 %) 120))
See iterate
Or, if you want to use lazy-seq explicitly, you can do this:
(defn get-frequencies-hard []
(cons
120
(lazy-seq
(map #(* 1.059463 %) (get-frequencies-hard)))))
Which will cons 120 to a lazy seq of every value applied to the map function.

Count amount of odd numbers in a sentence

I am fairly new to lisp and this is one of the practice problems.
First of all, this problem is from simply scheme. I am not sure how to answer this.
The purpose of this question is to write the function, count-odd that takes a sentence as its input and count how many odd digits are contained in it as shown below:
(count-odd'(234 556 4 10 97))
6
or
(count-odd '(24680 42 88))
0
If possible, how would you be able to do it, using higher order functions, or recursion or both - whatever gets the job done.
I'll give you a few pointers, not a full solution:
First of all, I see 2 distinct ways of doing this, recursion or higher order functions + recursion. For this case, I think straight recursion is easier to grok.
So we'll want a function which takes in a list and does stuff, so
(define count-odd
(lambda (ls) SOMETHING))
So this is recursive, so we'd want to split the list
(define count-odd
(lambda (ls)
(let ((head (car ls)) (rest (cdr ls)))
SOMETHING)))
Now this has a problem, it's an error for an empty list (eg (count-odd '())), but I'll let you figure out how to fix that. Hint, check out scheme's case expression, it makes it easy to check and deal with an empty list
Now something is our recursion so for something something like:
(+ (if (is-odd head) 1 0) (Figure out how many odds are in rest))
That should give you something to start on. If you have any specific questions later, feel free to post more questions.
Please take first into consideration the other answer guide so that you try to do it by yourself. The following is a different way of solving it. Here is a tested full solution:
(define (count-odd num_list)
(if (null? num_list)
0
(+ (num_odds (car num_list)) (count-odd (cdr num_list)))))
(define (num_odds number)
(if (zero? number)
0
(+ (if (odd? number) 1 0) (num_odds (quotient number 10)))))
Both procedures are recursive.
count-odd keeps getting the first element of a list and passing it to num_odds until there is no element left in the list (that is the base case, a null list).
num_odds gets the amount of odd digits of a number. To do so, always asks if the number is odd in which case it will add 1, otherwise 0. Then the number is divided by 10 to remove the least significant digit (which determines if the number is odd or even) and is passed as argument to a new call. The process repeats until the number is zero (base case).
Try to solve the problem by hand using only recursion before jumping to a higher-order solution; for that, I'd suggest to take a look at the other answers. After you have done that, aim for a practical solution using the tools at your disposal - I would divide the problem in two parts.
First, how to split a positive integer in a list of its digits; this is a recursive procedure over the input number. There are several ways to do this - by first converting the number to a string, or by using arithmetic operations to extract the digits, to name a few. I'll use the later, with a tail-recursive implementation:
(define (split-digits n)
(let loop ((n n)
(acc '()))
(if (< n 10)
(cons n acc)
(loop (quotient n 10)
(cons (remainder n 10) acc)))))
With this, we can solve the problem in terms of higher-order functions, the structure of the solution mirrors the mental process used to solve the problem by hand:
First, we iterate over all the numbers in the input list (using map)
Split each number in the digits that compose it (using split-digits)
Count how many of those digits are odd, this gives a partial solution for just one number (using count)
Add all the partial solutions in the list returned by map (using apply)
This is how it looks:
(define (count-odd lst)
(apply +
(map (lambda (x)
(count odd? (split-digits x)))
lst)))
Don't be confused if some of the other solutions look strange. Simply Scheme uses non-standard definitions for first and butfirst. Here is a solution, that I hope follows Simply Scheme friendly.
Here is one strategy to solve the problem:
turn the number into a list of digits
transform into a list of zero and ones (zero=even, one=odd)
add the numbers in the list
Example: 123 -> '(1 2 3) -> '(1 0 1) -> 2
(define (digit? x)
(<= 0 x 9))
(define (number->digits x)
(if (digit? x)
(list x)
(cons (remainder x 10)
(number->digits (quotient x 10)))))
(define (digit->zero/one d)
(if (even? d) 0 1))
(define (digits->zero/ones ds)
(map digit->zero/one ds))
(define (add-numbers xs)
(if (null? xs)
0
(+ (first xs)
(add-numbers (butfirst xs)))))
(define (count-odds x)
(add-numbers
(digits->zero/ones
(number->digits x))))
The above is untested, so you might need to fix a few typos.
I think this is a good way, too.
(define (count-odd sequence)
(length (filter odd? sequence)))
(define (odd? num)
(= (remainder num 2) 1))
(count-odd '(234 556 4 10 97))
Hope this will help~
The (length sequence) will return the sequence's length,
(filter proc sequence) will return a sequence that contains all the elements satisfy the proc.
And you can define a function called (odd? num)

Resources