Advertisement
SepandMeenu

Product Excluding Self

Sep 11th, 2018
580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.08 KB | None | 0 0
  1. #lang racket
  2. ;; Given a list of numbers, return a list where the i-th element corresponds to the multiplication of the initial list except its i-th element.
  3.  
  4. ;; Example:
  5. ;; [1,2,3,4] -> [24, 12, 8, 6]
  6.  
  7. ; index :: [Number] -> [(Integer, Number)]
  8. ; indexes a list of numbers
  9. (define (index lNum)
  10.   (for/list [(i (in-naturals))
  11.              (n (in-list lNum))]
  12.     (cons i n) ; tuple '(i . n)
  13.     )
  14.   )
  15.  
  16. ; filter-i :: [(Integer, Number)] -> [(Integer, Number)]
  17. ; filters an indexed list, indexed-l, by removing
  18. ; the element with index i
  19. (define (filter-i indexed-l idx)
  20.   (filter [lambda (a) (not [eq? (car a) idx])] indexed-l)
  21.   )
  22.  
  23. ; product-ex-self :: [Number] -> [Number]
  24. ; produces a list of products of elements of list, l,
  25. ; in which, in each product, one of the list elements
  26. ; is excluded
  27. (define (product-ex-self lNum)
  28.   (let [(idx-l (index lNum)) ; indexed list
  29.         ]
  30.     ;--IN--
  31.     (for/list [(ix (in-list idx-l))]
  32.       (apply * (map cdr [filter-i idx-l (car ix)]))
  33.       )
  34.     )
  35.   )
  36.  
  37. (define mylist (list 1 2 3 4))
  38. (print (product-ex-self mylist))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement