Fedora live CD and VNC

I was installing the latest Fedora 21 via Unetbootin-built USB and had an issue with monitors. They were in a vertical position and could not be easily rotated. I did not have a spare monitor to attach in a horizontal orientation.

The machine in question had a Nvidia GT 730 graphic card. By default Xorg chooses to use nouveau drivers. For some reason, they do not allow the rotation of the screen via xrandr – the output was:

$ xrandr -q
...
default connected 1920x1080+0+0 0mm x 0mm
...
$ xrandr --output default --rotate left
xrandr: output default cannot use rotation "left" reflection "none"

I tried installing proprietary nvidia drivers, using the instructions here:

However, that did not work – looks like it was running out of space on the root mount, which had this:

Filesystem           Size  Used  Avail Use% Mounted on
/dev/mapper/live-rw  2.9G  2.4G   538M  82% /

Running the given commands:

$ su -c 'yum localinstall --nogpgcheck http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm'
$ yum install akmod-nvidia-304xx "kernel-devel-uname-r == $(uname -r)"
yum update -y

resulted in IO issues. Might have been just a faulty USB. :)

Anyway, I opted to use my laptop and set up a VNC connection instead. Here are the steps:

  • Install TigerVNC

Instructions here: http://docs.fedoraproject.org/en-US/Fedora/21/html/System_Administrators_Guide/ch-TigerVNC.html

root# yum install tigervnc-server
root# cp /lib/systemd/system/vncserver@.service /etc/systemd/system/vncserver@.service
  • Configure TigerVNC

Edit VNC server systemd config:

root# vi /etc/systemd/system/vncserver@.service

and change to liveuser, add geometry parameter as appropriate for your situation

  • Update SELinux policy

Due to this bug: https://bugzilla.redhat.com/show_bug.cgi?id=1062968

root# yum update selinux-policy

In my case, this updated selinux-policy to 3.13.1-105.9.fc21 and worked fine with it.

  • Set up the password
liveuser$ vncpasswd
  • Enable VNC port

Credits: http://www.howopensource.com/2011/08/vnc-error-unable-to-connect-to-host-no-route-to-host-113-solved/

root# iptables -I INPUT 1 -p tcp --dport 5901 -j ACCEPT
  • Reload the configuration and start the server
root# systemctl daemon-reload
root# systemctl start vncserver@:1.service

Credits: http://forums.fedoraforum.org/showthread.php?t=272137&page=4

Edit VNC xstartup file:

liveuser$ vi ~/.vnc/xstartup

Comment out this line:

exec /etc/X11/xinit/xinitrc

Add this line at the end:

/usr/bin/xfce4-session &

Restart VNC server:

root# systemctl restart vncserver@:1.service

Now you should have a running VNC server that you can access with some VNC client. I used vinagre as the laptop had Xubuntu, but any other should work. Fedora installation worked fine using this setup and was really quick.

The nicest thing – VNC session was horizontal :).


One Response to “Fedora live CD and VNC”

DMPK on September 18th, 2017 10:57:

… [Trackback]

[…] Read More here|Read More|Find More Informations here|Here you can find 43887 more Informations|Informations to that Topic: icyrock.com/blog/2015/04/fedora-live-cd-and-vnc/ […]


Leave a Reply

(required)

(required)

Next round of 4clojure.com solutions

After the seventh round, five more 4clojure.com solutions:

;;; Problem 60 - Sequence Reduction
(deftest test-problem-60
  (let [v1 (fn fred
             ([f [p1 & ps]] (fred f p1 ps))
             ([f p1 [p2 & ps]]
              (cons p1
                    (when p2
                      (lazy-seq (fred f (f p1 p2) ps))))))
        __ v1]
    (is (= (take 5 (__ + (range))) [0 1 3 6 10]))
    (is (= (__ conj [1] [2 3 4]) [[1] [1 2] [1 2 3] [1 2 3 4]]))
    (is (= (last (__ * 2 [3 4 5])) (reduce * 2 [3 4 5]) 120))))

;;; Problem 59 - Juxtaposition
(deftest test-problem-59
  (let [v1 (fn [& fns]
             (fn [& xs]
               (map #(apply % xs) fns)))
        __ v1]
    (is (= [21 6 1] ((__ + max min) 2 3 5 1 6 4)))
    (is (= ["HELLO" 5] ((__ #(.toUpperCase %) count) "hello")))
    (is (= [2 6 4] ((__ :a :c :b) {:a 2, :b 4, :c 6, :d 8 :e 10})))))

;;; Problem 58 - Function composition
(deftest test-problem-58
  (let [v1 (fn [& fns]
             (fn [& xs]
               (let [[f & rfns] (reverse fns)]
                 (reduce #(%2 %)
                         (apply f xs)
                         rfns))))
        v2 (fn [& fns]
             (reduce (fn [f g]
                       (fn [& xs]
                         (f (apply g xs))))
                     fns))
        __ v2]
    (is (= [3 2 1] ((__ rest reverse) [1 2 3 4])))
    (is (= 5 ((__ (partial + 3) second) [1 2 3 4])))
    (is (= true ((__ zero? #(mod % 8) +) 3 5 7 9)))
    (is (= "HELLO" ((__ #(.toUpperCase %) #(apply str %) take) 5 "hello world")))))

;;; Problem 57 - Simple Recursion
(deftest test-problem-57
  (let [v1 [5 4 3 2 1] 
        __ v1]
    (is (= __ ((fn foo [x] (when (> x 0) (conj (foo (dec x)) x))) 5)))))

;;; Problem 56 - Find Distinct Items
(deftest test-problem-56
  (let [v1 (fn [xs]
             (loop [[e & c] xs a [] d #{}]
               (if e
                 (recur c
                        (if (d e) a (conj a e))
                        (conj d e))
                 a)))
        __ v1]
    (is (= (__ [1 2 1 3 1 2 4]) [1 2 3 4]))
    (is (= (__ [:a :a :b :b :c :c]) [:a :b :c]))
    (is (= (__ '([2 4] [1 2] [1 3] [1 3])) '([2 4] [1 2] [1 3])))
    (is (= (__ (range 50)) (range 50)))))

(run-tests)

One Response to “Next round of 4clojure.com solutions”

roofing contractor on August 30th, 2017 09:09:

… [Trackback]

[…] Find More here|Find More|Find More Informations here|There you can find 32961 additional Informations|Infos to that Topic: icyrock.com/blog/2015/03/next-round-of-4clojure-com-solutions-7/ […]


Leave a Reply

(required)

(required)

Next round of 4clojure.com solutions

After the sixth round, five more 4clojure.com solutions:

;;; Problem 55 - Count Occurrences
(deftest test-problem-55
  (let [v1 (fn [xs]
             (reduce (fn [a v] (assoc a v (inc (get a v 0)))) {} (vec xs)))
        __ v1]
    (is (= (__ [1 1 2 3 2 1 1]) {1 4, 2 2, 3 1}))
    (is (= (__ [:b :a :b :a :b]) {:a 2, :b 3}))
    (is (= (__ '([1 2] [1 3] [1 3])) {[1 2] 1, [1 3] 2}))))

 ;;; Problem 54 - Partition a Sequence
(deftest test-problem-54
  (let [v1 (fn [n xs]
             (loop [a [] r xs]
               (if (< (count r) n)
                 a
                 (recur (conj a (take n r)) (drop n r)))))
        __ v1]
    (is (= (__ 3 (range 9)) '((0 1 2) (3 4 5) (6 7 8))))
    (is (= (__ 2 (range 8)) '((0 1) (2 3) (4 5) (6 7))))
    (is (= (__ 3 (range 8)) '((0 1 2) (3 4 5))))))

 ;;; Problem 53 - Longest Increasing Sub-Seq
(deftest test-problem-53
  (let [subseqs #(take-while not-empty (iterate (partial rest) %))
        filter2 (fn [f xs]
                  (loop [ll (first xs) l [ll] [fr :as r] (rest xs)]
                    (if (or (nil? ll)
                            (nil? fr)
                            (not (f ll fr)))
                      l
              (recur fr (conj l fr) (rest r)))))
        do-run #(map (partial filter2 <) %)
        do-long (partial filter #(> (count %) 1))
        do-sort (partial sort-by #(-' (count %)))
        v1 #(-> % subseqs do-run do-long (conj []) do-sort first)
        __ v1]
    (is (= (__ [1 0 1 2 3 0 4 5]) [0 1 2 3]))
    (is (= (__ [5 6 1 3 2 7]) [5 6]))
    (is (= (__ [2 3 3 4 5]) [3 4 5]))
    (is (= (__ [7 6 5 4]) []))))

 ;;; Problem 52 - Intro to Destructuring
(deftest test-problem-52
  (is (= [2 4] (let [[a b c d e f g] (range)] ))))

 ;;; Problem 51 - Advanced Destructuring
(deftest test-problem-51
  (let [v1 [1 2 3 4 5]
        __ v1]
    (is (= [1 2 [3 4 5] [1 2 3 4 5]] (let [[a b & c :as d] __] [a b c d])))))

(run-tests)

3 Responses to “Next round of 4clojure.com solutions”

Next round of 4clojure.com solutions « Blog Archive « icyrock.com on March 1st, 2015 01:20:

[…] the seventh round, five more 4clojure.com […]


todoindie on August 24th, 2017 09:48:

… [Trackback]

[…] Read More on|Read More|Read More Informations here|There you will find 79491 additional Informations|Informations on that Topic: icyrock.com/blog/2015/02/next-round-of-4clojure-com-solutions-6/ […]


car crash compilation usa on September 19th, 2017 07:00:

… [Trackback]

[…] Find More on|Find More|Find More Infos here|Here you will find 30432 additional Infos|Infos to that Topic: icyrock.com/blog/2015/02/next-round-of-4clojure-com-solutions-6/ […]


Leave a Reply

(required)

(required)

Basic X Window keyboard and mouse input blocking

Here’s a small Python script using python-xlib that will block the keyboard and mouse input and then display random-colored, random-sized rectangles whenever an event happens. I tested it in Xubuntu 14.10, not sure if it is possible to run on non-Linux platforms. Obviously, you’ll need to install python-xlib. I use virtualenv to do that, but there’s also a “regular” Debian package available.

from Xlib import Xatom, Xutil
from Xlib.display import Display, X
import sys
import signal 
import random

class bunch(dict):
  __getattr__ = dict.__getitem__
  __setattr__ = dict.__setitem__

def check_for_magic_keys(state, event):
  keys = state['keys']
  if event.type == X.KeyPress:
    keys[event.detail] = True
  elif event.type == X.KeyRelease:
    keys[event.detail] = False

  keycode_alt = 64
  keycode_1 = 10
  keycode_delete = 119

  magic_keys = keys.get(keycode_alt) and keys.get(keycode_1) and keys.get(keycode_delete)
  if magic_keys:
    print("Magic keys pressed, exiting")
    return True

  return False

def random_color(screen):
  red = random.randrange(0, 65536)
  green = random.randrange(0, 65536)
  blue = random.randrange(0, 65536)

  return screen.default_colormap.alloc_color(red, green, blue).pixel

def random_rectangle(screen, window):
  x = random.randrange(0, screen.width_in_pixels)
  y = random.randrange(0, screen.height_in_pixels)
  width = random.randrange(0, screen.width_in_pixels - x)
  height = random.randrange(0, screen.height_in_pixels - y)

  window.window.fill_rectangle(
    gc = window.gc,
    x = x,
    y = y,
    width  = width,
    height = height,
  )

def draw(state, event):
  screen = state.display.screen()
  foreground = random_color(screen)
  background = random_color(screen)

  state.window.gc.change(
    foreground = foreground,
    background = background,
  )

  random_rectangle(screen, state.window)

def handle_event(state, event):
  debug = False
  if debug:
    print(event)
    return True

  if check_for_magic_keys(state, event):
    return False

  draw(state, event)
  return True

def grab_keyboard_and_mouse(root):
  root.grab_keyboard(
    owner_events = True,
    pointer_mode = X.GrabModeAsync,
    keyboard_mode = X.GrabModeAsync,
    time = X.CurrentTime
  )
  
  root.grab_pointer(
    owner_events = True,
    event_mask = X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
    pointer_mode = X.GrabModeAsync,
    keyboard_mode = X.GrabModeAsync,
    confine_to = 0,
    cursor = 0,
    time = X.CurrentTime
  )

def create_window(display, root):
  screen = display.screen()

  window = root.create_window(
    x = 0,
    y = 0,
    width = screen.width_in_pixels,
    height = screen.height_in_pixels,
    border_width = 0,
    depth = screen.root_depth)
  
  atom_net_wm_state = display.intern_atom('_NET_WM_STATE', True)
  atom_net_wm_state_fullscreen = display.intern_atom('_NET_WM_STATE_FULLSCREEN', True)

  window.change_property(
    property = atom_net_wm_state,
    type = Xatom.ATOM,
    format = 32,
    data = [atom_net_wm_state_fullscreen], 
  )

  window.set_wm_normal_hints(
    flags = Xutil.PPosition | Xutil.PSize | Xutil.PMinSize,
    min_width = screen.width_in_pixels,
    min_height = screen.height_in_pixels,
  )

  gc = window.create_gc(
    foreground = screen.black_pixel,
    background = screen.white_pixel,
  )

  return bunch(window = window, gc = gc)

def event_loop(state):
  display = state.display

  while True:
    event = display.next_event()
    display.allow_events(
      mode = X.AsyncBoth,
      time = X.CurrentTime)            

    if not handle_event(state, event):
      break

def main():
  display = Display()
  root = display.screen().root

  grab_keyboard_and_mouse(root)
  window = create_window(display, root)
  window.window.map()

  state = bunch(
    display = display,
    root = root,
    window = window,
    keys = bunch())

  # Comment these out after you have confirmed the magic key works
  signal.signal(signal.SIGALRM, lambda a, b: sys.exit(1))
  signal.alarm(4)

  event_loop(state)

if __name__ == '__main__':
  main()

How it works:

  • It creates a window that covers the whole desktop
  • It then grabs both the key and the mouse input
  • Whenever an event happens, it will first check for a magic key
  • If it is a magic key, it will exit
  • If it is not a magic key, it will display a random rectangle and continue to run

The magic key is currently set to Alt + 1 + Del, pressed at the same time. There’s also a small debug section in the event loop that can be enabled by setting debug = True. Printing events like this allows for reconfiguration if needed, e.g. to change the magic key.

The above version has the signal.alarm call – I left this there, so that it exits after 4 seconds while testing. Otherwise, if it doesn’t work, you have no input. Well, actually you do – I found that Alt + F1 works, so you can escape to a console and kill the python process, but while testing I found it easier to just do a timed exit. In order to be used for longer periods, the signal lines should be commented out.


3 Responses to “Basic X Window keyboard and mouse input blocking”

Christ Gospel Church Cult on August 7th, 2017 14:15:

… [Trackback]

[…] Find More here|Find More|Read More Infos here|There you can find 57234 additional Infos|Infos on that Topic: icyrock.com/blog/2015/01/basic-x-window-keyboard-and-mouse-input-blocking/ […]


In vitro pharmacology studies on September 7th, 2017 03:45:

… [Trackback]

[…] Find More on|Find More|Read More Infos here|There you will find 89713 more Infos|Infos on that Topic: icyrock.com/blog/2015/01/basic-x-window-keyboard-and-mouse-input-blocking/ […]


DMPK on September 18th, 2017 08:03:

… [Trackback]

[…] Find More on|Find More|Find More Informations here|Here you can find 98049 additional Informations|Infos on that Topic: icyrock.com/blog/2015/01/basic-x-window-keyboard-and-mouse-input-blocking/ […]


Leave a Reply

(required)

(required)

Duolingo lessons to go

If you are using Duolingo and are nearing the end of the tree, you might be anxious to know how many lessons are left till you can claim your tree is all golden. Here’s a small Javascript snippet that allows to get that from the main language page on the site:

var lessons = $('.lessons-left:not(:empty)').map(function() {
    return this.innerHTML
})

var listToInt = function(list) {
    return _.map(list, function(e) {
        return parseInt(e)
    })
}

var expanded = _.map(lessons, function(e) {
    var list = e.split('/')
    return listToInt(list)
})

var done = _.collect(expanded, _.head)
var total = _.collect(expanded, _.last)

var sum = function(list) {
    return _.reduce(list, function(a, b) { 
        return a + b
    }, 0)
}

console.log("lessons to go:", sum(total) - sum(done))

Here’s how it can be used:

  • Open Chrome Developer Tools window by pressing F12
  • Go to Sources tab
  • Go to Snippets sub-tab
  • On the left, right-click and select New to create a new snippet. Name it whatever you like, I named it “Duolingo – lessons to go”
  • Put the above code in the snippet source tab that opens
  • Run it by pressing Ctrl + Enter or by clicking on a play icon in the top right of the Developer Tools window

It should print your tree leftover in the console. Now let’s get that number down to 0!


One Response to “Duolingo lessons to go”

DMPK Services on September 13th, 2017 05:28:

… [Trackback]

[…] Find More here|Find More|Read More Infos here|Here you will find 878 additional Infos|Informations to that Topic: icyrock.com/blog/2014/12/duolingo-lessons-to-go/ […]


Leave a Reply

(required)

(required)

Project Euler in Haskell – problems 6 through 10

Continuing from the previous one, here are my solutions to problems 6-10. Same warning applies – they are unusually long for a Haskell program and as usual take them with a grain of salt.

Project Euler 6 in Haskell

Project Euler problem 6

ssdiff :: Int -> Int
ssdiff n = (sum [1..n] ^ 2) - (sum $ map (^2) [1..n])
  
main = do
  print $ ssdiff 10
  print $ ssdiff 100

Project Euler 7 in Haskell

Project Euler problem 7

import           Data.Numbers.Primes

nthprime :: Int -> Int
nthprime n = primes !! (n-1)

main = do
  print $ nthprime 6
  print $ nthprime 10001

Project Euler 8 in Haskell

Project Euler problem 8

import           Data.Char
import           Data.List

minLen :: Int -> [a] -> Bool
minLen n xs = not $ null (drop n xs)

nibbles :: Int -> [a] -> [[a]]
nibbles n xs = map (take n) $ filter (minLen n) $ tails xs

prod :: String -> Int
prod s = product $ map digitToInt s

maxProd :: String -> Int -> Int
maxProd s n = maximum $ map prod (nibbles n s)

main :: IO ()
main = do
     txt <- readFile "src/Euler/euler8.txt"
     numTxt <- return $ concat $ lines txt
     print $ maxProd numTxt 4
     print $ maxProd numTxt 13

Project Euler 9 in Haskell

Project Euler problem 9

pythTrip :: Int -> Int
pythTrip n = head [a * b * c | a <- [1..n - 2]
                             , b <- [a + 1..n - 2]
                             , let c = n - a - b
                             , c > b
                             , a ^ 2 + b ^ 2 == c ^ 2]

main :: IO ()
main = do
     print $ pythTrip 1000

Project Euler 10 in Haskell

Project Euler problem 10

This one was interesting. Using the Data.Numbers.Primes package, it’s very easy and very fast:

import qualified Data.Numbers.Primes as P

sumOfPrimes :: Int -> Integer
sumOfPrimes n = (sum . map toInteger . takeWhile (< n)) P.primes

main :: IO ()
main = do
     print $ sumOfPrimes 10
     print $ sumOfPrimes 2000000

However, I was intrigued how to do Sieve of Eratosthenes in Haskell. Here’s what I came up with:

import qualified Data.Vector.Unboxed as UV

sieve :: Int -> UV.Vector Bool
sieve m = let s = UV.replicate (1 + m) True
              sqm = (floor . sqrt . fromIntegral) m
              update v n
                | v UV.! n == False = v
                | otherwise  = UV.update v (UV.zip xs ys)
                  where sqn = n * n
                        xs = UV.enumFromStepN sqn n (1 + (m - sqn) `div` n)
                        ys = UV.replicate (UV.length xs) False
              sievep v n
                | n <= sqm = sievep (update v n) (n + 1)
                | otherwise = v
          in sievep s 2

primes :: Int -> [Int]
primes m = (UV.toList . UV.drop 2 . UV.map fst
            . UV.filter ((== True) . snd)
            . UV.zip (UV.enumFromN 0 (1 + m)) . sieve) m

sumOfPrimes :: Int -> Integer
sumOfPrimes = sum . map toInteger . primes

main :: IO ()
main = do
     print $ sumOfPrimes 10
     print $ sumOfPrimes 2000000

I must say I was a bit surprised how the process of writing turned out to be different. First, I used Vectors and Arrays package provided much confusion here. Not sure if I’m right, but looks like Vectors package is newer. Some things such as DiffArray turned out to be unsuccessful experiments, for example. Second, I found it quite un-Haskelly, given the solution is non-lazy and bounded.

I guess the number of different solutions and papers (some relatively new to that point) that I found, especially on the main Haskell Wiki page says a lot:

I guess I’ll just go with the built-in for now.


Leave a Reply

(required)

(required)

Solving the Impossible puzzle in Clojure

I found this puzzle recently. I should say I rediscovered it, as I knew it from before. I wanted to solve it in Clojure – here’s one possible solution, with comments on the thought process involved in solving it (in the comments before the actual code).

(ns com.icyrock.clojure.prb.xynum)

; http://puzzling.stackexchange.com/questions/251/i-dont-know-the-two-numbers-but-now-i-do
; http://en.wikipedia.org/wiki/Impossible_Puzzle
; http://people.sc.fsu.edu/~jburkardt/fun/puzzles/impossible_solution.html

; Two numbers, 1 < x < y, x + y < n (n = 100 in the linked question)
; p = x * y
; s = x + y

; p: I cannot determine the two numbers.
;   => p not unique: p = x1 * y1 = x2 * y2 = ...
;      Let's call this an ambiguous product

; s: I knew that.
;   => s can be created from one or multiple pairs: s = x1 + y1 = x2 + y2 = ...
;      Those pairs form these products:
;        p1 = x1 * y1
;        p2 = x2 * y2
;        ...
;      Each of these products can be created from multiple pairs (i.e. is ambiguous):
;        p1 = x11 * y11 = x12 * y12 = ...
;        p2 = x21 * y21 = x12 * y22 = ...
;        ...
;      Let's call this product-ambiguous sum

; p: Now I can determine them.
;   => p = x1 * y1 = x2 * y2 = ...
;      Only one of (xk, yk) forms a product-ambiguous sum
;      Let's call this unambiguous product

; s: So can I.
;   => s = x1 + y1 = x2 + y2 = ...
;      Only one of all the possible products:
;        p1 = x1 * y1
;        p2 = x2 * y2
;        ...
;      is an unambiguous product
;      Let's call this unambiguous sum

(defn xynum [n]
  (let [pairs (for [y (range 2 n) x (range 2 y) :when (< (+ x y) n)] [x y])
        sum-map (group-by (partial apply +) pairs)
        prod-map (group-by (partial apply *) pairs)
        ; Pair forms a product. That product can be formed from at least some other pair.
        is-ambiguous-product (fn [pair] 
                               (> (count (prod-map (apply * pair))) 1))
        ; Pair forms a sum. That sum can be formed from other pairs. Those pairs form some products. All those products are ambiguous.
        is-product-ambiguous-sum (fn [pair] 
                                   (every? true? (map is-ambiguous-product (sum-map (apply + pair)))))
        ; Pair forms a product. That product can be formed from other pairs. Only one of those pairs forms a product-ambiguous sum.
        is-unambiguous-product (fn [pair] 
                                 (= 1 (count (filter true? (map is-product-ambiguous-sum (prod-map (apply * pair)))))))
        ; Pair forms a sum. That sum can be formed from other pairs. Only one of those pairs forms an unambiguous product.
        is-unambiguous-sum (fn [pair] 
                             (= 1 (count (filter true? (map is-unambiguous-product (sum-map (apply + pair)))))))
        is-pair-a-candidate (fn [pair] (and
                                         (is-ambiguous-product pair)
                                         (is-product-ambiguous-sum pair)
                                         (is-unambiguous-product pair)
                                         (is-unambiguous-sum pair)))
        candidates (filter is-pair-a-candidate pairs)]
    (println "Pair count:" (count pairs))
    (println "Sum map count:" (count sum-map))
    (println "Product map count:" (count prod-map))
    (println "Candidates count:" (count candidates))
    (println "Candidates: " candidates)))

(defn -main []
  (xynum 100))

(-main)

Note also the Wikipedia entry, which contains solutions in other languages. I particularly liked the Scala version, notably for its conciseness and readability.


Leave a Reply

(required)

(required)

Next round of 4clojure.com solutions

After the fifth round, five more 4clojure.com solutions:

;;; Problem 50 - Split by Type
(deftest test-problem-50
  (let [v1 (fn [xs] (for [t (map type xs)] (filter #(= (type %) t) xs))) 
        v2 (fn [xs] (vals (group-by type xs)))
        __ v2]
    (is (= (set (__ [1 :a 2 :b 3 :c])) #{[1 2 3] [:a :b :c]}))
    (is (= (set (__ [:a "foo"  "bar" :b])) #{[:a :b] ["foo" "bar"]}))
    (is (= (set (__ [[1 2] :a [3 4] 5 6 :b])) #{[[1 2] [3 4]] [:a :b] [5 6]}))))
 
;;; Problem 49 - Split a sequence
(deftest test-problem-49
  (let [v1 (fn [n xs] [(take n xs) (drop n xs)]) 
        __ v1]
    (is (= (__ 3 [1 2 3 4 5 6]) [[1 2 3] [4 5 6]]))
    (is (= (__ 1 [:a :b :c :d]) [[:a] [:b :c :d]]))
    (is (= (__ 2 [[1 2] [3 4] [5 6]]) [[[1 2] [3 4]] [[5 6]]]))))
 
;;; Problem 48 - Intro to some
(deftest test-problem-48
  (let [v1 6 
        __ v1]
    (is (= __ (some #{2 7 6} [5 6 7 8])))
    (is (= __ (some #(when (even? %) %) [5 6 7 8])))))

;;; Problem 47 - Contain Yourself
(deftest test-problem-47
  (let [v1 4 
        __ v1]
    (is (contains? #{4 5 6} __))
    (is (contains? [1 1 1 1 1] __))
    (is (contains? {4 :a 2 :b} __))
    ; No longer works in CLojure 1.5+: http://clojuredocs.org/clojure_core/clojure.core/contains_q
    ; (is (not (contains? '(1 2 4) __))) 
    ))

;;; Problem 46 - Flipping out
(deftest test-problem-46
  (let [v1 (fn [f] #(f %2 %)) 
        __ v1]
    (is (= 3 ((__ nth) 2 [1 2 3 4 5])))
    (is (= true ((__ >) 7 8)))
    (is (= 4 ((__ quot) 2 8)))
    (is (= [1 2 3] ((__ take) [1 2 3 4 5] 3)))))

(run-tests)

One Response to “Next round of 4clojure.com solutions”

Next round of 4clojure.com solutions « Blog Archive « icyrock.com on February 26th, 2015 20:58:

[…] the sixth round, five more 4clojure.com […]


Leave a Reply

(required)

(required)

Next round of 4clojure.com solutions

After the fourth round, five more 4clojure.com solutions:

;;; Problem 45 - Intro to Iterate
(deftest test-problem-45
  (let [v1 [1 4 7 10 13] 
        __ v1]
    (is (= __ (take 5 (iterate #(+ 3 %) 1))))))
 
;;; Problem 44 - Rotate Sequence
(deftest test-problem-44
  (let [v1 (fn [n xs] (let [k (mod n (count xs))] (concat (drop k xs) (take k xs))))
        __ v1]
    (is (= (__ 2 [1 2 3 4 5]) '(3 4 5 1 2)))
    (is (= (__ -2 [1 2 3 4 5]) '(4 5 1 2 3)))
    (is (= (__ 6 [1 2 3 4 5]) '(2 3 4 5 1)))
    (is (= (__ 1 '(:a :b :c)) '(:b :c :a)))
    (is (= (__ -4 '(:a :b :c)) '(:c :a :b)))))
 
;;; Problem 43 - Reverse Interleave
(deftest test-problem-43
  (let [v1 (fn [xs n] (partition (/ (count xs) n) (apply interleave (partition n xs)))) 
        __ v1]
    (is (= (__ [1 2 3 4 5 6] 2) '((1 3 5) (2 4 6))))
    (is (= (__ (range 9) 3) '((0 3 6) (1 4 7) (2 5 8))))
    (is (= (__ (range 10) 5) '((0 5) (1 6) (2 7) (3 8) (4 9))))))
 
;;; Problem 42 - Factorial Fun 
(deftest test-problem-42
  (let [v1 #(apply * (range 1 (inc %)))
        __ v1]
    (is (= (__ 1) 1))
    (is (= (__ 3) 6))
    (is (= (__ 5) 120))
    (is (= (__ 8) 40320))))
 
;;; Problem 41 - Drop Every Nth Item
(deftest test-problem-41
  (let [v1 (fn [xs n] (apply concat (map #(take (dec n) %) (partition-all n xs))))
        __ v1] 
    (is (= (__ [1 2 3 4 5 6 7 8] 3) [1 2 4 5 7 8]))
    (is (= (__ [:a :b :c :d :e :f] 2) [:a :c :e]))
    (is (= (__ [1 2 3 4 5 6] 4) [1 2 3 5 6]))))
 
(run-tests)

One Response to “Next round of 4clojure.com solutions”

Next round of 4clojure.com solutions « Blog Archive « icyrock.com on September 14th, 2014 07:18:

[…] the fifth round, five more 4clojure.com […]


Leave a Reply

(required)

(required)

Lazy seq for Pascal’s triangle in Clojure

Here’s a lazy-seq for Pascal’s triangle:

(ns com.icyrock.clojure.prb.lazy_seq
  (:use clojure.test))

(defn next-pascal-row [prev]
  (concat [1] (map #(apply + %) (map list prev (rest prev))) [1]))

(deftest next-pascal-row-test
  (is (= [1 1] (next-pascal-row [1])))
  (is (= [1 2 1] (next-pascal-row [1 1])))
  (is (= [1 3 3 1] (next-pascal-row [1 2 1])))
  (is (= [1 4 6 4 1] (next-pascal-row [1 3 3 1]))))

(defn lazy-pascal-triangle 
  ([] (lazy-pascal-triangle [1]))
  ([prev] (cons prev 
                (lazy-seq (lazy-pascal-triangle (next-pascal-row prev))))))

(deftest lazy-pascal-triangle-test
  (is (= [[1]
          [1 1]
          [1 2 1]
          [1 3 3 1]
          [1 4 6 4 1]
          [1 5 10 10 5 1]
          [1 6 15 20 15 6 1]]
         (take 7 (lazy-pascal-triangle)))))

(run-tests)

3 Responses to “Lazy seq for Pascal’s triangle in Clojure”

Fernando on July 30th, 2014 08:33:

Nice. You could also leverage iterate:

(defn lazy-pascal-triangle ([] (lazy-pascal-triangle [1])) ([prev] (iterate next-pascal-row prev)))


icyrock.com on August 18th, 2014 21:40:

Great, thanks for the addition Fernando!


binaural on August 24th, 2017 04:20:

… [Trackback]

[…] Find More here|Find More|Find More Infos here|There you will find 4770 more Infos|Informations to that Topic: icyrock.com/blog/2014/07/lazy-seq-for-pascals-triangle-in-clojure/ […]


Leave a Reply

(required)

(required)