Problem of the Day
A new programming or logic puzzle every Mon-Fri

List Segments

If you're a unix user you may be familiar with the popular command 'ls'. The 'ls' command simply prints all the files and folders in a directory. Today's objective is to create a program that takes in an absolute folder path and prints out all the files and folders inside that directory. For bonus points make it also work with relative paths. If an invalid directory is passed simply print out "Invalid directory".

Permalink: http://problemotd.com/problem/list-segments/

Comments:

  • Anonymous - 9 years, 4 months ago

    #!/bin/bash [[ ! -d "$1" ]] && echo 'Invalid Directory' && exit 1 ls -1 "$1"

    reply permalink

  • Anonymous - 9 years, 4 months ago

    #!/bin/bash
    [[ ! -d "$1" ]] && echo 'Invalid Directory' && exit 1
    ls -1 "$1"
    

    reply permalink

  • Driphter - 9 years, 4 months ago

    Clojure!

    (ns line-segments
      (:require [clojure.java.io :as io]
                [clojure.string :as str]))
    
    (defn ls
      ([]
       (ls "."))
      ([path]
       (let [file (io/file path)]
         (if-not (and (.exists file) (.isDirectory file))
           (println "Invalid directory")
           (->> (.listFiles file)
                (map #(.getName %))
                (str/join " ")
                println)))))
    

    reply permalink

Content curated by @MaxBurstein