r/RacketHomeworks • • Nov 18 '22

The Nine Languages You Should Learn After Racket

3 Upvotes

Sure, Lisps are great for helping you think about language like a parser, and all kinds of other things, but one language can only teach you so much.

  1. Forth - now that we've spent all this time writing tail-recursive code to keep things of the stack, why not try a stack-based language where we can play around with the stack, and stacks, not lists, are the essential data structure? And with suffix instead of prefix notation, there's no need for parens!

  2. APL - Now that we've done list and stack-based languages, let's move on to one that is array-oriented, and sees itself as an extension of mathematical notation. This leads to very succinct programs, and this economy can have it's own kind of elegance.

  3. Prolog - Logic programming: what is it? How does it work? Is it like HTML for programs? Am I ever going to say anything here? No! The computer will figure it out!

  4. Haskell - Pure functions, static types- minimal state. Take functional programming to its extreme (or was that prolog?)

  5. RISC-V Hey, if we want to get any work done, eventually we have to talk to the hardware

  6. C - Pointers!

  7. Smalltalk - objects! Now that we're out of functional world see how great the world can be when everything is an object!

  8. Scratch - Visual! Events! If you're young enough, you may have already had this one.

  9. Vimscript - When the perfect tool needs the perfect language- yay!


r/RacketHomeworks • • Nov 29 '22

Inserting an element in the list to the left (and to the right) of the given element

0 Upvotes

Problem: write a function insert-right-once, that receives three parameters: symbols new and old and list xs. The function should return a new list, which is the same as xs, except that immediately after the first occurrence of the symbol old, the symbol new should be inserted into xs. For example, the call (insert-right-once 'x 'c '(a b c d c b a)) should return a list (a b c x d c b a).

Also, write the function insert-left-once that does the same thing, only from the left.

And finally, write the function insert-right-many that inserts the symbol new immediately after each occurrence of the symbol old. Also, write the insert-left-many function that does the analog thing from the left.

Solution:

#lang racket

(define (insert-right-once new old xs)
  (cond [(null? xs) '()]
        [(eq? (car xs) old)
         (cons old (cons new (cdr xs)))]
        [else (cons (car xs) (insert-right-once new old (cdr xs)))]))

(define (insert-left-once new old xs)
  (cond [(null? xs) '()]
        [(eq? (car xs) old)
         (cons new xs)]
        [else (cons (car xs) (insert-left-once new old (cdr xs)))]))

(define (insert-right-many new old xs)
  (cond [(null? xs) '()]
        [(eq? (car xs) old)
         (cons old (cons new (insert-right-many new old (cdr xs))))]
        [else (cons (car xs) (insert-right-many new old (cdr xs)))]))

(define (insert-left-many new old xs)
  (cond [(null? xs) '()]
        [(eq? (car xs) old)
         (cons new (cons old (insert-left-many new old (cdr xs))))]
        [else (cons (car xs) (insert-left-many new old (cdr xs)))]))

Now we can try those functions, for example, like this:

> (insert-right-once 'x 'c '(a b c d c b a))
'(a b c x d c b a)
> (insert-right-many 'x 'c '(a b c d c b a))
'(a b c x d c x b a)
> (insert-left-once 'x 'c '(a b c d c b a))
'(a b x c d c b a)
> (insert-left-many 'x 'c '(a b c d c b a))
'(a b x c d x c b a)

r/RacketHomeworks • • Nov 18 '22

Find all factors of the given natural number

0 Upvotes

Problem: Define a procedure, factors, that takes as input an natural number and outputs a list containing all the factors of that number.

Solution:

#lang racket

(define (factors n)
  (define (factor-helper k)
    (cond [(> k n) '()]
          [(zero? (remainder n k)) (cons k (factor-helper (+ k 1)))]
          [else (factor-helper (+ k 1))]))
  (factor-helper 1))

Now, we have:

> (factors 100)
'(1 2 4 5 10 20 25 50 100)

This is correct but slow. We can write faster procedure if we notice that it's enough to go only to sqrt(n):

(define (factors n)
  (define (f-helper i fl fr)
    (if (> (* i i) n)
        (append (reverse fl) fr)
        (let-values ([(q r) (quotient/remainder n i)]) 
          (if (zero? r)
              (if (= i q)
                  (f-helper (+ i 1) fl (cons i fr))
                  (f-helper (+ i 1) (cons i fl) (cons q fr)))
              (f-helper (+ i 1) fl fr)))))
    (f-helper 1 '() '()))

r/RacketHomeworks • • Nov 27 '22

Comparing curl and mit-scheme as projects tells us why the first is successful and the second is not

0 Upvotes

Someone will say that mit-scheme and the curl project have almost nothing in common. And that's kind of true. And yet, when you look a little closer, you can see that those two projects actually have one thing in common: both projects have only one single person who is the maintainer of the entire project. In the case of the mit-scheme it's Chris Hanson, and in the case of the curl project it's Daniel Stenberg. There is no big (or even small) team in either of these two projects - just one man, each of them is capo di tutti capi in his own project, so to speak.

And yet, the difference in approach, seriousness and responsibility of these two men is drastic: while Daniel Stenberg tries to make curl work well on as many platforms as possible (please see this link where Stenberg proudly and quite rightly boasts that curl works on 89 operating systems!), our "hero" Chris Hanson, on the other hand , tries to achieve the exact opposite: to make mit-scheme work on as few platforms as possible!

Indeed, what should we think when the main maintainer writes literally this on the home page of mit-scheme, I quote:

"We no longer support OS/2, DOS, or Windows, although it's possible that this software could be used on Windows Subsystem for Linux (we haven't tried)."

This Hanson's inimitable "we haven't tried" blew me away!

And more:

"No support for Apple silicon: At this time, we are unable to support new macs using Apple's silicon (the M1 chip)."

And more:

"We also no longer distribute macos applications..."

Well done Hanson, keep it up!

So, while Daniel Stenberg is trying hard and it is really important to him that his project works everywhere and that it works well, Chris Hanson, quite the opposite, immaturely and pubescently, even brags that he hasn't even tried whether the mit-scheme works on the Windows Subsystem for Linux! Although, by nature of his job, it should certainly be one of his main preoccupations! Also, he is not upset at all by the fact that the mit-scheme does not work on native Windows, that it does not work on the new Mac, that there is no installer for macos, and so on, although all this existed before, but disappeared due to carelessness and neglect!

And right there, my dear schemers, is hidden the main reason why curl is a successful project that grows and develops, while mit-scheme is an unsuccessful project that not only does not progress but very obviously fails!


r/RacketHomeworks • • Nov 18 '22

How to calculate double integral?

0 Upvotes

Problem: calculate double integral of given real function F:R^2 -> R

Solution:

#lang racket

(define (accumulate op nv a b term next)
  (if (> a b) nv
      (op (term a) 
          (accumulate op nv (next a) b term next))))

(define (integral a b f dx)
  (* dx (accumulate + 0 a b f (lambda (x) (+ x dx)))))

(define (integrate2 f a b c d dx dy)
  (integral a b (lambda (x) (integral c d (lambda (y) (f x y)) dy)) dx))

(define (f x y)
  (* 9 x x x y y))

Now, we can try to calculate this integral, for example:

We can do that easily:

> (integrate2 f 1 3 2 4 0.001 0.001)
3364.15365622111

That's OK, since the exact result of this integral is 3360 (see exact calculation here)


r/RacketHomeworks • • Nov 27 '22

Rendering xexpr scheme representation of web page to html

0 Upvotes

Problem: Lists in Scheme are well-known to be suitable for holding various types of (hierarchical) data structures, including html documents.

For example, this html document

<html lang="en">
  <head>
    <title>Racket Homeworks subreddit</title>
  </head>
  <body class="container fancy" width="800px">
    <p>Hi guys!</p>
    <p style="color:red">Subreddit <a href="https://reddit.com/r/RacketHomeworks">RacketHomeworks</a> rulez!</p>
  </body>
</html>

can be represented using this nested list in scheme (which we call xexpr) as follows:

'(html (@ lang "en")
   (head
     (title "Racket Homeworks subreddit"))
   (body (@ class "container fancy"
            width "800px")
     (p "Hi guys!")
     (p (@ style "color:red") "Subreddit "
        (a (@ href "https://reddit.com/r/RacketHomeworks") " RacketHomeworks")
         " rulez!"))))

Task: write a function render-html that receives the xexpr of an html document representation as an input parameter, and prints to the standard output the html representation of that document, suitable for rendering in a web browser.

Solution:

#lang racket

(define (render-html xexpr)
  (cond [(pair? xexpr)
         (let ([tag (car xexpr)]
               [attrs (get-attribs xexpr)])
           (display "<")
           (display tag)
           (when attrs (render-attrs attrs))
           (display ">")
           (for-each (lambda (x) (render-html x))
                     (if attrs (cddr xexpr) (cdr xexpr)))
           (display "</")
           (display tag)
           (display ">"))]
        [else (display xexpr)]))
        
(define (get-attribs tag)
  (and (not (null? (cdr tag)))
       (pair? (cadr tag))
       (eq? '@ (caadr tag))
       (cdadr tag)))

(define (render-attrs attrs)
  (unless (null? attrs)
    (display " ")
    (display (car attrs))
    (display "=\"")
    (display (cadr attrs))
    (display "\"")
    (render-attrs (cddr attrs))))

Now, we can use render-html, like this:

> (define mypage
   `(html (@ lang en)
     (head
      (title "Racket Homeworks subreddit"))
     (body (@ class "container fancy"
              width "800px")
       (p "Hi guys!")
       (p (@ style "color:red") "Subreddit "
          (a (@ href "https://reddit.com/r/RacketHomeworks") "RacketHomeworks")
         " rulez!"))))

> (render-html mypage)

<html lang="en"><head><title>Racket Homeworks subreddit</title></head><body class="container fancy" width="800px"><p>Hi guys!</p><p style="color:red">Subreddit <a href="https://reddit.com/r/RacketHomeworks">RacketHomeworks</a> rulez!</p></body></html>

r/RacketHomeworks • • Nov 29 '22

Operations with numbers in unary numeral system

0 Upvotes

Problem: In this problem, you need to write several functions for working with numbers written in the so-called unary numeral system. In this system, the natural number n is written as a list of n symbols 1. E.g. the number 5 would be written as '(1 1 1 1 1).

  1. Write the functions decimal->unary and unary->decimal that converts a natural number written in ordinary decimal representation into unary notation and vice versa, respectively.

  2. Write the functions unary-add1 and unary-sub1 that add and subtract number 1 from the given number in the unary representation, respectively

  3. Using the functions defined in 2., write the functions unary+ and unary- which receive as input two numbers in unary representation and as a result return their sum and difference respectively, also in unary representation

  4. Write a unary* function that multiplies two unary numbers

  5. Write a function unary-pow that receives two unary numbers a and b and returns the number ab in unary notation.

Solution:

#lang racket

(define (decimal->unary d)
  (if (zero? d)
      '()
      (cons 1 (decimal->unary (- d 1)))))

(define (unary->decimal u)
  (if (null? u)
      0
      (+ 1 (unary->decimal (cdr u)))))

(define (unary-add1 u)
  (cons 1 u))

(define (unary-sub1 u)
  (if (null? u)
      (error "Cannot subtract 1 from zero!")
      (cdr u)))

(define (unary+ u1 u2)
  (if (null? u2)
      u1
      (unary+ (unary-add1 u1) (unary-sub1 u2))))

(define (unary- u1 u2)
  (if (null? u2)
      u1
      (unary- (unary-sub1 u1) (unary-sub1 u2))))

(define (unary* u1 u2)
  (if (null? u1)
      '()
      (unary+ (unary* (unary-sub1 u1) u2) u2)))

(define (unary-pow u1 u2)
  (if (null? u2)
      (cons 1 '())
      (unary* u1 (unary-pow u1 (cdr u2)))))

Now we have, for example, this calculation:

> (unary-add1 '(1 1 1))
'(1 1 1 1)
> (unary-sub1 '(1 1 1))
'(1 1)
> (unary+ '(1 1 1) '(1 1))
'(1 1 1 1 1)
> (unary- '(1 1 1 1 1) '(1 1 1))
'(1 1)
> (unary* '(1 1 1 1) '(1 1 1))
'(1 1 1 1 1 1 1 1 1 1 1 1)
> (unary-pow '(1 1) '(1 1 1))
'(1 1 1 1 1 1 1 1)
> (unary->decimal (unary-pow '(1 1) '(1 1 1)))
8
> (decimal->unary 7)
'(1 1 1 1 1 1 1)

r/RacketHomeworks • • Dec 24 '22

How to draw the official Racketfest flag?

1 Upvotes

Problem: As we know, Jesse Alama's Racketfest is approaching, so it's time to make the nice official flag for that important event. In this problem, your task is to design and draw in Racket the official Racketfest flag.

Solution: The solution is simple and elegant and really reflects the true character of this event:

#lang racket

(require lang/posn)
(require 2htdp/image)

(define BLUE (color 0 51 153))
(define GOLD (color 255 204 0))

(define (racketfest-flag width)
  (define WIDTH width)
  (define HEIGHT (* WIDTH 2/3))
  (define UNIT (/ HEIGHT 2))
  (define ANGLE (/ pi 6))
  (define STARS-NUM 12)
  (define CENTER-X (/ WIDTH 2))
  (define CENTER-Y (/ HEIGHT 2))
  (define STAR-SIDE-LEN (* 2/9 UNIT (sin (/ pi 5))))
  (define A-STAR (text "95 €" 25 GOLD))
  (define 12-STARS (make-list STARS-NUM A-STAR))

  (define star-posns
    (for/list ([i (range 0 STARS-NUM)])
      (make-posn (+ CENTER-X (* 2/3 UNIT (sin (* ANGLE i))))
                 (+ CENTER-Y (* 2/3 UNIT (cos (* ANGLE i)))))))

  (place-images
   12-STARS
   star-posns
   (rectangle WIDTH HEIGHT 'solid BLUE)))

Now we can call our racketfest-flag function to draw the official Racketfest flag:

> (racketfest-flag 600)

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Aug 11 '24

Calculating the Reduced Row Echelon Form (RREF) of a given matrix

1 Upvotes

Problem: One of the most common operations in linear algebra is reducing a matrix to the so-called "reduced row echelon form" (RREF).

By using this operation (more information can be found in this video: https://www.youtube.com/watch?v=1rBU0yIyQQ8), one can easily solve a system of linear equations, find the inverse of a matrix, check the linear dependence/independence of a given set of vectors, find the basis of the row space, basis of the column space of the matrix, etc. Overall, it is a very useful operation in linear algebra.

Write a Racket program that calculates the RREF for a given matrix M.

Solution:

#lang racket

(define (matrix xxs)
  (apply vector (map list->vector xxs)))

(define (matrix-set! mat i j v)
  (vector-set! (vector-ref mat i) j v))

(define (matrix-get mat i j)
  (vector-ref (vector-ref mat i) j))

; scale row i of matrix mat by a (nonzero) number num:  num * r_i --> ri
(define (scale-row mat i num)
  (let ([rowv (vector-ref mat i)])
    (for ([j (range (vector-length rowv))])
      (matrix-set! mat i j (* num (vector-ref rowv j))))))

; swap rows i and j of matrix mat:  r_i <--> r_j
(define (swap-rows mat i j)
  (let ([rowi (vector-ref mat i)]
        [rowj (vector-ref mat j)])
    (vector-set! mat i rowj)
    (vector-set! mat j rowi)))

; add a multiple of row j to row i: r_i + num * r_j --> r_i
(define (add-row-multiple mat i j num)
  (let ([rowi (vector-ref mat i)]
        [rowj (vector-ref mat j)])
    (for ([k (range (vector-length rowi))])
      (matrix-set! mat i k (+ (vector-ref rowi k) (* num (vector-ref rowj k)))))))

; this is the main function for calculating the REF or RREF of a given matrix mat
; if parameter rref? is set to #t then RREF of matrix mat is calculated
; if parameter rref? is set to #f then REF of matrix mat is calculated
(define (reduce-matrix mat [rref? #t])
  (define m (vector-length mat))
  (define n (vector-length (vector-ref mat 0)))
  (define r -1)
  (for ([j (range 0 n)])
    (let ([i (+ r 1)])
      (let loop ()
        (when (and (< i m) (zero? (matrix-get mat i j)))
          (set! i (+ i 1))
          (loop)))
      (when (< i m)
        (set! r (+ r 1))
        (swap-rows mat r i)
        (scale-row mat r (/ 1 (matrix-get mat r j))) 
        (for ([k (range (+ r 1) m)])
          (add-row-multiple mat k r (- (matrix-get mat k j))))
        (when rref?
          (for ([k (range 0 r)])
            (add-row-multiple mat k r (- (matrix-get mat k j)))))))))

(define (ref mat)
  (reduce-matrix mat #f))

(define (rref mat)
  (reduce-matrix mat #t))

Now we can test our program on the example of the same matrix shown in the video. We can see that we get the same result as in the video:

> (define M (matrix '((1 2 3 4)
                      (4 5 6 7)
                      (6 7 8 9))))
> (rref M)
> M
'#(#(1 0 -1 -2) 
   #(0 1  2  3) 
   #(0 0  0  0))
> 

Note 1: The rref function modifies the input matrix in-place. Therefore, if we want to preserve the original matrix, we need to copy it before calling rref.

Note 2: In addition to the rreffunction, the above code also includes a function ref that calculates the "plain" row echelon form (not reduced).


r/RacketHomeworks • • Nov 15 '23

Congratulations to Daniel Stenberg, a kick in the butt to Chris Hanson!

2 Upvotes

Dear Schemers,

today I stumbled upon a new post by Daniel Stenberg in which he proudly highlights that his curl library now works on 100 different operating systems and 28 different CPU architectures!

It's an incredible engineering achievement and a true exemplary example of successfully leading a software project that aims to be useful to as many people on as many different machines as possible. As long as I live, I will always emphasize and praise Daniel Stenberg, who has never said something like "I'm shutting down support for Windows, those who want to run curl on Windows should use WSL, but I don't care, I haven't even tried if it works at all." You will never hear something like that from Daniel Stenberg!

But you will hear exactly that from Chris Hanson, the "maintainer" (I intentionally put it in quotes because I don't consider him a maintainer at all, but quite the opposite - he could be called a gravedigger) of the sadly regressing mit-scheme project, which runs on fewer and fewer operating systems and on fewer and fewer different CPU architectures every day!

I don't know about you, dear Schemers, but whoever I complained to about this, they all criticized me and downvoted me harshly, so I have no doubt it will be the same this time. A few days ago I even wrote a post about it on the /r/mit subreddit, where I was also ridiculed.

To me, it's incredible because MIT is the cradle of Lisp and Scheme, and they allowed their cult implementation, mit-scheme, to fall to such low levels and into the hands of completely the wrong person, inadequate for the task. MIT is full of countless intelligent hackers, programming enthusiasts, but none of them has ever felt the need to take the damn mit-scheme and lift it from the bottom and finally brighten MIT's face as an institution, which is only embarrassing itself when people see how sad the state of mit-scheme is today and in what even sadder state it will be tomorrow if nothing is done.

Yes, people: spit on me, therefore, as much as you like, but that won't erase the undeniable truth: mit-scheme is declining because of Chris Hanson and because of MIT's negligence as an institution that should (if anyone else!) nurture it like its child in the cradle!


r/RacketHomeworks • • Nov 18 '22

r/RacketHomeworks Lounge

2 Upvotes

A place for members of r/RacketHomeworks to chat with each other


r/RacketHomeworks • • Nov 18 '22

Motivation for this subreddit

6 Upvotes

Many people ask me why I started this subreddit, what is my motivation for it?

Well, I noticed that there are a lot of arrogant professors on the /r/racket subreddit who supposedly want to help students, but in reality they don't give them the right answers (or just ignore student's cry for help). And when they do respond, they just confuse and frustrate poor students with their deliberately cryptic "answers", sometimes intentionally, but mostly because (blinded by their HtDP religion) they really think that, by asking the student Socratic questions, they are helping students, which in reality is completely the opposite because the student usually becomes even more confused and loses confidence precisely because of them, when he sees what incredible smart-ass people he is surrounded by.

Those professors think that Racket and the "famous" HTDP-religion is the most important thing in the world, but in reality there are many students who don't like Racket at all but are forced to learn it. Many of them just want to get rid of it all as soon as possible. Those puffed-up professors can't possibly understand that.

And that's why this subreddit is here, to give frank and straightforward answers to everyone: both to those who love racket and those who don't and can't wait to get rid of it!

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Apr 02 '24

MIT Scheme: Negligence and Insularity - A Call to Action

4 Upvotes

Dear Redditors,

Seeing the latest post titled "How do I add R7RS libraries to MIT Scheme" (link: https://www.reddit.com/r/scheme/comments/1btm1f4/how_do_i_add_r7rs_libraries_to_mit_scheme/), I don't know whether to cry or laugh.

Sadly, I lean more towards tears, due to the truly dismal state in which one of the oldest and most renowned implementations of the Scheme programming language, "MIT Scheme," finds itself.

Actually, it didn't find itself in this state on its own; it was brought into this position by the negligence of Chris Hanson, its maintainer, and Arthur Gleckler, his sycophant who would apparently defend him even if he ran over someone with a car and fled the scene.

So, what's the issue?

In that post, a naive Redditor asks on the /r/scheme subreddit how to add an R7RS library to MIT Scheme. To which Arthur Gleckler, the eternal apologist for the current state of MIT Scheme, who thinks nothing should be changed because the state is simply ideal, says: "Use (find-scheme-libraries! ".") to register all the libraries in a directory. To import a package: ,(import (only (srfi 1) fold))**".

And I ask Arthur Gleckler now: where is that written in the MIT Scheme documentation?

Because, what he said isn't written anywhere! It's not written because the documentation hasn't been updated in the last 20 years! The culprit is the lazy Chris Hanson, who should be removed from his position as the head of this project immediately!

Arthur Gleckler uses insider information and pontificates around Reddit. For him, this state in which only he knows how to add a library to MIT Scheme is ideal! He doesn't see a problem with nobody else knowing because Chris Hanson and he made sure it stays that way forever!

And me, the only one who warned about this in a few of my posts on /r/scheme, I got banned for it and made unable to see their posts at all!

What a bunch of wretches, what pitiful individuals!

People, rise up against these people today! Because tomorrow it will be too late: if you do nothing, MIT Scheme will continue to be the private playground of Chris Hanson and Arthur Gleckler, and this duo will enjoy dominantly urinating on the rest of us, as we've had the opportunity to witness in this latest example!


r/RacketHomeworks • • Jan 17 '23

"I feel nothing but gratitude..."

1 Upvotes

I see that Gleckler and his well-oiled machine (unfortunately) continue to go down the path of self-destruction: just when I was hoping that Gleckler would come to his senses and stop publishing this shit on the scheme subreddit, today his latest "work" dawned. Work that nobody needs , nor will it ever be useful to anyone. But God forbid that someone says that truth publicly on /r/scheme. God forbid: that one would be lynched immediately, just like I was :(

Gleckler, you killed the spirit of Scheme! You and your sycophantic crew banished me from your (now we can safely say dead) sub. A sub which is dead thanks to you, not to me! I brought liveliness and discussion that interested many to /r/scheme (this can be seen by the number of comments and the total number of visits to my posts). During that time, you brought dulling and death, and in the end you removed me forever because you hate me!

I hope that you are now happy and that you enjoy the "Sound of silence" that eerily inhabits your sub all the time, sub cleansed of every discussion, confrontation, and even ordinary human conversation!

The soulless robots stole the soul of Scheme, with the wholehearted approval of the assholes who were constantly downvoted my posts and taunting me to the admins for every small stupid thing. They always saw the speck in my eye, but not the log in theirs! But, that's how it is in life!

Stinks, let me just tell you: I have done more to popularize Scheme with my concise, clear and useful posts here, in one month, than you have done with your barking at the moon in your entire life!

Enjoy on /r/scheme with your dear Gleckler who doesn't fuck you 2 percent! He just cares about having a big poop there and leaving ASAP! He doesn't care what you have to say as long as you are obedient consumers of his shit. Well then, be it!

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Jan 06 '23

Factorial digit sum

2 Upvotes

Problem: n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!, in the number 1000!, and in the number 10000!

Solution:

#lang racket

(define (factorial n)
  (foldl * 1 (range 1 (add1 n))))

(define (sum xs)
  (foldl + 0 xs))

(define (number->digits n)
   (map (lambda (c) (- (char->integer c) 48))
        (string->list (number->string n))))


(define (factorial-sum n)
  (sum (number->digits (factorial n))))

Now we can calculate desired sum of digits in 10!, 100!, 1000! and 10000! :

> (factorial-sum 10)
27
> (factorial-sum 100)
648
> (factorial-sum 1000)
10539
> (factorial-sum 10000)
149346

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Dec 13 '22

Can we sum numbers from the given list to get the given number?

1 Upvotes

Problem: Write function can-sum? which takes a nonnegative integer target-sum and the list of nonnegative integers numbers as arguments.

The function should return boolean indicating whether or not it is possible to generate the target-sum using numbers from the array as summands. You may use an element from the list numbers as many times as needed.

For example, (can-sum 7 '(2 3)) should evaluate to true, because it is possible to write 7 as 7 = 2 + 2 + 3. Also, (can-sum? 7 '(5 3 4 7)) should evaluate to true, but (can-sum? 7 '(2 4)) should evaluate to false.

Solution 1 (a bad one first):

#lang racket

(define (can-sum? target-sum numbers)
  (define (can-sum-helper target)
    (cond [(zero? target) #t]
          [(< target 0) #f]
          [else (ormap (lambda (n)
                         (can-sum-helper (- target n)))
                       numbers)]))
  (can-sum-helper target-sum))

Now we can check our solution:

> (can-sum? 7 '(2 3))
#t
> (can-sum? 7 '(5 3 4 7))
#t
> (can-sum? 7 '(2 4))
#f
> (can-sum? 8 '(2 3 5))
#t

Everything looks fine. But, if we try this:

> (can-sum? 300 '(7 14))

than our program program freezes. It simply takes too long to execute and we can't wait for it to finish. The reason is that the program has exponential time complexity. Fortunately, this problem, similarly to one of our previous problems, has an overlapping subproblems structure. Which means that in this case memoization will save the day. So, let's add memoization to our function:

Solution 2 (a good one!):

#lang racket

(define (memo f)
  (let ([lookup (make-hash)])
    (lambda x
      (unless (hash-has-key? lookup x)
        (hash-set! lookup x (apply f x)))
      (hash-ref lookup x))))

(define (can-sum? target-sum numbers)
  (define (can-sum-helper target)
    (cond [(zero? target) #t]
          [(< target 0) #f]
          [else (ormap (lambda (n)
                         (can-sum-helper (- target n)))
                       numbers)]))
  (set! can-sum-helper (memo can-sum-helper))
  (can-sum-helper target-sum))

If we now try to solve the same problem that caused us problems, we will see that now this expression will be executed practically instantly:

> (can-sum? 300 '(7 14))
#f

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Dec 03 '22

I am very sorry that Bernie Sanders did not win the 2016 presidential election

2 Upvotes

Problem: Bernie Sanders didn't win the presidential election in 2020. Because of this, the whole world went to hell with those crazy people ready for a mental institution.

Solution: unfortunately, there is none. :(

[Disclaimer: I know, some of you will think this is spam that has no place here. However, like all other posts on this subreddit, this one is educational in nature -- this post teaches you: not everything can be solved by programming in Scheme. There are things that transcend that. So this is also a very important (life) lesson.]


r/RacketHomeworks • • Dec 29 '22

Largest product in a series

1 Upvotes

Problem:

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Solution: if we just want to know which is the biggest product, then this program is enough:

#lang racket

(define NUMBER-STR
  (string-append
   "73167176531330624919225119674426574742355349194934"
   "96983520312774506326239578318016984801869478851843"
   "85861560789112949495459501737958331952853208805511"
   "12540698747158523863050715693290963295227443043557"
   "66896648950445244523161731856403098711121722383113"
   "62229893423380308135336276614282806444486645238749"
   "70172427121883998797908792274921901699720888093776"
   "65727333001053367881220235421809751254540594752243"
   "52584907711670556013604839586446706324415722155397"
   "53697817977846174064955149290862569321978468622482"
   "83972241375657056057490261407972968652414535100474"
   "82166370484403199890008895243450658541227588666881"
   "16427171479924442928230863465674813919123162824586"
   "17866458359124566529476545682848912883142607690042"
   "24219022671055626321111109370544217506941658960408"
   "84580156166097919133875499200524063689912560717606"
   "05886116467109405077541002256983155200055935729725"
   "71636269561882670428252483600823257530420752963450"))


(define (find numstr n)
  (define len (string-length numstr))
  (define (char->digit c) (- (char->integer c) 48))
  (define (loop i m)
    (if (> i (- len n))
        m
        (let* ([ndigits (map char->digit
                             (string->list (substring numstr i (+ i n))))]
               [p (foldl * 1 ndigits)])
          (loop (+ i 1) (max m p)))))
  (loop 0 0))

Now we can call our find function, like this:

> (find NUMBER-STR 4)
5832
> (find NUMBER-STR 13)
23514624000

If we want to know not only what is the largest product, but also with which digits it will be achieved, then we can use this modified version of program:

(define (find2 numstr n)
  (define len (string-length numstr))
  (define (char->digit c) (- (char->integer c) 48))
  (define (loop i m digits)
    (if (> i (- len n))
        (list m digits)
        (let* ([ndigits (map char->digit
                             (string->list (substring numstr i (+ i n))))]
               [p (foldl * 1 ndigits)])
          (if (> p m)
              (loop (+ i 1) p ndigits)
              (loop (+ i 1) m digits)))))
    (loop 0 0 ""))

Now we can call find2, like this:

> (find2 NUMBER-STR 4)
'(5832 (9 9 8 9))
> (find2 NUMBER-STR 13)
'(23514624000 (5 5 7 6 6 8 9 6 6 4 8 9 5))

From that, we see that largest product 23514624000 is achieved by multiplying this 13 consecutive digits: 5, 5, 7, 6, 6, 8, 9, 6, 6, 4, 8, 9, 5.


r/RacketHomeworks • • Jan 25 '23

SICP , implement a set as an unordered-linked-list

2 Upvotes

r/RacketHomeworks • • Dec 28 '22

Sum square difference

2 Upvotes

Problem: The sum of the squares of the first ten natural numbers is,

1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Solution:

#lang racket

; 1^2 + 2^2 + ... + n^2
(define (sum-of-first-n-squares n)
  (/ (* n (+ n 1) (+ (* 2 n) 1)) 6))

; (1 + 2 + ... + n)^2
(define (sum-of-first-n-numbers-squared n)
  (let ([a (/ (* n (+ n 1)) 2)])
    (* a a)))

Now we can calculate the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum, like this:

> (- (sum-of-first-n-numbers-squared 100)
     (sum-of-first-n-squares 100))
25164150

So, we see that our result is the number 25164150.

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=


r/RacketHomeworks • • Nov 18 '22

Problem 1 - complete solution

1 Upvotes

Problem: https://reddit.com/r/Racket/comments/yxatrr/return_a_list_of_indexes_after_using_recursion/

Complete solution:

#lang racket

(define (umbral-simple lista umbral tipon)
  (define cmp (if (equal? tipon #\m) < >))
  (define (helper xs ix)
    (cond ((null? xs) '())
          ((cmp (car xs) umbral) (cons ix (helper (cdr xs) (+ ix 1))))
          (else (helper (cdr xs) (+ ix 1)))))
  (helper lista 0))

Now, you have, for example:

> (umbral-simple '(10 50 30 20 40) 25 #\m)
'(0 3)

r/RacketHomeworks • • Apr 12 '23

The only remaining device in the world that can still run the mit-scheme...

3 Upvotes

... is Chris Hanson's toaster:

Hey Chris Hanson, are you ashamed that your decades of inaction has caused mit-scheme to fail completely and no longer work on almost any platform except your toaster?

Disaster, horror!

(for the background story of this post, please see this discussion: Comparing curl and mit-scheme as projects tells us why the first is successful and the second is not : RacketHomeworks (reddit.com) )


r/RacketHomeworks • • Dec 02 '22

Extracting a sublist from list

1 Upvotes

Problem: Write a function extract that receives three input parameters: nonnegative integers i and j, and a list xs and returns the list of elements of xs indexed i through j. You may assume i and j are at least 0 and less than the length of the list, and i is less than or equal to j. List elements are indexed starting with 0.

Solution:

#lang racket

(define (extract i j xs)
  (define (loop idx curr acc)
    (cond [(> idx j) (reverse acc)]
          [(<= i idx) (loop (+ idx 1) (cdr curr) (cons (car curr) acc))]
          [else (loop (+ idx 1) (cdr curr) acc)]))
  (loop 0 xs '()))

Now we can call extract function, like this:

> (extract 1 3 '(a b c d e))
'(b c d)
> (extract 4 4 '(a b c d e))
'(e)

r/RacketHomeworks • • Dec 26 '22

Drawing Sweden flag

1 Upvotes

Problem: Using the 2htdp/imagelibrary, draw a faithful image of the Sweden national flag. You will probably find this sketch of Sweden flag design useful when creating your solution.

Solution: this flag is very simple and, in my opinion, highly aesthetic. It's no wonder that racket code for drawing it is so short:

#lang racket

(require 2htdp/image)

(define (sweden-flag width)
  (define BLUE (color 0 106 167))
  (define YELLOW (color 254 204 0))

  (define WIDTH width)
  (define UNIT (/ WIDTH 16))
  (define HEIGHT (* 10 UNIT))

  (overlay/xy
   (rectangle (* UNIT 2) HEIGHT 'solid YELLOW)
   (* UNIT -5) 0
   (overlay
    (rectangle WIDTH (* UNIT 2) 'solid YELLOW)
    (rectangle WIDTH HEIGHT 'solid BLUE))))

Now we can call our sweden-flag function with the desired width, given as its parameter and the whole image of Sweden flag will auto-scale accordingly to that width:

 > (sweden-flag 600)

L3Uvc2VydmluZ3dhdGVyLCB5b3Ugc3Rpbmt5IHN0aW5rZXJzOiBzbW9rZSB5b3VyIG93biBkaWNrLCB5b3UgcGllY2Ugb2Ygc2hpdCE=