April 5, 2011

Some men are discovered; others are found out.
Words must be weighed, not counted.
By failing to prepare, you are preparing to fail.
He who spends a storm beneath a tree, takes life with a grain of TNT.
You attempt things that you do not even plan because of your extreme stupidity.
Take care of the luxuries and the necessities will take care of themselves.
Words are the voice of the heart.
Your mind understands what you have been taught; your heart, what is true.
A king's castle is his home.
He who has a shady past knows that nice guys finish last.
The universe is laughing behind your back.
The best prophet of the future is the past.
It is a poor judge who cannot award a prize.
Even the boldest zebra fears the hungry lion.
Money will say more in one moment than the most eloquent lover can in years.
Money may buy friendship but money can not buy love.
Might as well be frank, monsieur. It would take a miracle to get you out of Casablanca.
Creditors have much better memories than debtors.
Many pages make a thick book.
Every purchase has its price.
Do not underestimate the power of the Force.
You will step on the night soil of many countries.
Mind your own business, Spock. I'm sick of your halfbreed interference.
He who invents adages for others to peruse takes along rowboat when going on cruise.
Of all forms of caution, caution in love is the most fatal.
If you suspect a man, don't employ him.
The Tree of Learning bears the noblest fruit, but noble fruit tastes bad.
Stop searching forever. Happiness is unattainable.
A man who fishes for marlin in ponds will put his money in Etruscan bonds.
A good memory does not equal pale ink.
How sharper than a hound's tooth it is to have a thankless serpent.
You dialed 5483
It's later than you think.
Mistakes are oft the stepping stones to failure.
It's not reality that's important, but how you perceive things.
Promptness is its own reward, if one lives by the clock instead of the sword.
Like winter snow on summer lawn, time past is time gone.
Far duller than a serpent's tooth it is to spend a quiet youth.
Let not the sands of time get in your lunch.
The attacker must vanquish; the defender need only survive.
Standing on head makes smile of frown, but rest of face also upside down.
Deprive a mirror of its silver and even the Czar won't see his face.
Man's horizons are bounded by his vision.
To criticize the incompetent is easy; it is more difficult to criticize the competent.
He who has imagination without learning has wings but no feet.
Men seldom show dimples to girls who have pimples.
Troglodytism does not necessarily imply a low cultural level.
You cannot kill time without injuring eternity.
As goatherd learns his trade by goat, so writer learns his trade by wrote.
One man tells a falsehood, a hundred repeat it as true.
Crazee Edeee, his prices are INSANE!!!
It is better to wear out than to rust out.
When the wind is great, bow before it; when the wind is heavy, yield to it.
The wise shepherd never trusts his flock to a smiling wolf.
It is the wise bird who builds his nest in a tree.
How you look depends on where you go.
A plucked goose doesn't lay golden eggs.
A man who turns green has eschewed protein.
Put not your trust in money, but put your money in trust.
Even a hawk is an eagle among crows.
Even the smallest candle burns brighter in the dark.
People who take cat naps don't usually sleep in a cat's cradle.
A truly wise man never plays leapfrog with a Unicorn.
Do not clog intellect's sluices with bits of knowledge of questionable uses.
Let him who takes the Plunge remember to return it by Tuesday.
Try to divide your time evenly to keep others happy.
You have mail.
His heart was yours from the first moment that you met.
Sin has many tools, but a lie is the handle which fits them all.
Let a fool hold his tongue and he will pass for a sage.
With clothes the new are best, with friends the old are best.
He is truly wise who gains wisdom from another's mishap.
Beware of a dark-haired man with a loud tie.
Today is the last day of your life so far.
Flee at once, all is discovered.
Man who falls in vat of molten optical glass makes spectacle of self.
Go directly to jail. Do not pass Go, do not collect $200.
For a good time, call 8367-3100.
Those who can, do; those who can't, simulate.
Those who can, do; those who can't, write. Those who can't write work for the Bell Labs Record.
God does not play dice.
This fortune is inoperative. Please try another.
Laugh, and the world ignores you. Crying doesn't help either.
No amount of genius can overcome a preoccupation with detail.
You will feel hungry again in another hour.
You now have Asian Flu.
God made the integers; all else is the work of Man.
Disk crisis, please clean up!
You auto buy now.
Many are called, few are chosen. Fewer still get to do the choosing.
Try the Moo Shu Pork. It is especially good today.
Many are cold, but few are frozen.
The early worm gets the bird.
He who hesitates is sometimes saved.
Time is nature's way of making sure that everything doesn't happen at once.
The future isn't what it used to be. (It never was.)
Can't open /usr/lib/fortunes.
If God had wanted you to go around nude, He would have given you bigger hands.
It is better to have loved and lost than just to have lost.
A journey of a thousand miles begins with a cash advance from Sam.
Disk crunch - please clean up.
Center meeting at 4pm in 2C-543
I will never lie to you.
Spock: We suffered 23 casualties in that attack, Captain.
Your computer account is overdrawn. Please reauthorize.
1 bulls, 3 cows
It's hard to get ivory in Africa, but in Alabama the Tuscaloosa.
Waste not, get your budget cut next year.
Old MacDonald had an agricultural real estate tax abatement.
Snow Day - stay home.
Save gas, don't eat beans.
All that glitters has a high refractive index.
Ignore previous fortune.
When in doubt, lead trump.
23. ... r-q1
unix soit qui mal y pense
Even a cabbage may look at a king.
Honi soit la vache qui rit.
No directory
Don't eat yellow snow.
One Bell System - it works.
One Bell System - it sometimes works.
* UNIX is a Trademark of Bell Laboratories.
chess tonight
External Security:
Peters hungry, time to eat lunch.
A foolish consistency is the hobgoblin of little minds.
IOT trap -- core dumped
IOT trap -- mos dumped
Rotten wood can not be carved - Confucius (Analects, Book 5, Ch. 9)
System going down at 1:45 this afternoon for disk crashing.
: is not an identifier
Quantity is no substitute for quality, but its the only one we've got.
Those who can do, those who can't, write.
The more things change, the more they'll never be the same again.
New crypt. See /usr/news/crypt.
You might have mail.
You can't go home again, unless you set $HOME
You are in a maze of twisty little passages, all alike.


Pages: 1 2 3

14 Responses to “Fortune”

  1. […] today’s Programming Praxis exercise, our goal is to implement the fortune Unix command line tool. […]

  2. My Haskell solution (see for a version with comments):

    import Control.Monad
    import System.Environment
    import System.Random
    chance :: Int -> Int -> a -> a -> IO a
    chance x y a b = fmap (\r -> if r < x then a else b) $ randomRIO (0, y-1)
    fortune :: [a] -> IO a
    fortune = foldM (\a (n,x) -> chance 1 n x a) undefined . zip [1..]
    main :: IO ()
    main = putStrLn =<< fortune . lines =<<
           readFile . head . (++ ["fortunes.txt"]) =<< getArgs
  3. Dave Webb said

    A Python solution:

    import random,sys
    filename = sys.argv[1] if len(sys.argv) > 1 else '/usr/games/lib/fortunes'
    with open(filename) as fortunes:
        print random.choice(list(fortunes)),
  4. arturasl said

    Beauty of awk :

    END{print l}
  5. Graham said

    My first solution is similar to Dave Webb’s, but I also wrote up an iterative
    function that will use less resources if the fortune file is large.

    #!/usr/bin/env python
    from random import choice, randrange, seed
    from sys import argv
    def whole_file(f):
    # easily written, good if f is smallish
        return choice(f.readlines())
    def iter_file(f):
    # good if f is large
        curr_line, n = None, 0
        for line in f:
            n += 1
            i = 0 if randrange(n) > 1 else 1
            curr_line = [curr_line, line][i]
        return curr_line
    def main(f, func=iter_file):
        print func(f)
        return None
    if __name__ == "__main__":
        f_name = argv[1] if len(argv) > 1 else "fortunes.txt"
        with open(f_name) as f:
  6. Graham said

    Woops, line 14 should read i = 0 if randrange(n) >= 1 else 1

  7. Graham said

    After writing my above solution, I took this as an opportunity to play
    with pylint a sourcecode analyzer.
    My new version is available here.

  8. Mike said

    Another variation on solutions posted by Dave and Graham.

    from collections import deque
    from itertools import count, compress
    from random import randint
    from sys import argv
    FORTUNES = 'fortunes.txt'
    with open(argv[1] if argv[1:] else FORTUNES, 'rt') as f:
       print deque(compress(f, (not randint(0,n) for n in count())), maxlen=1).pop()
  9. Graham said

    Nice one Mike; I need to learn more about the itertools module.
    Quick question, though: randint(0, n) uniformly picks a random integer from [0, n]
    (inclusive), so doesn’t this use the probability 1/(n + 1) instead of 1/n?

  10. Mike said

    @Graham. Yes, my program calculates the probability as 1/(n+1). However, n starts at 0.
    So, for fortune lines 0, 1, 2, …, the probabilities are 1/1, 1/2, 1/3, ….
    This is the same as n starting at 1 and calculating the probability as 1/n.

  11. Ross said

    An version in Common Lisp:

    (defun fortune (filename)
      "Return a Unix V7 fortune"
      (with-open-file (s filename :direction :input)
        (loop :with fortune
              :for line = (read-line s nil)
              :while line
              :counting line :into counter
              :do (when (< (random counter) 1) (setq fortune line))
              :finally (return fortune))))

    and a completely golfed command line Perl version perl -ne 'rand($.)<1&&($l=$_)}{print$l' just because the awk version was still readable.

  12. Graham said

    @Mike: My mistake! Thanks for clearing that up.

  13. Khanh Nguyen said

    In F#,

    open System
    let rnd = new Random()
    let lines = System.IO.File.ReadAllLines("fortunes.txt")
    Seq.nth (rnd.Next(Seq.length lines)) lines
  14. […] reimplemented a basic version of Fortune. This version prints to the standard output a randomly chosen line from a text file. You can […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: