using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MadLibs_RosettaCode
{
	class Program
	{
		static void Main(string[] args)
		{
			string madLibs =
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story,
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name,
a he or she and a noun (<name> gets replaced both times with the same value).";

			StringBuilder sb = new StringBuilder();
			Regex pattern = new Regex(@"\<(.*?)\>");
			string storyLine;
			string replacement;

			Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
			Console.WriteLine("Enter a story: ");

			// Continue to get input while empty line hasn't been entered.
			do
			{
				storyLine = Console.ReadLine();
				sb.Append(storyLine + Environment.NewLine);
			} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));

			// Retrieve only the unique regex matches from the user entered story.
			Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
			if(nameMatch != null)
			{
				do
				{
					Console.WriteLine("Enter value for: " + nameMatch.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
				sb.Replace(nameMatch.Value, replacement);
			}

			foreach (Match match in pattern.Matches(sb.ToString()))
			{
				replacement = string.Empty;
				// Guarantee we get a non-whitespace value for the replacement
				do
				{
					Console.WriteLine("Enter value for: " + match.Value);
					replacement = Console.ReadLine();
				} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));

				int location = sb.ToString().IndexOf(match.Value);
				sb.Remove(location, match.Value.Length).Insert(location, replacement);
			}

			Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
			Console.WriteLine(sb.ToString());
		}
	}
}


// Maximum levels for each pixel.
levels = 60

// Create a random color for each level.
colors = new array[[levels]]
for a = 0 to levels-1
   [email protected] = new color[randomFloat[0,1], randomFloat[0,1], randomFloat[0,1]]

// Make this number smaller for higher resolution.
stepsize = .005

g = new graphics
g.antialiased[false]

for im = -1.2 to 1.2 step stepsize
{
   imag = i * im
   for real = -2 to 1 step stepsize
   {
      C = real + imag
      z = 0
      count = -1

      do
      {
         z = z^2 + C
         count=count+1;
      } while abs[z] < 4 and count < levels

      g.color[[email protected]((count-1) mod levels)]
      g.fillRectSize[real, im, stepsize, stepsize]
   }
}

g.show[]


(ns magic.rosetta
    (:require [clojure.string :as str]))

(defn mad-libs
    "Write a program to create a Mad Libs like story.
     The program should read an arbitrary multiline story from input.
     The story will be terminated with a blank line.
     Then, find each replacement to be made within the story,
     ask the user for a word to replace it with, and make all the replacements.
     Stop when there are none left and print the final story.
     The input should be an arbitrary story in the form:
     <name> went for a walk in the park. <he or she>
     found a <noun>. <name> decided to take it home.
     Given this example, it should then ask for a name,
     a he or she and a noun (<name> gets replaced both times with the same value). "
    []
    (let
        [story (do
            (println "Please enter story:")
            (loop [story []]
                (let [line (read-line)]
                    (if (empty? line)
                        (str/join "\n" story)
                        (recur (conj story line))))))
         tokens (set (re-seq #"<[^<>]+>" story))
         story-completed (reduce
            (fn [s t]
                (str/replace s t (do
                    (println (str "Substitute " t ":"))
                    (read-line))))
            story
            tokens)]
        (println (str
            "Here is your story:\n"
            "------------------------------------\n"
            story-completed))))
; Sample run at REPL:
;
; user=> (magic.rosetta/mad-libs)
; Please enter story:
; One day <who> wake up at <where>.
; <who> decided to <do something>.
; While <who> <do something>, strange man
; appears and gave <who> a <thing>.

; Substitute <where>:
; Sweden
; Substitute <thing>:
; Nobel prize
; Substitute <who>:
; Bob Dylan
; Substitute <do something>:
; walk
; Here is your story:
; ------------------------------------
; One day Bob Dylan wake up at Sweden.
; Bob Dylan decided to walk.
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.


10 rem mad lib for rosetta code
15 dim bf$(100),wd$(50),tg$(50):tb=49152
20 print chr$(147);chr$(14);"Mad Lib Processor":print
25 gosub 1000
30 gosub 100:gosub 250:gosub 300:gosub 400
40 print:print:print "Again? ";:gosub 500:print k$
45 if k$<>"y" then end
50 goto 20
100 tg=1:for i=1 to bp:n$="":mo=0
105 t$=bf$(i)
110 for j=1 to len(t$)
115 ch$=mid$(t$,j,1)
120 if ch$="<" then mo=1:goto 140
125 if ch$=">" then mo=0:gosub 200:n$=n$+wd$:tg$="":goto 140
130 if mo=0 then n$=n$+ch$
135 if mo=1 then tg$=tg$+ch$
140 next j
145 bf$(i)=n$
150 next i
155 return
200 for z=1 to tg
205 if tg$(z)=tg$ then wd$=wd$(z):return
210 next z
215 tg=tg+1:tg$(tg)=tg$
220 print "Enter a ";tg$(tg);:input wd$
225 wd$(tg)=wd$
230 return
250 print chr$(147):print "Processing...":print
255 m=tb:os=0:ns=0:for i=1 to bp-1
260 t$=bf$(i)
265 for c=1 to len(t$):ch$=mid$(t$,c,1)
270 poke m,asc(ch$+chr$(0)):m=m+1:next c
275 next i:rem poke m,32:m=m+1
280 m=m-1:return
300 rem insert cr for word wrap
310 pt=tb:sz=0:ll=0
320 if peek(pt)=32 then gosub 350:if(ll+sz>39) then poke pt,13:ll=-1:sz=0
325 if peek(pt)=13 then ll=-1
330 if pt<>m then pt=pt+1:ll=ll+1:goto 320
340 return
350 rem look ahead to next space
355 nx=pt+1:sz=1
360 if peek(nx)=32 or peek(nx)=13 then return
365 nx=nx+1:sz=sz+1
370 if nx=m then return
375 goto 360
400 rem output memory buffer
401 ln=0:print chr$(147);
410 for i=tb to m:c=peek(i)
420 if c=13 then ln=ln+1
425 print chr$(c);
430 if ln=23 then ln=0:print:gosub 550
440 next i
450 return
500 rem clear buffer, wait for a key
501 get k$:if k$<>"" then 501
505 get k$:if k$="" then 505
510 return
550 rem pause prompt
560 print"[Pause]{CRSR-LEFT 7}";
565 gosub 500
570 print"{SPACE 7}{CRSR-LEFT 7}{CRSR-UP}";
575 return
1000 rem load file
1005 bp=1
1010 print:input "Enter name of file: ";fi$
1020 open 7,8,7,"0:"+fi$+",s,r"
1025 rem gosub 2000
1030 rem if er<>0 then print:gosub 2100:return
1035 get#7,a$
1036 ifa$=chr$(13)thenbf$(bp)=t$+a$:print" ";:t$="":bp=bp+1:goto 1040
1038 t$=t$+a$
1040 if (st and 64)=0 then goto 1035
1049 close 7:gosub 2000
1050 if er=0 then printchr$(147):return
1055 gosub 2100
1060 if er<>0 then goto 1000
1080 return
2000 rem check disk error
2001 open 15,8,15:input#15,er,en$,et$,es$:close15
2010 return
2100 rem print pretty error
2101 ca$=left$(en$,1):ca$=chr$(asc(ca$)+128):en$=ca$+right$(en$,len(en$)-1)
2105 print:print er;"- ";en$;" at .:";et$;" .:";es$
2110 print:print "Press a key.":gosub 500
2115 return


###sysinclude X.uh
$ff0000 sto szin
300 sto maxiter
maxypixel sto YRES
maxxpixel sto XRES
myscreen "Mandelbrot" @YRES @XRES graphic
@YRES 2 / (#d) sto y2
@YRES 2 / (#d) sto x2
#g 0. @XRES (#d) 1.  i: {#d
#g 0. @YRES (#d) 1. {#d
#d
{#d}§i 400. - @x2 - @x2 /
sto x
{#d}  @y2 - @y2 /
sto y
zero#d xa zero#d ya zero iter
(( #d
@x @xa dup* @ya dup* -+
@y @xa *2 @ya *+ sto ya
sto xa #g inc iter
@iter @maxiter >= then((>))
#d ( @xa dup* @ya dup* + 4. > )))
#g @iter @maxiter == { #d
myscreen {d} {d}§i @szin [][]
}{ #d
myscreen {d} {d}§i #g @iter 64 * [][]
}
#d}
#d}
(( ( myscreen key? 10000 usleep )))
myscreen !graphic
end
{ „x” }
{ „x2” }
{ „y” }
{ „y2” }
{ „xa” }
{ „ya” }
{ „iter” }
{ „maxiter” }
{ „szin” }
{ „YRES” }
{ „XRES” }
{ „myscreen” }


import std.stdio, std.regex, std.algorithm, std.string, std.array;

void main() {
    writeln("Enter a story template, terminated by an empty line:");
    string story;
    while (true) {
        auto line = stdin.readln().strip();
        if (line.empty) break;
        story ~= line ~ "\n";
    }

    auto re = regex("<.+?>", "g");
    auto fields = story.match(re).map!q{a.hit}().array().sort().uniq();
    foreach (field; fields) {
        writef("Enter a value for '%s': ", field[1 .. $ - 1]);
        story = story.replace(field, stdin.readln().strip());
    }

    writeln("\nThe story becomes:\n", story);
}


-module(madlib).
-compile(export_all).

main() ->
    main([]).

main([]) ->
    madlib(standard_io);
main([File]) ->
    {ok, F} = file:open(File,read),
    madlib(F).

madlib(Device) ->
    {Dict, Lines} = parse(Device),
    Substitutions = prompt(Dict),
    print(Substitutions, Lines).

prompt(Dict) ->
    Keys = dict:fetch_keys(Dict),
    lists:foldl(fun (K,D) ->
                        S = io:get_line(io_lib:format("Please name a ~s: ",[K])),
                        dict:store(K, lists:reverse(tl(lists:reverse(S))), D)
                end, Dict, Keys).

print(Dict,Lines) ->
    lists:foreach(fun (Line) ->
                          io:format("~s",[substitute(Dict,Line)])
                  end, Lines).

substitute(Dict,Line) ->
    Keys = dict:fetch_keys(Dict),
    lists:foldl(fun (K,L) ->
                        re:replace(L,K,dict:fetch(K,Dict),[global,{return,list}])
                end, Line, Keys).

parse(Device) ->
    parse(Device, dict:new(),[]).

parse(Device, Dict,Lines) ->
    case io:get_line(Device,"") of
        eof ->
            {Dict, lists:reverse(Lines)};
        "\n" ->
            {Dict, lists:reverse(Lines)};
        Line ->
            parse(Device, parse_line(Dict, Line), [Line|Lines])
    end.

parse_line(Dict, Line) ->
    {match,Matches} = re:run(Line,"<.*?>",[global,{capture,[0],list}]),
    lists:foldl(fun ([M],D) ->
                        dict:store(M,"",D)
                end, Dict, Matches).


F compress(uncompressed)
   V dict_size = 256
   V dictionary = Dict((0 .< dict_size).map(i -> (String(Char(code' i)), i)))
   V w = ‘’
   [Int] result
   L(c) uncompressed
      V wc = w‘’c
      I wc C dictionary
         w = wc
      E
         result.append(dictionary[w])
         dictionary[wc] = dict_size
         dict_size++
         w = c

   I !w.empty
      result.append(dictionary[w])

   R result

F decompress([Int] &compressed)
   V dict_size = 256
   V dictionary = Dict((0 .< dict_size).map(i -> (i, String(Char(code' i)))))
   V result = ‘’
   V w = String(Char(code' compressed.pop(0)))
   result ‘’= w
   L(k) compressed
      V entry = ‘’
      I k C dictionary
         entry = dictionary[k]
      E I k == dict_size
         entry = w‘’w[0]
      E
         exit(‘Bad compressed k: ’k)
      result ‘’= entry
      dictionary[dict_size] = w‘’entry[0]
      dict_size++
      w = entry

   R result

V compressed = compress(‘TOBEORNOTTOBEORTOBEORNOT’)
print(compressed)
print(decompress(&compressed))


default(f32)

type complex = (f32, f32)

fun dot(c: complex): f32 =
  let (r, i) = c
  in r * r + i * i

fun multComplex(x: complex, y: complex): complex =
  let (a, b) = x
  let (c, d) = y
  in (a*c - b * d,
      a*d + b * c)

fun addComplex(x: complex, y: complex): complex =
  let (a, b) = x
  let (c, d) = y
  in (a + c,
      b + d)

fun divergence(depth: int, c0: complex): int =
  loop ((c, i) = (c0, 0)) = while i < depth && dot(c) < 4.0 do
    (addComplex(c0, multComplex(c, c)),
     i + 1)
  in i

fun mandelbrot(screenX: int, screenY: int, depth: int, view: (f32,f32,f32,f32)): [screenX][screenY]int =
  let (xmin, ymin, xmax, ymax) = view
  let sizex = xmax - xmin
  let sizey = ymax - ymin
  in map (fn (x: int): [screenY]int  =>
           map  (fn (y: int): int  =>
                  let c0 = (xmin + (f32(x) * sizex) / f32(screenX),
                            ymin + (f32(y) * sizey) / f32(screenY))
                  in divergence(depth, c0))
                (iota screenY))
         (iota screenX)

fun main(screenX: int, screenY: int, depth: int, xmin: f32, ymin: f32, xmax: f32, ymax: f32): [screenX][screenY]int =
  mandelbrot(screenX, screenY, depth, (xmin, ymin, xmax, ymax))


USING: formatting io kernel make regexp sequences sets splitting ;
IN: rosetta-code.mad-libs

: get-mad-lib ( -- str )
    "Enter a mad lib. A blank line signals end of input." print
    [
        [ "> " write flush readln dup , empty? f t ? ] loop
    ] { } make harvest "\n" join ;

: find-replacements ( str -- seq )
    R/ <[\w\s]+>/ all-matching-subseqs members ;

: query ( str -- str )
    rest but-last "Enter a(n) %s: " printf flush readln ;

: replacements ( str seq -- str )
    dup [ query ] map [ replace ] 2each ;

: mad-libs ( -- )
    get-mad-lib dup find-replacements replacements nl print ;

MAIN: mad-libs


Reads a story in template form, containing special entries such as <dog's name> amongst the text.
You will be invited to supply a replacement text for each such entry, as encountered,
after which the story will be presented with your substitutions made.


Dim As String con, cadena
cadena = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
Dim As Integer k = Instr(cadena, "<")

Print "La historia: "
Print cadena & Chr(10)
While k
    Dim As String reemplaza = Mid(cadena, k, Instr(cadena, ">") - k + 1)
    Print "What should replace "; reemplaza; : Input con
    While k
        cadena = Left(cadena, k-1) & con & Mid(cadena, k + Len(reemplaza))
        k = Instr(k, cadena, reemplaza)
    Wend
    k = Instr(cadena, "<")
Wend
Print Chr(10) & "La historia final: "
Print cadena & Chr(10)


package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

func main() {
    pat := regexp.MustCompile("<.+?>")
    if len(os.Args) != 2 {
        fmt.Println("usage: madlib <story template file>")
        return
    }
    b, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmpl := string(b)
    s := []string{}          // patterns in order of appearance
    m := map[string]string{} // mapping from patterns to replacements
    for _, p := range pat.FindAllString(tmpl, -1) {
        if _, ok := m[p]; !ok {
            m[p] = ""
            s = append(s, p)
        }
    }
    fmt.Println("Enter replacements:")
    br := bufio.NewReader(os.Stdin)
    for _, p := range s {
        for {
            fmt.Printf("%s: ", p[1:len(p)-1])
            r, isPre, err := br.ReadLine()
            if err != nil {
                log.Fatal(err)
            }
            if isPre {
                log.Fatal("you're not playing right. :P")
            }
            s := strings.TrimSpace(string(r))
            if s == "" {
                fmt.Println("  hmm?")
                continue
            }
            m[p] = s
            break
        }
    }
    fmt.Println("\nYour story:\n")
    fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {
        return m[p]
    }))
}


package LZW is

   MAX_CODE : constant := 4095;

   type Codes is new Natural range 0 .. MAX_CODE;
   type Compressed_Data is array (Positive range <>) of Codes;

   function Compress (Cleartext : in String) return Compressed_Data;
   function Decompress (Data : in Compressed_Data) return String;

end LZW;


compress: function [str][
    dict: #[]
    loop 0..255 'i -> dict\[to :char i]: i

    w: ""
    result: new []
    loop str 'c [
        wc: w ++ c
        if? key? dict wc -> w: wc
        else [
            'result ++ dict\[w]
            dict\[wc]: size dict
            w: to :string c
        ]
    ]

    if 0 < size w -> 'result ++ dict\[w]
    return result
]

decompress: function [compressed][
    dict: #[]
    arr: new compressed
    loop 0..255 'i -> dict\[i]: to :string to :char i

    w: dict\[first arr]
    remove 'arr .index 0

    result: w
    loop arr 'k [
        entry: ""
        if? key? dict k -> entry: dict\[k]
        else [
            if? k = size dict -> entry: w ++ first w
            else -> panic ~"Error with compressed: |k|"
        ]
        'result ++ entry
        dict\[size dict]: w ++ first entry
        w: entry
    ]
    return result
]

compressed: compress "TOBEORNOTTOBEORTOBEORNOT"
print "Compressed:"
print compressed
print ""

decompressed: decompress compressed
print "Decompressed:"
print decompressed


_xmin    = -8601
_xmax    =  2867
_ymin    = -4915
_ymax    =  4915
_maxiter =  32
_dx = ( _xmax - _xmin ) / 79
_dy = ( _ymax - _ymin ) / 24

void local fn MandelbrotSet
  printf @"\n"
  SInt32 cy = _ymin
  while ( cy <= _ymax )
    SInt32 cx = _xmin
    while ( cx <= _xmax )
      SInt32   x = 0
      SInt32   y = 0
      SInt32  x2 = 0
      SInt32  y2 = 0
      SInt32 iter = 0
      while ( iter < _maxiter )
        if ( x2 + y2 > 16384 ) then break
        y = ( ( x  * y ) >> 11 ) + (SInt32)cy
        x = x2 - y2 + (SInt32)cx
        x2 = ( x * x ) >> 12
        y2 = ( y * y ) >> 12
        iter++
      wend
      print fn StringWithFormat( @"%3c", iter + 32 );
      cx += _dx
    wend
    printf @"\n"
    cy += _dy
  wend
end fn

window 1, @"Mandelbrot Set", ( 0, 0, 820, 650 )
WindowSetBackgroundColor( 1, fn ColorBlack )
text @"Impact", 10.0, fn ColorWithRGB( 1.000, 0.800, 0.000, 1.0 )

fn MandelbrotSet

HandleEvents


import System.IO (stdout, hFlush)

import System.Environment (getArgs)

import qualified Data.Map as M (Map, lookup, insert, empty)

getLines :: IO [String]
getLines = reverse <$> getLines_ []
  where
    getLines_ xs = do
      line <- getLine
      case line of
        [] -> return xs
        _ -> getLines_ $ line : xs

prompt :: String -> IO String
prompt p = putStr p >> hFlush stdout >> getLine

getKeyword :: String -> Maybe String
getKeyword ('<':xs) = getKeyword_ xs []
  where
    getKeyword_ [] _ = Nothing
    getKeyword_ (x:'>':_) acc = Just $ '<' : reverse ('>' : x : acc)
    getKeyword_ (x:xs) acc = getKeyword_ xs $ x : acc
getKeyword _ = Nothing

parseText :: String -> M.Map String String -> IO String
parseText [] _ = return []
parseText line@(l:lx) keywords =
  case getKeyword line of
    Nothing -> (l :) <$> parseText lx keywords
    Just keyword -> do
      let rest = drop (length keyword) line
      case M.lookup keyword keywords of
        Nothing -> do
          newword <- prompt $ "Enter a word for " ++ keyword ++ ": "
          rest_ <- parseText rest $ M.insert keyword newword keywords
          return $ newword ++ rest_
        Just knownword -> do
          rest_ <- parseText rest keywords
          return $ knownword ++ rest_

main :: IO ()
main = do
  args <- getArgs
  nlines <-
    case args of
      [] -> unlines <$> getLines
      arg:_ -> readFile arg
  nlines_ <- parseText nlines M.empty
  putStrLn ""
  putStrLn nlines_


CONST lzw_data$ = "TOBEORNOTTOBEORTOBEORNOT"

PRINT "LZWData: ", lzw_data$
encoded$ = Encode_LZW$(lzw_data$)
PRINT "Encoded: ", encoded$
PRINT "Decoded: ", Decode_LZW$(encoded$)

'----------------------------------------------------------

FUNCTION Encode_LZW$(sample$)

    LOCAL dict ASSOC int
    LOCAL ch$, buf$, result$
    LOCAL nr, x

    FOR nr = 0 TO 255
        dict(CHR$(nr)) = nr
    NEXT

    FOR x = 1 TO LEN(sample$)

        ch$ = MID$(sample$, x, 1)

        IF dict(buf$ & ch$) THEN
            buf$ = buf$ & ch$
        ELSE
            result$ = APPEND$(result$, 0, STR$(dict(buf$)))
            dict(buf$ & ch$) = nr
            INCR nr
            buf$ = ch$
        END IF
    NEXT

    result$ = APPEND$(result$, 0, STR$(dict(buf$)))

    RETURN result$

END FUNCTION

'----------------------------------------------------------

FUNCTION Decode_LZW$(sample$)

    LOCAL list$ ASSOC STRING
    LOCAL old$, ch$, x$, out$, result$
    LOCAL nr

    FOR nr = 0 TO 255
        list$(STR$(nr)) = CHR$(nr)
    NEXT

    old$ = TOKEN$(sample$, 1)

    ch$ = list$(old$)
    result$ = ch$

    FOR x$ IN LAST$(sample$, 1)

        IF NOT(LEN(list$(x$))) THEN
            out$ = list$(old$)
            out$ = out$ & ch$
        ELSE
            out$ = list$(x$)
        END IF

        result$ = result$ & out$
        ch$ = LEFT$(out$, 1)
        list$(STR$(nr)) = list$(old$) & ch$

        INCR nr
        old$ = x$
    NEXT

    RETURN result$

END FUNCTION


      plaintext$ = "TOBEORNOTTOBEORTOBEORNOT"
      encodeLZW$ = FNencodeLZW(plaintext$)
      FOR i% = 1 TO LEN(encodeLZW$) STEP 2
        PRINT ; ASCMID$(encodeLZW$,i%) + 256*ASCMID$(encodeLZW$,i%+1) " " ;
      NEXT
      PRINT ' FNdecodeLZW(encodeLZW$)
      END

      DEF FNencodeLZW(i$)
      LOCAL c%, d%, i%, l%, o$, w$, dict$()
      DIM dict$(4095)
      FOR i% = 0 TO 255 : dict$(i%) = CHR$(i%) : NEXT
      l% = i%
      i% = 1
      w$ = LEFT$(i$,1)
      REPEAT
        d% = 0
        REPEAT
          c% = d%
          IF i% > LEN(i$) EXIT REPEAT
          FOR d% = 1 TO l%-1
            IF w$ = dict$(d%) EXIT FOR
          NEXT d%
          IF d% < l% i% += 1 : w$ += MID$(i$, i%, 1)
        UNTIL d% >= l%
        dict$(l%) = w$ : l% += 1 : w$ = RIGHT$(w$)
        o$ += CHR$(c% MOD 256) + CHR$(c% DIV 256)
      UNTIL i% >= LEN(i$)
      = o$

      DEF FNdecodeLZW(i$)
      LOCAL c%, i%, l%, o$, t$, w$, dict$()
      DIM dict$(4095)
      FOR i% = 0 TO 255 : dict$(i%) = CHR$(i%) : NEXT
      l% = i%
      c% = ASC(i$) + 256*ASCMID$(i$,2)
      w$ = dict$(c%)
      o$ = w$
      IF LEN(i$) < 4 THEN = o$
      FOR i% = 3 TO LEN(i$) STEP 2
        c% = ASCMID$(i$,i%) + 256*ASCMID$(i$,i%+1)
        IF c% < l% t$ = dict$(c%) ELSE t$ = w$ + LEFT$(w$,1)
        o$ += t$
        dict$(l%) = w$ + LEFT$(t$,1)
        l% += 1
        w$ = t$
      NEXT
      = o$


const int MaxIterations = 1000;
const vec2 Focus = vec2(-0.51, 0.54);
const float Zoom = 1.0;

vec3
color(int iteration, float sqLengthZ) {
    // If the point is within the mandlebrot set
    // just color it black
    if(iteration == MaxIterations)
        return vec3(0.0);

    // Else we give it a smoothed color
   	float ratio = (float(iteration) - log2(log2(sqLengthZ))) / float(MaxIterations);

    // Procedurally generated colors
    return mix(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 0.0), sqrt(ratio));
}

void
mainImage(out vec4 fragColor, in vec2 fragCoord) {
    // C is the aspect-ratio corrected UV coordinate.
    vec2 c = (-1.0 + 2.0 * fragCoord / iResolution.xy) * vec2(iResolution.x / iResolution.y, 1.0);

    // Apply scaling, then offset to get a zoom effect
    c = (c * exp(-Zoom)) + Focus;
	vec2 z = c;

    int iteration = 0;

    while(iteration < MaxIterations) {
        // Precompute for efficiency
   	float zr2 = z.x * z.x;
        float zi2 = z.y * z.y;

        // The larger the square length of Z,
        // the smoother the shading
        if(zr2 + zi2 > 32.0) break;

        // Complex multiplication, then addition
    	z = vec2(zr2 - zi2, 2.0 * z.x * z.y) + c;
        ++iteration;
    }

    // Generate the colors
    fragColor = vec4(color(iteration, dot(z,z)), 1.0);

    // Apply gamma correction
    fragColor.rgb = pow(fragColor.rgb, vec3(0.5));
}


procedure main()
   ml := "<name> went for a walk in the park. There <he or she> _
          found a <noun>. <name> decided to take it home."  # sample
   MadLib(ml)                                               # run it
end

link strings

procedure MadLib(story)
   write("Please provide words for the following:")
   V := []
   story ? while ( tab(upto('<')), put(V,tab(upto('>')+1)) )
   every writes(v := !set(V)," : ") do
      story := replace(story,v,read())
   write("\nYour MadLib follows:\n",story)
end


require 'general/misc/prompt regex'

madlib=:3 :0
  smoutput 'Please enter the story template'
  smoutput 'See http://rosettacode.org/wiki/Mad_Libs for details'
  t=.''
  while.#l=.prompt '' do. t=.t,l,LF end.
  repl=. ~.'<[^<>]*>' rxall t
  for_bef. repl do.
    aft=. prompt (}.}:;bef),': '
    t=.t rplc bef,<aft
  end.
  t
)


import java.util.*;

public class MadLibs {

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

        String name, gender, noun;

        System.out.print("Enter a name: ");
        name = input.next();

        System.out.print("He or she: ");
        gender = input.next();

        System.out.print("Enter a noun: ");
        noun = input.next();

        System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");

    }
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

/* -------- aux stuff ---------- */
void* mem_alloc(size_t item_size, size_t n_item)
{
  size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
  x[0] = item_size;
  x[1] = n_item;
  return x + 2;
}

void* mem_extend(void *m, size_t new_n)
{
  size_t *x = (size_t*)m - 2;
  x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
  if (new_n > x[1])
    memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
  x[1] = new_n;
  return x + 2;
}

inline void _clear(void *m)
{
  size_t *x = (size_t*)m - 2;
  memset(m, 0, x[0] * x[1]);
}

#define _new(type, n) mem_alloc(sizeof(type), n)
#define _del(m)   { free((size_t*)(m) - 2); m = 0; }
#define _len(m)   *((size_t*)m - 1)
#define _setsize(m, n)  m = mem_extend(m, n)
#define _extend(m)  m = mem_extend(m, _len(m) * 2)

/* ----------- LZW stuff -------------- */
typedef uint8_t byte;
typedef uint16_t ushort;

#define M_CLR 256 /* clear table marker */
#define M_EOD 257 /* end-of-data marker */
#define M_NEW 258 /* new code index */

/* encode and decode dictionary structures.
   for encoding, entry at code index is a list of indices that follow current one,
   i.e. if code 97 is 'a', code 387 is 'ab', and code 1022 is 'abc',
   then dict[97].next['b'] = 387, dict[387].next['c'] = 1022, etc. */
typedef struct {
  ushort next[256];
} lzw_enc_t;

/* for decoding, dictionary contains index of whatever prefix index plus trailing
   byte.  i.e. like previous example,
    dict[1022] = { c: 'c', prev: 387 },
    dict[387]  = { c: 'b', prev: 97 },
    dict[97]   = { c: 'a', prev: 0 }
   the "back" element is used for temporarily chaining indices when resolving
   a code to bytes
 */
typedef struct {
  ushort prev, back;
  byte c;
} lzw_dec_t;

byte* lzw_encode(byte *in, int max_bits)
{
  int len = _len(in), bits = 9, next_shift = 512;
  ushort code, c, nc, next_code = M_NEW;
  lzw_enc_t *d = _new(lzw_enc_t, 512);

  if (max_bits > 15) max_bits = 15;
  if (max_bits < 9 ) max_bits = 12;

  byte *out = _new(ushort, 4);
  int out_len = 0, o_bits = 0;
  uint32_t tmp = 0;

  inline void write_bits(ushort x) {
    tmp = (tmp << bits) | x;
    o_bits += bits;
    if (_len(out) <= out_len) _extend(out);
    while (o_bits >= 8) {
      o_bits -= 8;
      out[out_len++] = tmp >> o_bits;
      tmp &= (1 << o_bits) - 1;
    }
  }

  //write_bits(M_CLR);
  for (code = *(in++); --len; ) {
    c = *(in++);
    if ((nc = d[code].next[c]))
      code = nc;
    else {
      write_bits(code);
      nc = d[code].next[c] = next_code++;
      code = c;
    }

    /* next new code would be too long for current table */
    if (next_code == next_shift) {
      /* either reset table back to 9 bits */
      if (++bits > max_bits) {
        /* table clear marker must occur before bit reset */
        write_bits(M_CLR);

        bits = 9;
        next_shift = 512;
        next_code = M_NEW;
        _clear(d);
      } else  /* or extend table */
        _setsize(d, next_shift *= 2);
    }
  }

  write_bits(code);
  write_bits(M_EOD);
  if (tmp) write_bits(tmp);

  _del(d);

  _setsize(out, out_len);
  return out;
}

byte* lzw_decode(byte *in)
{
  byte *out = _new(byte, 4);
  int out_len = 0;

  inline void write_out(byte c)
  {
    while (out_len >= _len(out)) _extend(out);
    out[out_len++] = c;
  }

  lzw_dec_t *d = _new(lzw_dec_t, 512);
  int len, j, next_shift = 512, bits = 9, n_bits = 0;
  ushort code, c, t, next_code = M_NEW;

  uint32_t tmp = 0;
  inline void get_code() {
    while(n_bits < bits) {
      if (len > 0) {
        len --;
        tmp = (tmp << 8) | *(in++);
        n_bits += 8;
      } else {
        tmp = tmp << (bits - n_bits);
        n_bits = bits;
      }
    }
    n_bits -= bits;
    code = tmp >> n_bits;
    tmp &= (1 << n_bits) - 1;
  }

  inline void clear_table() {
    _clear(d);
    for (j = 0; j < 256; j++) d[j].c = j;
    next_code = M_NEW;
    next_shift = 512;
    bits = 9;
  };

  clear_table(); /* in case encoded bits didn't start with M_CLR */
  for (len = _len(in); len;) {
    get_code();
    if (code == M_EOD) break;
    if (code == M_CLR) {
      clear_table();
      continue;
    }

    if (code >= next_code) {
      fprintf(stderr, "Bad sequence\n");
      _del(out);
      goto bail;
    }

    d[next_code].prev = c = code;
    while (c > 255) {
      t = d[c].prev; d[t].back = c; c = t;
    }

    d[next_code - 1].c = c;

    while (d[c].back) {
      write_out(d[c].c);
      t = d[c].back; d[c].back = 0; c = t;
    }
    write_out(d[c].c);

    if (++next_code >= next_shift) {
      if (++bits > 16) {
        /* if input was correct, we'd have hit M_CLR before this */
        fprintf(stderr, "Too many bits\n");
        _del(out);
        goto bail;
      }
      _setsize(d, next_shift *= 2);
    }
  }

  /* might be ok, so just whine, don't be drastic */
  if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr);

  _setsize(out, out_len);
bail: _del(d);
  return out;
}

int main()
{
  int i, fd = open("unixdict.txt", O_RDONLY);

  if (fd == -1) {
    fprintf(stderr, "Can't read file\n");
    return 1;
  };

  struct stat st;
  fstat(fd, &st);

  byte *in = _new(char, st.st_size);
  read(fd, in, st.st_size);
  _setsize(in, st.st_size);
  close(fd);

  printf("input size:   %d\n", _len(in));

  byte *enc = lzw_encode(in, 9);
  printf("encoded size: %d\n", _len(enc));

  byte *dec = lzw_decode(enc);
  printf("decoded size: %d\n", _len(dec));

  for (i = 0; i < _len(dec); i++)
    if (dec[i] != in[i]) {
      printf("bad decode at %d\n", i);
      break;
    }

  if (i == _len(dec)) printf("Decoded ok\n");

  _del(in);
  _del(enc);
  _del(dec);

  return 0;
}


function madlibs(template)
    println("The story template is:\n", template)
    fields = Set(getfield.(collect(eachmatch(r"<[^>]+>", template)), :match))
    print("\nInput a comma-separated list of words to replace the following items:",
          join(fields, ", "), "\n -> ")
    values = split(readline(STDIN), ",")
    for (m, v) in zip(fields, values)
        template = replace(template, m, v)
    end
    println("\nThe story becomes:\n", template)
end

const template = """
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
"""

madlibs(template)


// version 1.1.2

fun main(args: Array<String>) {
    println("Please enter a multi-line story template terminated by a blank line\n")
    val sb  = StringBuilder()
    while (true) {
        val line = readLine()!!
        if (line.isEmpty()) break
        sb.append("$line\n") // preserve line breaks
    }
    var story = sb.toString()
    // identify blanks
    val r = Regex("<.*?>")
    val blanks = r.findAll(story).map { it.value }.distinct()
    println("Please enter your replacements for the following 'blanks' in the story:")
    for (blank in blanks) {
        print("${blank.drop(1).dropLast(1)} : ")
        val repl = readLine()!!
        story = story.replace(blank, repl)
    }
    println("\n$story")
}


temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(temp$,"<")
while k
    replace$   = mid$(temp$,k,instr(temp$,">")-k + 1)
    print "Replace:";replace$;" with:"; :input with$
    while k
        temp$  = left$(temp$,k-1) + with$ + mid$(temp$,k + len(replace$))
        k      = instr(temp$,replace$,k)
    wend
k = instr(temp$,"<")
wend
print temp$
wait


using System;
using System.Collections.Generic;
using System.Text;

namespace LZW
{
    public class Program
    {
        public static void Main(string[] args)
        {
            List<int> compressed = Compress("TOBEORNOTTOBEORTOBEORNOT");
            Console.WriteLine(string.Join(", ", compressed));
            string decompressed = Decompress(compressed);
            Console.WriteLine(decompressed);
        }

        public static List<int> Compress(string uncompressed)
        {
            // build the dictionary
            Dictionary<string, int> dictionary = new Dictionary<string, int>();
            for (int i = 0; i < 256; i++)
                dictionary.Add(((char)i).ToString(), i);

            string w = string.Empty;
            List<int> compressed = new List<int>();

            foreach (char c in uncompressed)
            {
                string wc = w + c;
                if (dictionary.ContainsKey(wc))
                {
                    w = wc;
                }
                else
                {
                    // write w to output
                    compressed.Add(dictionary[w]);
                    // wc is a new sequence; add it to the dictionary
                    dictionary.Add(wc, dictionary.Count);
                    w = c.ToString();
                }
            }

            // write remaining output if necessary
            if (!string.IsNullOrEmpty(w))
                compressed.Add(dictionary[w]);

            return compressed;
        }

        public static string Decompress(List<int> compressed)
        {
            // build the dictionary
            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            for (int i = 0; i < 256; i++)
                dictionary.Add(i, ((char)i).ToString());

            string w = dictionary[compressed[0]];
            compressed.RemoveAt(0);
            StringBuilder decompressed = new StringBuilder(w);

            foreach (int k in compressed)
            {
                string entry = null;
                if (dictionary.ContainsKey(k))
                    entry = dictionary[k];
                else if (k == dictionary.Count)
                    entry = w + w[0];

                decompressed.Append(entry);

                // new sequence; add it to the dictionary
                dictionary.Add(dictionary.Count, w + entry[0]);

                w = entry;
            }

            return decompressed.ToString();
        }
    }
}


set terminal png
set output 'mandelbrot.png'


text = Import[
   InputString["Enter the filename of the story template:"]];
answers =
  AssociationMap[
   InputString[
     "Enter a" <>
      If[StringMatchQ[#,
        "<" ~~ Alternatives @@ Characters["aeiou"] ~~ ___], "n", ""] <>
       " " <> StringTrim[#, "<" | ">"] <> ":"] &,
   Union[StringCases[text, RegularExpression["<[^>]+>"]]]];
Print[StringReplace[text, Normal[answers]]];


def madlib(template)
    // loop through and find/remove all of the replacements
    replacements = {}
    ind = 0
    while ind < len(template)
        // check if we have found a replacement to perform
        if template[ind] = "<"
            // get the name of the replacement and add it to the list
            // if we haven't already encountered it
            ind += 1
            replace_name = ""
            while template[ind] != ">"
                replace_name += template[ind]
                ind += 1
            end while

            if not replace_name in replacements
                replacements.append(replace_name)
            end if
            ind += 1
        else
            ind += 1
        end if
    end while

    // prompt the user for replacement values
    replacement_values = {}
    for phrase in replacements
        replacement_values.append(input("enter " + phrase + ": "))
    end for
    println

    // make replacements and output the story
    ind = 0
    while ind < len(template)
        // check if we have found a replacement to perform
        if template[ind] = "<"
            // get the name of the replacement
            ind += 1
            replace_name = ""
            while template[ind] != ">"
                replace_name += template[ind]
                ind += 1
            end while

            // output the replacement
            print replacement_values[replacements[replace_name]]
            ind += 1
        else
            print template[ind]
            ind += 1
        end if
    end while
end madlib

madlib("<name> went for a walk in the park. <he or she> " + \
       "found a <noun>. <name> decided to take it home.")


import rdstdin, re, algorithm, sequtils, strutils

#let templ = readLineFromStdin "Enter your story: "
const templ = """<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home."""

echo "The story template is:\n", templ
var fields = templ.findAll re"<[^>]+>"
fields.sort(cmp)
fields = deduplicate fields
let values = readLineFromStdin("\nInput a comma-separated list of words to replace the following items\n  " & fields.join(",") & ": ").split(",")

var story = templ
for f,v in zip(fields, values).items:
  story = story.replace(f, v)
echo "\nThe story becomes:\n\n", story


: madlibs
| story i word |

   "" while(System.Console askln dup notEmpty) [ + ] drop ->story

   while(story indexOf('<') dup ->i notNull) [
      story extract(i, story indexOfFrom('>', i)) ->word
      story replaceAll(word, "Word for" . word . System.Console askln) ->story
      ]

   "Your story :" . story println ;


Program Madlib; Uses DOS, crt; {See, for example, https://en.wikipedia.org/wiki/Mad_Libs}
{Reads the lines of a story but which also contain <xxx> sequences. For each value of xxx,
 found as the lines of the story are read, a request is made for a replacement text.
 The story is then written out with the corresponding replacements made.}
{Concocted by R.N.McLean (whom God preserve), Victoria university, NZ.}
 Procedure Croak(gasp: string); {A dying message.}
  Begin
   Writeln(' Eurghfff...');
   Writeln(Gasp);
   HALT;
  End;
 var inf: text; {Drivelstuff.}
 const StoryLimit = 66;TableLimit = 65;		{Big enough.}
 var Story: array[1..StoryLimit] of string;	{Otherwise, use a temporary disc file.}
 var Target,Replacement: array[1..TableLimit] of string;
 var StoryLines,TableCount: integer;		{Usage.}

 Function Reading(var inf: text;var Aline: string): boolean;
  Begin
   Aline:='';
   Reading:=true;
   if eoln(inf) then Reading:=false	{Agh! Why can't the read statement return true/false?}
    else ReadLn(inf,Aline);
   if Aline = '' then Reading:=false;	{Specified that a blank line ends the story.}
  End;

 Procedure Inspect(text: string); Forward;{I'd rather have multi-pass compilation than deal with this.}

 Procedure Table(it: string);	{Check it as a target, and obtain its replacement.}
  var i: integer;	{A stepper.}
  Begin
   for i:=1 to TableCount do if it = Target[i] then exit;	{Already in the table?}
   if TableCount >= TableLimit then Croak('Too many table entries!');	{No. Room for another?}
   inc(TableCount);				{Yes.}
   Target[TableCount]:=it;			{Include the < and > to preclude partial matches.}
   write('Enter your text for ',it,': ');	{Pretty please?}
   readln(Replacement[TableCount]);		{Thus.}
   Inspect(Replacement[TableCount]);		{Enable full utilisation.}
  End; {of Table.}

 var InDeep: integer;	{Counts inspection recursion.}
 Procedure Inspect(text: string);		{Look for <...> in text.}
  var i: integer;	{A stepper.}
  var mark: integer;	{Fingers the latest < in Aline.}
  Begin
   inc(InDeep);		{Supply an opportunity, and fear the possibilities.}
   if InDeep > 28 then Croak('Excessive recursion! Inspecting ' + text);
   for i:=1 to Length(text) do	{Now scan the line for trouble.}
    if text[i] = '<' then mark:=i	{Trouble starts here? Just mark its place.}
     else if text[i] = '>' then	{Trouble ends here?}
      Table(copy(text,mark,i - mark + 1));	{Deal with it.}
   dec(InDeep);		{I'm done.}
  End; {of Inspect.}

 Procedure Swallow(Aline: string);	{Add a line to the story, and inspect it for <...>.}
  Begin
   if StoryLines >= StoryLimit then Croak('Too many lines in the story!');	{Suspicion forever.}
   inc(StoryLines);		{Otherwise, this is safe.}
   Story[StoryLines]:=Aline;	{So save another line.}
   Inspect(Aline);		{Look for any <...> inclusions.}
  End; {of Swallow.}

 var Rolling: integer;		{Counts rolling rolls.}
 Procedure Roll(bumf: string);	{Write a line, with amendments.}
  var last,mark: integer;	{Fingers for the scan.}
  var hit: string;		{Copied once.}
  var i,it: integer;		{Steppers.}
  label hic;	{Oh dear.}
  Begin
   inc(Rolling);	{Here I go.}
   if Rolling > 28 then Croak('Excessive recursion! Rolling ' + bumf);	{Self-expansion is out.}
   last:=0;			{Where the previous text ended.}
   for i:=1 to Length(bumf) do	{Scan the text.}
    if bumf[i] = '<' then mark:=i	{Remember where a <...> starts.}
     else if bumf[i] = '>' then		{So that when the stopper is found,}
      begin				{It can be recognised.}
       Write(copy(bumf,last + 1,mark - last - 1));	{Text up to the <.}
       hit:=copy(bumf,mark,i - mark + 1);	{Grab this once.}
       for it:=1 to TableCount do	{Search my table.}
        if Target[it] = hit then	{A match?}
         begin				{Yes!}
          Roll(Replacement[it]);	{Write this instead.}
          goto hic;			{There is no "exit loop" style statement.}
         end;				{"Exit" exits the procedure or function.}
   hic:last:=i;		{Advance the trailing finger.}
      end;	{On to the next character.}
   Write(copy(bumf,last + 1,Length(bumf) - last));	{Text after the last >, possibly null.}
   dec(Rolling);			{I'm done.}
   if Rolling <= 0 then WriteLn;	{And if this is the first level, add a end-of-line.}
  End;	{of Roll.}

 var inname: string;	{For a file name.}
 var Aline: string;	{A scratchpad.}
 var i: integer;	{A stepper.}
 BEGIN
  InDeep:=0;		{No inspections yet.}
  Rolling:=0;		{No output.}
  inname:=ParamStr(1);	{Perhaps the file name is specified as a run-time parameter.}
  if inname = '' then inname:='Madlib.txt';	{If not, this will do.}
  Assign(inf,inname); Reset(inf);		{Open the input file.}
  StoryLines:=0; TableCount:=0;			{Prepare the counters.}
  while reading(inf,Aline) do Swallow(Aline);	{Read and inspect the story.}
  close(inf);					{Finished with input.}
  for i:=1 to StoryLines do Roll(Story[i]);	{Write the amended story.}
 END.


#include <string>
#include <map>

// Compress a string to a list of output symbols.
// The result will be written to the output iterator
// starting at "result"; the final iterator is returned.
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
  // Build the dictionary.
  int dictSize = 256;
  std::map<std::string,int> dictionary;
  for (int i = 0; i < 256; i++)
    dictionary[std::string(1, i)] = i;

  std::string w;
  for (std::string::const_iterator it = uncompressed.begin();
       it != uncompressed.end(); ++it) {
    char c = *it;
    std::string wc = w + c;
    if (dictionary.count(wc))
      w = wc;
    else {
      *result++ = dictionary[w];
      // Add wc to the dictionary.
      dictionary[wc] = dictSize++;
      w = std::string(1, c);
    }
  }

  // Output the code for w.
  if (!w.empty())
    *result++ = dictionary[w];
  return result;
}

// Decompress a list of output ks to a string.
// "begin" and "end" must form a valid range of ints
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
  // Build the dictionary.
  int dictSize = 256;
  std::map<int,std::string> dictionary;
  for (int i = 0; i < 256; i++)
    dictionary[i] = std::string(1, i);

  std::string w(1, *begin++);
  std::string result = w;
  std::string entry;
  for ( ; begin != end; begin++) {
    int k = *begin;
    if (dictionary.count(k))
      entry = dictionary[k];
    else if (k == dictSize)
      entry = w + w[0];
    else
      throw "Bad compressed k";

    result += entry;

    // Add w+entry[0] to the dictionary.
    dictionary[dictSize++] = w + entry[0];

    w = entry;
  }
  return result;
}

#include <iostream>
#include <iterator>
#include <vector>

int main() {
  std::vector<int> compressed;
  compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
  copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
  std::cout << std::endl;
  std::string decompressed = decompress(compressed.begin(), compressed.end());
  std::cout << decompressed << std::endl;

  return 0;
}


package main

import "fmt"
import "math/cmplx"

func mandelbrot(a complex128) (z complex128) {
    for i := 0; i < 50; i++ {
        z = z*z + a
    }
    return
}

func main() {
    for y := 1.0; y >= -1.0; y -= 0.05 {
        for x := -2.0; x <= 0.5; x += 0.0315 {
            if cmplx.Abs(mandelbrot(complex(x, y))) < 2 {
                fmt.Print("*")
            } else {
                fmt.Print(" ")
            }
        }
        fmt.Println("")
    }
}


#!/usr/bin/perl
use warnings;
use strict;

my $template = shift;
open my $IN, '<', $template or die $!;
my $story = do { local $/ ; <$IN> };

my %blanks;
undef $blanks{$_} for $story =~ m/<(.*?)>/g;

for my $blank (sort keys %blanks) {
    print "$blank: ";
    chomp (my $replacement = <>);
    $blanks{$blank} = $replacement;
}

$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story;


without js -- file i/o, prompt_string
string mlfile = "", -- eg story.txt
mltxt = iff(length(mlfile)?join(read_lines(mlfile),"\n"):"""
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
""")

sequence strings = {}, replacements = {}
integer startpos, endpos=1
while 1 do
    startpos = find('<',mltxt,endpos)
    if startpos=0 then exit end if
    endpos = find('>',mltxt,startpos)
    if endpos=0 then ?"missing >" abort(0) end if
    string s = mltxt[startpos..endpos]
    if not find(s,strings) then
        strings = append(strings,s)
        replacements = append(replacements,prompt_string(sprintf("Enter replacement for %s:",{s})))
    end if
end while
puts(1,substitute_all(mltxt,strings,replacements))


(defn make-dict []
  (let [vals (range 0 256)]
    (zipmap (map (comp #'list #'char) vals) vals)))

(defn compress [#^String text]
  (loop [t (seq text)
         r '()
         w '()
         dict (make-dict)
         s 256]
    (let [c (first t)]
      (if c
        (let [wc (cons c w)]
          (if (get dict wc)
            (recur (rest t) r wc dict s)
            (recur (rest t) (cons (get dict w) r) (list c) (assoc dict wc s) (inc s))))
        (reverse (if w (cons (get dict w) r) r))))))

(compress "TOBEORNOTTOBEORTOBEORNOT")


"<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
true
while
    "<" find dup var ini
    if
        ">" find ini - 1 + ini swap slice var replace
        "Replace: " replace " with: " chain chain input var with nl
        true
        while
            replace with subst
            replace find
        endwhile
        true
    else
        false
    endif
endwhile
print


import util.

go =>
  Story = read_story(),
  println("Fill in the proper values:"),
  nl,
  Map = get_info(get_tags(Story)) ,
  println("\nHere is the story:\n"),
  println(replace_tags(Story,Map)),
  nl.

read_story() = Story =>
  println("Write the story template with <tag> for the tags and finish with an empty line."),
  nl,
  Story1 = read_line(),
  while (Line = read_line(), Line != "")
     Story1 := Story1 ++ " " ++ Line
  end,
  Story = Story1.

%
% Get the tags between <...>.
%
get_tags(S) = Tags =>
  Len = S.length,
  StartPos = [P: {C,P} in zip(S,1..Len), C = '<'],
  EndPos   = [P: {C,P} in zip(S,1..Len), C = '>'],
  Tags = [slice(S,Start,End) : {Start,End}  in zip(StartPos,EndPos)].remove_dups().

%
% Get the tag info from user and return a map
%
get_info(Tags) = Map =>
  Map = new_map(),
  foreach(Tag in Tags)
     printf("%w: ", Tag),
     Map.put(Tag,readln())
  end.

% Replace all the <tags> with user values.
replace_tags(S,Map) = S =>
  foreach(Tag=Value in Map)
    S := replace_string(T,Tag,Value)
  end.

% Picat's replace/3 does not handle substrings well,
% so we roll our own...
replace_string(List,Old,New) = Res =>
  Res = copy_term(List),
  while (find(Res,Old,_,_))
    once(append(Before,Old,After,Res)),
    Res := Before ++ New ++ After
  end.


(de madlib (Template)
   (setq Template (split (chop Template) "<" ">"))
   (let (Reps () Text ())
      (while Template
         (push 'Text (pop 'Template))
         (let? Rep (mapcar pack (split (pop 'Template) ":"))
            (if (assoc (car Rep) Reps)
               (push 'Text (cdr @))
               (until (and
                         (prin "Gimme a(n) " (or (cadr Rep) (car Rep)) ": ")
                         (clip (in NIL (line)))
                         (push 'Text @)
                         (push 'Reps (cons (car Rep) @)) )
                  (prinl "Huh? I got nothing.") ) ) ) )
      (prinl (need 30 '-))
      (prinl (flip Text)) ) )


#!/usr/bin/pike

Stdio.Readline readln = Stdio.Readline();

void print_help()
{
    write(#"Write a Story.

Names or objects in the story can be made variable by
referencing them as <person> <object>, etc.
End the story with an empty line.

Type show to read the story. You will be asked to fill the variables,
and the the story will be shown.

Type help to see this message again.
Type exit to quit.

");
}

void add_line(string input)
{
    array variables = parse_for_variables(input);
    write("Found variables: %{\"%s\" %}\n", variables);
    story += input+"\n";
}

array parse_for_variables(string input)
{
    array vars = Array.flatten(array_sscanf(input, "%*[^<>]%{<%[^<>]>%*[^<>]%}%*[^<>]"));
    return Array.uniq(vars);
}

mapping fill_variables(string story)
{
    array vars = parse_for_variables(story);
    mapping variables = ([]);
    foreach(vars;; string name)
    {
        string value = readln->read(sprintf("Please name a%s %s: ", (<'a','e','i','o','u'>)[name[1]]?"":"n", name));
        if (value != "")
            variables["<"+name+">"] = value;
    }
    return variables;
}

void show_story(string story)
{
    mapping variables = fill_variables(story);
    write("\n"+replace(story, variables));
}

void do_exit()
{
    exit(0);
}

mapping functions = ([ "help":print_help,
                       "show":show_story,
                       "exit":do_exit,
                     ]);
string story = "";

void main()
{
    Stdio.Readline.History readline_history = Stdio.Readline.History(512);
    readln->enable_history(readline_history);

    string prompt="> ";

    print_help();
    while(1)
    {
        string input=readln->read(prompt);
        if(!input)
            exit(0);
        if(input == "")
            show_story(story);
        else if (functions[input])
            functions[input]();
        else add_line(input);
    }
}


lzw = (s) ->
  dct = {} # map substrings to codes between 256 and 4096
  stream = [] # array of compression results

  # initialize basic ASCII characters
  for code_num in [0..255]
    c = String.fromCharCode(code_num)
    dct[c] = code_num
  code_num = 256

  i = 0
  while i < s.length
    # Find word and new_word
    #   word = longest substr already encountered, or next character
    #   new_word = word plus next character, a new substr to encode
    word = ''
    j = i
    while j < s.length
      new_word = word + s[j]
      break if !dct[new_word]
      word = new_word
      j += 1

    # stream out the code for the substring
    stream.push dct[word]

    # build up our encoding dictionary
    if code_num < 4096
      dct[new_word] = code_num
      code_num += 1

    # advance thru the string
    i += word.length
  stream

console.log lzw "TOBEORNOTTOBEORTOBEORNOT"


(declaim (ftype (function (vector vector &optional fixnum fixnum) vector)
                vector-append))
(defun vector-append (old new &optional (start2 0) end2)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (prog1 old
    (let* ((old-fill (fill-pointer old))
           (new-fill (+ old-fill (length new))))
      (when (> new-fill (array-dimension old 0))
        (adjust-array old (* 4 new-fill)))
      (setf (fill-pointer old) new-fill)
      (replace old new :start1 old-fill :start2 start2 :end2 end2))))

(declaim (ftype (function (vector t) vector) vector-append1))
(defun vector-append1 (old new)
  (prog1 old
    (let* ((old-fill (fill-pointer old))
           (new-fill (1+ old-fill)))
      (when (> new-fill (array-dimension old 0))
        (adjust-array old (* 4 new-fill)))
      (setf (fill-pointer old) new-fill)
      (setf (aref old old-fill) new))))

(declaim (ftype (function (&optional t) vector) make-empty-vector))
(defun make-empty-vector (&optional (element-type t))
  (make-array 0 :element-type element-type :fill-pointer 0 :adjustable t))

(declaim (ftype (function (t &optional t) vector) make-vector-with-elt))
(defun make-vector-with-elt (elt &optional (element-type t))
  (make-array 1 :element-type element-type
                :fill-pointer 1
                :adjustable t
                :initial-element elt))

(declaim (ftype (function (vector t) vector) vector-append1-new))
(defun vector-append1-new (old new)
  (vector-append1 (vector-append (make-empty-vector 'octet) old)
                  new))

(declaim (ftype (function (vector vector) vector) vector-append-new))
(defun vector-append-new (old new)
  (vector-append (vector-append (make-empty-vector 'octet) old)
                 new))

(deftype octet () '(unsigned-byte 8))

(declaim (ftype (function () hash-table) build-dictionary))
(defun build-dictionary ()
  (let ((dictionary (make-hash-table :test #'equalp)))
    (loop for i below 256
          do (let ((vec (make-vector-with-elt i 'octet)))
               (setf (gethash vec dictionary) vec)))
    dictionary))

(declaim (ftype (function ((vector octet)) (vector octet))
                lzw-compress-octets))
(defun lzw-compress-octets (octets)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (loop with dictionary-size of-type fixnum = 256
        with w = (make-empty-vector 'octet)
        with result = (make-empty-vector 't)
        with dictionary = (build-dictionary)
        for c across octets
        for wc = (vector-append1-new w c)
        if (gethash wc dictionary) do (setq w wc)
        else do
          (vector-append result (gethash w dictionary))
          (setf (gethash wc dictionary)
                (make-vector-with-elt dictionary-size))
          (incf dictionary-size)
          (setq w (make-vector-with-elt c 'octet))
        finally (unless (zerop (length (the (vector octet) w)))
                  (vector-append result (gethash w dictionary)))
                (return result)))

(declaim (ftype (function (vector) (vector octet)) lzw-decompress))
(defun #1=lzw-decompress (octets)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (when (zerop (length octets))
    (return-from #1# (make-empty-vector 'octet)))
  (loop with dictionary-size = 256
        with dictionary = (build-dictionary)
        with result = (make-vector-with-elt (aref octets 0) 'octet)
        with w = (copy-seq result)
        for i from 1 below (length octets)
        for k = (make-vector-with-elt (aref octets i) 't)
        for entry = (or (gethash k dictionary)
                        (if (equalp k dictionary-size)
                            (vector-append1-new w (aref w 0))
                            (error "bad compresed entry at pos ~S" i)))
        do (vector-append result entry)
           (setf (gethash (make-vector-with-elt dictionary-size) dictionary)
                 (vector-append1-new w (aref entry 0)))
           (incf dictionary-size)
           (setq w entry)
        finally (return result)))

(defgeneric lzw-compress (datum)
  (:method ((string string))
    (lzw-compress (babel:string-to-octets string)))
  (:method ((octets vector))
    (lzw-compress-octets octets)))

(defun lzw-decompress-to-string (octets)
  (babel:octets-to-string (lzw-decompress octets)))

(defun test (string)
  (assert (equal #2=(lzw-decompress-to-string (lzw-compress string)) string) ()
          "Can't compress ~S properly, got ~S instead" string #2#)
  t)


use fmt;
use math;

type complex = struct {
	re: f64,
	im: f64
};

export fn main() void = {
	for (let y = -1.2; y < 1.2; y += 0.05) {
		for (let x = -2.05; x < 0.55; x += 0.03) {
			let z = complex {re = 0.0, im = 0.0};

			for (let m = 0z; m < 100; m += 1) {
				let tz = z;

				z.re = tz.re*tz.re - tz.im*tz.im;
				z.im = tz.re*tz.im + tz.im*tz.re;
				z.re += x;
				z.im += y;
			};
			fmt::print(if (abs(z) < 2f64) '#' else '.')!;
		};
		fmt::println()!;
	};
};

fn abs(z: complex) f64 = {
	return math::sqrtf64(z.re*z.re + z.im*z.im);
};


(stringrange, stringsize):                            /* 2 Nov. 2013 */
Mad_Libs: procedure options (main);
   declare (line, left, right) character (100) varying;
   declare true bit(1) value ('1'b), false bit (1) value ('0'b);
   declare name    character (20) varying, seen_name    bit (1) initial (false);
   declare pronoun character (20) varying, seen_pronoun bit (1) initial (false);
   declare noun    character (20) varying, seen_noun    bit (1) initial (false);
   declare replaced_all bit (1);
   declare in file input;

   open file (in) title ('/MADLIBS.DAT,type(text),recsize(100)');

   do forever;
      get file (in) edit (line) (L);
      if line = '' then leave;

      do until (replaced_all);
         replaced_all = true;
         if index(line, '<name>') > 0 then
            if seen_name then
               do until (index(line, '<name>') = 0);
                  call split(line, '<name>', left, right);
                  line = left || name || right;
                  replaced_all = false;
               end;
            else
               do;
                  put skip list ('Please type a name:');
                  get edit (name) (L);
                  seen_name = true; replaced_all = false;
               end;
         if index(line, '<he or she>') > 0 then
            if seen_pronoun then
               do until (index(line, '<he or she>') = 0);
                  call split(line, '<he or she>', left, right);
                  line = left || pronoun || right;
                  replaced_all = false;
               end;
            else
               do;
                   put skip list ('Please type a pronoun (he or she):');
                   get edit (pronoun) (L);
                   seen_pronoun = true; replaced_all = false;
               end;
         if index(line, '<noun>') > 0 then
            if seen_noun then
               do until (index(line, '<noun>') = 0);
                  call split(line, '<noun>', left, right);
                  line = left || noun || right;
                  replaced_all = false;
               end;
            else
               do;
                  put skip list ('Please type a noun:');
                  get edit (noun) (L);
                  seen_noun = true; replaced_all = false;
               end;
         end;
      put skip list (line);
   end;

split: procedure (line, text, Left, Right);
   declare (line, text, left, right) character (*) varying;
   declare i fixed binary;

   i = index(line, text);
   left  = substr(line, 1, i-1);
   right = substr(line, i+length(text), length(line) - (i + length(text)) + 1 );
end split;

end Mad_Libs;


function New-MadLibs
{
    [CmdletBinding(DefaultParameterSetName='None')]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory=$false)]
        [AllowEmptyString()]
        [string]
        $Name = "",

        [Parameter(Mandatory=$false, ParameterSetName='Male')]
        [switch]
        $Male,

        [Parameter(Mandatory=$false, ParameterSetName='Female')]
        [switch]
        $Female,

        [Parameter(Mandatory=$false)]
        [AllowEmptyString()]
        [string]
        $Item = ""
    )

    if (-not $Name)
    {
        $Name = (Get-Culture).TextInfo.ToTitleCase((Read-Host -Prompt "`nEnter a name").ToLower())
    }
    else
    {
        $Name = (Get-Culture).TextInfo.ToTitleCase(($Name).ToLower())
    }

    if ($Male)
    {
        $pronoun = "He"
    }
    elseif ($Female)
    {
        $pronoun = "She"
    }
    else
    {
        $title   = "Gender"
        $message = "Select $Name's Gender"
        $_male   = New-Object System.Management.Automation.Host.ChoiceDescription "&Male", "Selects male gender."
        $_female = New-Object System.Management.Automation.Host.ChoiceDescription "&Female", "Selects female gender."
        $options = [System.Management.Automation.Host.ChoiceDescription[]]($_male, $_female)
        $result  = $host.UI.PromptForChoice($title, $message, $options, 0)

        switch ($result)
        {
            0 {$pronoun = "He"}
            1 {$pronoun = "She"}
        }
    }

    if (-not $Item)
    {
        $Item = Read-Host -Prompt "`nEnter an item"
    }

    "`n{0} went for a walk in the park. {1} found a {2}. {0} decided to take it home.`n" -f $Name, $pronoun, $Item
}


import std.stdio, std.array;

auto compress(in string original) pure nothrow {
    int[string] dict;
    foreach (immutable char c; char.min .. char.max + 1)
        dict[[c]] = c;

    string w;
    int[] result;
    foreach (immutable ch; original)
        if (w ~ ch in dict)
            w = w ~ ch;
        else {
            result ~= dict[w];
            dict[w ~ ch] = dict.length;
            w = [ch];
        }
    return w.empty ? result : (result ~ dict[w]);
}

auto decompress(in int[] compressed) pure nothrow {
    auto dict = new string[char.max - char.min + 1];
    foreach (immutable char c; char.min .. char.max + 1)
        dict[c] = [c];

    auto w = dict[compressed[0]];
    auto result = w;
    foreach (immutable k; compressed[1 .. $]) {
        auto entry = (k < dict.length) ? dict[k] : w ~ w[0];
        result ~= entry;
        dict ~= w ~ entry[0];
        w = entry;
    }
    return result;
}

void main() {
    auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress;
    writeln(comp, "\n", comp.decompress);
}


import Data.Bool
import Data.Complex (Complex((:+)), magnitude)

mandelbrot
  :: RealFloat a
  => Complex a -> Complex a
mandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50

main :: IO ()
main =
  mapM_
    putStrLn
    [ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y)))
      | x <- [-2,-1.9685 .. 0.5] ]
    | y <- [1,0.95 .. -1] ]


If OpenConsole()

  cadena$ = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
  k = FindString(cadena$, "<")

  PrintN("La historia: ")
  Print(cadena$ + Chr(10))
  While k
    reemplaza$ = Mid(cadena$, k, FindString(cadena$, ">") - k + 1)
    Print(Chr(10) + "What should replace " + reemplaza$ + " ")
    con$ = Input ()
    While k
      cadena$ = Left(cadena$, k-1) + con$ + Mid(cadena$, k + Len(reemplaza$))
      k = FindString(cadena$, reemplaza$, k)
    Wend
    k = FindString(cadena$, "<")
  Wend
  PrintN(Chr(10) + "La historia final: ")
  PrintN(cadena$)
  Input()
  CloseConsole()
EndIf
End


import re

# Optional Python 2.x compatibility
#try: input = raw_input
#except: pass

template = '''<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.'''

def madlibs(template):
    print('The story template is:\n' + template)
    fields = sorted(set( re.findall('<[^>]+>', template) ))
    values = input('\nInput a comma-separated list of words to replace the following items'
                   '\n  %s: ' % ','.join(fields)).split(',')
    story = template
    for f,v in zip(fields, values):
        story = story.replace(f, v)
    print('\nThe story becomes:\n\n' + story)

madlibs(template)


Module:   LZW
Synopsis: LZW implementation for Rosetta code

define method output(n :: <integer>)
  format-out("%d ", n);
end;

define method contains?(dict, var)
  let x = element(dict, var, default: #f);
  x ~= #f;
end;

define method byte->string(c)
  add("", as(<character>, c));
end;

define method compress(input :: <string>) => <vector>;
  let result = make(<vector>);
  let dict = make(<string-table>);
  for (x from 0 to 255)
    dict[byte->string(x)] := x;
  end;

  let next-code = 256;
  let cur-seq = "";
  for (c in input)
    let wc = add(cur-seq, c);
    if (contains?(dict, wc))
      cur-seq := wc;
    else
      result := add(result, dict[cur-seq]);
      dict[wc] := next-code;
      next-code := next-code + 1;
      cur-seq := add("", c);
    end
  end;
  unless (empty?(cur-seq))
    result := add(result, dict[cur-seq]);
  end;
  result
end;

format-out("%=\n", compress("TOBEORNOTTOBEORTOBEORNOT"))


class
  APPLICATION

create
  make

feature {NONE}

  make
    local
      test: LINKED_LIST [INTEGER]
    do
      create test.make
      test := compress ("TOBEORNOTTOBEORTOBEORNOT")
      across
        test as t
      loop
        io.put_string (t.item.out + " ")
      end
      io.new_line
      io.put_string (decompress (test))
    end

  decompress (compressed: LINKED_LIST [INTEGER]): STRING
      --Decompressed version of 'compressed'.
    local
      dictsize, i, k: INTEGER
      dictionary: HASH_TABLE [STRING, INTEGER]
      w, entry: STRING
      char: CHARACTER_8
    do
      dictsize := 256
      create dictionary.make (300)
      create entry.make_empty
      create Result.make_empty
      from
        i := 0
      until
        i > 256
      loop
        char := i.to_character_8
        dictionary.put (char.out, i)
        i := i + 1
      end
      w := compressed.first.to_character_8.out
      compressed.go_i_th (1)
      compressed.remove
      Result := w
      from
        k := 1
      until
        k > compressed.count
      loop
        if attached dictionary.at (compressed [k]) as ata then
          entry := ata
        elseif compressed [k] = dictsize then
          entry := w + w.at (1).out
        else
          io.put_string ("EXEPTION")
        end
        Result := Result + entry
        dictsize := dictsize + 1
        dictionary.put (w + entry.at (1).out, dictsize)
        w := entry
        k := k + 1
      end
    end

  compress (uncompressed: STRING): LINKED_LIST [INTEGER]
      -- Compressed version of 'uncompressed'.
    local
      dictsize: INTEGER
      dictionary: HASH_TABLE [INTEGER, STRING]
      i: INTEGER
      w, wc: STRING
      char: CHARACTER_8
    do
      dictsize := 256
      create dictionary.make (256)
      create w.make_empty
      from
        i := 0
      until
        i > 256
      loop
        char := i.to_character_8
        dictionary.put (i, char.out)
        i := i + 1
      end
      create Result.make
      from
        i := 1
      until
        i > uncompressed.count
      loop
        wc := w + uncompressed [i].out
        if dictionary.has (wc) then
          w := wc
        else
          Result.extend (dictionary.at (w))
          dictSize := dictSize + 1
          dictionary.put (dictSize, wc)
          w := "" + uncompressed [i].out
        end
        i := i + 1
      end
      if w.count > 0 then
        Result.extend (dictionary.at (w))
      end
    end

end


haxe -swf mandelbrot.swf -main Mandelbrot


#! /bin/sh
exec huginn -E "${0}" "${@}"
#! huginn

import Algorithms as algo;
import Mathematics as math;
import Terminal as term;

mandelbrot( x, y ) {
  c = math.Complex( x, y );
  z = math.Complex( 0., 0. );
  s = -1;
  for ( i : algo.range( 50 ) ) {
    z = z * z + c;
    if ( | z | > 2. ) {
      s = i;
      break;
    }
  }
  return ( s );
}

main( argv_ ) {
  imgSize = term_size( argv_ );
  yRad = 1.2;
  yScale = 2. * yRad / real( imgSize[0] );
  xScale = 3.3 / real( imgSize[1] );
  glyphTab = [ ".", ":", "-", "+", "+" ].resize( 12, "*" ).resize( 26, "%" ).resize( 50, "@" ).push( " " );
  for ( y : algo.range( imgSize[0] ) ) {
    line = "";
    for ( x : algo.range( imgSize[1] ) ) {
      line += glyphTab[ mandelbrot( xScale * real( x ) - 2.3, yScale * real( y ) - yRad ) ];
    }
    print( line + "\n" );
  }
  return ( 0 );
}

term_size( argv_ ) {
  lines = 25;
  columns = 80;
  if ( size( argv_ ) == 3 ) {
    lines = integer( argv_[1] );
    columns = integer( argv_[2] );
  } else {
    lines = term.lines();
    columns = term.columns();
    if ( ( lines % 2 ) == 0 ) {
      lines -= 1;
    }
  }
  lines -= 1;
  columns -= 1;
  return ( ( lines, columns ) );
}


(define (get-mad-libs file)
  (with-input-from-file file
    (lambda ()
      (for/fold ((text ""))
        ((line (in-lines)))
        (string-append text line "\n")))))

(define (replace-context mad-libs)
  (define matches
    (regexp-match* #rx"<[a-zA-Z0-9 ]*>" mad-libs))
  (map
   (lambda (context)
     (display (format "~a?" context))
     (cons context (read-line)))
   (remove-duplicates matches)))

(define (play-mad-libs)
  (display "Tell me a file to play Mad Libs: ")
  (define text (get-mad-libs (read-line)))
  (define matches (replace-context text))

  (display
   (for/fold ((mad-story text))
     ((change (in-list matches)))
     (string-replace mad-story (car change) (cdr change)))))

(play-mad-libs)


t: {<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.}
view layout [a: area wrap t  btn "Done" [x: a/text unview]]
parse x [any [to "<" copy b thru ">" (append w: [] b)] to end]
foreach i unique w [replace/all x i ask join i ": "]  alert x


defmodule LZW do
  @encode_map  Enum.into(0..255, Map.new, &{[&1],&1})
  @decode_map  Enum.into(0..255, Map.new, &{&1,[&1]})

  def encode(str), do: encode(to_char_list(str), @encode_map, 256, [])

  defp encode([h], d, _, out), do: Enum.reverse([d[[h]] | out])
  defp encode([h|t], d, free, out) do
    val = d[[h]]
    find_match(t, [h], val, d, free, out)
  end

  defp find_match([h|t], l, lastval, d, free, out) do
    case Map.fetch(d, [h|l]) do
      {:ok, val} -> find_match(t, [h|l], val, d, free, out)
      :error     -> d1 = Map.put(d, [h|l], free)
                    encode([h|t], d1, free+1, [lastval | out])
    end
  end
  defp find_match([], _, lastval, _, _, out), do: Enum.reverse([lastval | out])

  def decode([h|t]) do
    val = @decode_map[h]
    decode(t, val, 256, @decode_map, val)
  end

  defp decode([], _, _, _, l), do: Enum.reverse(l) |> to_string
  defp decode([h|t], old, free, d, l) do
    val = if h == free, do: old ++ [List.first(old)], else: d[h]
    add = [List.last(val) | old]
    d1  = Map.put(d, free, add)
    decode(t, val, free+1, d1, val++l)
  end
end

str = "TOBEORNOTTOBEORTOBEORNOT"
IO.inspect enc = LZW.encode(str)
IO.inspect dec = LZW.decode(enc)
IO.inspect str == dec


-module(lzw).

-export([test/0, encode/1, decode/1]).

-import(lists, [reverse/1, reverse/2]).

test() ->
    Str = "TOBEORNOTTOBEORTOBEORNOT",
    [84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263] =
  encode(Str),
    Str = decode(encode(Str)),
    ok.

encode(Str) ->
    D = init(dict:new()),
    encode(Str, D, 256, []).

encode([H], D, _, Out) ->
    Val = dict:fetch([H], D),
    reverse([Val|Out]);
encode([H|T], D, Free, Out) ->
    Val = dict:fetch([H], D),
    find_match(T, [H], Val, D, Free, Out).

find_match([H|T], L, LastVal, D, Free, Out) ->
    case dict:find([H|L], D) of
  {ok, Val} ->
      find_match(T, [H|L], Val, D, Free, Out);
  error ->
      D1 = dict:store([H|L], Free, D),
      encode([H|T], D1, Free+1, [LastVal|Out])
    end;
find_match([], _, LastVal, _, _, Out) ->
    reverse([LastVal|Out]).

decode([H|T]) ->
    D   = init1(dict:new()),
    Val = dict:fetch(H, D),
    decode(T, Val, 256, D, Val).

decode([], _, _, _, L) ->
    reverse(L);
decode([H|T], Old, Free, D, L) ->
    Val = dict:fetch(H, D),
    Add = [lists:last(Val)|Old],
    D1  = dict:store(Free, Add, D),
    decode(T, Val, Free+1, D1, Val ++ L).

init(D) -> init(255, D).

init(0, D) ->  D;
init(N, D) ->  D1 = dict:store([N],N,D),  init(N-1, D1).

init1(D) -> init1(255, D).

init1(0, D) ->  D;
init1(N, D) ->  D1 = dict:store(N,[N],D),  init1(N-1, D1).


link graphics

procedure main()
    width := 750
    height := 600
    limit := 100
    WOpen("size="||width||","||height)
    every x:=1 to width & y:=1 to height do
    {
        z:=complex(0,0)
        c:=complex(2.5*x/width-2.0,(2.0*y/height-1.0))
        j:=0
        while j<limit & cAbs(z)<2.0 do
        {
           z := cAdd(cMul(z,z),c)
           j+:= 1
        }
        Fg(mColor(j,limit))
        DrawPoint(x,y)
    }
    WriteImage("./mandelbrot.gif")
    WDone()
end

procedure mColor(x,limit)
   max_color := 2^16-1
   color := integer(max_color*(real(x)/limit))

   return(if x=limit
          then "black"
          else color||","||color||",0")
end

record complex(r,i)

procedure cAdd(x,y)
    return complex(x.r+y.r,x.i+y.i)
end

procedure cMul(x,y)
    return complex(x.r*y.r-x.i*y.i,x.r*y.i+x.i*y.r)
end

procedure cAbs(x)
    return sqrt(x.r*x.r+x.i*x.i)
end


phrase: ask "Enter phrase, leave line empty to terminate:^/"
while [not empty? line: input] [append phrase rejoin ["^/" line]]
words: parse phrase [collect [any [to "<" copy b thru ">" keep (b)]]]
foreach w unique words [replace/all phrase w ask rejoin [w ": "]]
print phrase


/*REXX program prompts the user for a template substitutions within a story  (MAD LIBS).*/
parse arg iFID .                                 /*allow user to specify the input file.*/
if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified?  Then use the default.*/
@.=                                              /*assign defaults to some variables.   */
$=;          do recs=1  while  lines(iFID)\==0   /*read the input file until it's done. */
             @.recs=linein(iFID);  $=$  @.recs   /*read a record;  and append it to  @  */
             if @.recs=''  then leave            /*Read a blank line?   Then we're done.*/
             end  /*recs*/
recs=recs-1                                      /*adjust for a E─O─F  or  a blank line.*/
pm= 'please enter a word or phrase to replace: ' /*this is part of the  Prompt Message. */
!.=0                                             /*placeholder for phrases in  MAD LIBS.*/
#=0;    do  forever                              /*look for templates within the text.  */
        parse var  $   '<'   ?   ">"   $         /*scan for   <ααα>   stuff in the text.*/
        if ?=''   then leave                     /*No   ααα ?   Then we're all finished.*/
        if !.?    then iterate                   /*Already asked?   Then keep scanning. */
        !.?=1                                    /*mark this   ααα   as being  "found". */
               do  until  ans\=''                /*prompt user for a replacement.       */
               say '───────────'   pm    ?       /*prompt the user with a prompt message*/
               parse pull ans                    /*PULL  obtains the text from console. */
               end   /*forever*/
        #=#+1                                    /*bump the template counter.           */
        old.# = '<'?">";           new.# = ans   /*assign the "old" name and "new" name.*/
        end   /*forever*/
say                                              /*display a blank line for a separator.*/
say;  say copies('═', 79)                        /*display a blank line  and  a fence.  */

        do m=1  for recs                         /*display the text,  line for line.    */
                do n=1  for #                    /*perform substitutions in the text.   */
                @.m=changestr(old.n, @.m, new.n) /*maybe replace text in  @.m  haystack.*/
                end   /*n*/
        say @.m                                  /*display the (new) substituted text.  */
        end   /*m*/

say copies('═', 79)                              /*display a  final (output) fence.     */
say                                              /*stick a fork in it,  we're all done. */


temp="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = substr(temp,"<")
while k
      replace   = substr(temp,k,substr(temp,">")-k + 1)
      see "replace:" + replace + " with: "
      give with
      while k
            temp  = left(temp,k-1) + with + substr(temp,k + len(replace))
            k = substr(temp,replace)
      end
      k = substr(temp,"<")
end
see temp + nl


256 value next-symbol

\ current string fragment

create w 256 allot     \ counted string

: w=c ( c -- )       w 1+ c!        1 w c! ;
: w+c ( c -- )  w count + c!  w [email protected] 1+ w c! ;

\ Compression

\ dictionary of strings to symbols
0 value dict

: init-dict  table to dict  256 to next-symbol  dict set-current ;

: free-dict                           forth-wordlist set-current ;

: in-dict? ( key len -- ? )   \ can assume len > 1
  dict search-wordlist dup if nip then ;

: lookup-dict ( key len -- symbol )
  dup 1 = if drop [email protected] exit then
  dict search-wordlist if >body @ else abort" bad-dict!" then ;

: put-dict ( data key len -- )
  nextname create , ;

\ output buffer of symbols
\  in real life, these symbols would be packed into octets
variable out-size
create out 256 cells allot

: output ( symbol -- )
  dup out out-size @ cells + !  1 out-size +!
  dup 256 < if emit space else . then ;

: compress ( addr len -- )
  init-dict  0 out-size !
  over [email protected] w=c  1 /string
  bounds do
    i [email protected] w+c
    w count in-dict? 0= if
      w count 1- lookup-dict output
      next-symbol dup w count put-dict
      1+ to next-symbol
      i [email protected] w=c
    then
  loop
  w count lookup-dict output
  free-dict ;

\ Decompression

\ array of symbols to strings (in real code this would need to be growable)
\  next-symbol is reused for the size of this table
create symtab 256 cells allot
0 value start

: init-symtab  256 to next-symbol  here to start ;

: free-symtab  start here - allot ;

: get-symbol ( symbol -- addr len )
  dup 256 < if pad c! pad 1 exit then
  256 - cells symtab + @ count ;

: add-symbol ( addr len -- )
  here symtab next-symbol 256 - cells + !
  s,
  next-symbol 1+ to next-symbol ;

create entry 256 allot

: decompress ( addr len -- )
  init-symtab
  over @ dup emit w=c
  cells bounds cell+ do
    i @ next-symbol < if
      i @ get-symbol entry place
    else i @ next-symbol = if
      w 1+ [email protected] w count + c!  w count 1+ entry place
    else
      abort" bad symbol!"
    then then
    entry count type  \ output
    entry 1+ [email protected] w+c
    w count add-symbol
    entry count w place
  1 cells +loop
  free-symtab ;

\ Testing

s" TOBEORNOTTOBEORTOBEORNOT" compress cr
\ T O B E O R N O T 256 258 260 265 259 261 263

out out-size @ decompress cr
\ TOBEORNOTTOBEORTOBEORNOT


!
! lzw_shared_parameters.f90
!
! LZW Common Variables Used by Coder and Decoder
!
! Author: Pedro Garcia Freitas <[email protected]>
! May, 2011
!
! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/
!
      MODULE LZW_SHARED_PARAMETERS
      IMPLICIT NONE
!
! PARAMETER definitions
!
      INTEGER , PARAMETER  ::  COMPILER_INTEGER_SIZE = 32 , BITS = 12 , FILEIN = 66 ,     &
                             & FILEOUT = 99 , MAX_VALUE = (2**BITS) - 1 ,                 &
                             & MAX_CODE = MAX_VALUE - 1 , MAX_DICTIONARY_SIZE = 5021 ,    &
                             & SYMBOL_SIZE = 8 , MISSING_BITS = COMPILER_INTEGER_SIZE -   &
                             & SYMBOL_SIZE
!
! Local variables
!
      INTEGER , DIMENSION(0:MAX_DICTIONARY_SIZE)  ::  concatenatedsymbols
      INTEGER , DIMENSION(0:MAX_DICTIONARY_SIZE)  ::  prefixcodes
      INTEGER  ::  the_status = 0

! change this if compiler dont use 32 bits for integer

      END MODULE LZW_SHARED_PARAMETERS
!
! codecIO.f90
!
! bit IO routines for coder and encoder.
!
! Author: Pedro Garcia Freitas <[email protected]>
! May, 2011
!
! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/
!
      MODULE CODECIO
      USE LZW_SHARED_PARAMETERS
      IMPLICIT NONE
!
      CONTAINS
      SUBROUTINE SETOUTPUTCODE(Code)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  Code
      INTENT (IN) Code
!
! Local variables
!
      INTEGER  ::  buffer
      INTEGER  ::  outputbitbuffer = 0
      INTEGER  ::  outputbitcount = 0
      INTEGER  ::  shift
      INTEGER  ::  shiftedsymbol
!
      shift = COMPILER_INTEGER_SIZE - BITS - outputbitcount
      shiftedsymbol = ISHFT(Code , shift)
      outputbitbuffer = IOR(outputbitbuffer , shiftedsymbol)
      outputbitcount = outputbitcount + BITS

      DO WHILE(outputbitcount >= SYMBOL_SIZE)
!         IF( outputbitcount<SYMBOL_SIZE )EXIT
         buffer = ISHFT(outputbitbuffer , -MISSING_BITS)
         CALL SETRAWBYTE(buffer)
         outputbitbuffer = ISHFT(outputbitbuffer , SYMBOL_SIZE)
         outputbitcount = outputbitcount - SYMBOL_SIZE
      END DO
      RETURN
      END SUBROUTINE SETOUTPUTCODE

      SUBROUTINE SETRAWBYTE(Symbol)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  Symbol
      INTENT (IN) Symbol
!

      CALL FPUTC(FILEOUT , ACHAR(Symbol))
      END SUBROUTINE SETRAWBYTE

      FUNCTION GETRAWBYTE()
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  GETRAWBYTE
!
! Local variables
!
      CHARACTER  ::  bufferedbyte
!
      CALL FGETC(FILEIN , bufferedbyte , THE_status)
      GETRAWBYTE = IACHAR(bufferedbyte)
      END FUNCTION GETRAWBYTE

      FUNCTION GETINPUTCODE()
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  GETINPUTCODE
!
! Local variables
!
      INTEGER  ::  inputbitbuffer = 0
      INTEGER  ::  inputbitcounter = 0
      INTEGER  ::  integerinputbuff
      INTEGER  ::  returnn
      INTEGER  ::  shiftedbit
!
      DO WHILE( inputbitcounter <= MISSING_BITS )
!         IF( inputbitcounter>MISSING_BITS )EXIT
         integerinputbuff = GETRAWBYTE()
         shiftedbit = ISHFT(integerinputbuff , MISSING_BITS - inputbitcounter)
         inputbitbuffer = IOR(inputbitbuffer , shiftedbit)
         inputbitcounter = inputbitcounter + SYMBOL_SIZE
      END DO

      returnn = ISHFT(inputbitbuffer , BITS - COMPILER_INTEGER_SIZE)
      inputbitbuffer = ISHFT(inputbitbuffer , BITS)
      inputbitcounter = inputbitcounter - BITS
      GETINPUTCODE = returnn
      RETURN
      END FUNCTION GETINPUTCODE
end module codecIO
! lzw_encoder.f90
!
! LZW Coder (Compressor)
!
! Author: Pedro Garcia Freitas <[email protected]>
! May, 2011
!
! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/
!
      MODULE LZW_ENCODER
      USE LZW_SHARED_PARAMETERS
      USE CODECIO
      IMPLICIT NONE
!
! PARAMETER definitions
!
      INTEGER , PARAMETER  ::  HASH_SHIFT = BITS - SYMBOL_SIZE
!
! Local variables
!
      INTEGER , DIMENSION(0:MAX_DICTIONARY_SIZE)  ::  symbolvalues
      CONTAINS
      SUBROUTINE COMPRESS()
      IMPLICIT NONE
!
! Local variables
!
      INTEGER  ::  codedsymbol
      INTEGER  ::  my_index
      INTEGER  ::  nextsymbol
      INTEGER  ::  symbol
      CHARACTER  ::  bufferedbyte
!
      nextsymbol = COMPILER_INTEGER_SIZE*SYMBOL_SIZE
      SYMbolvalues(:) = -1

!      codedsymbol = GETRAWBYTE()
      CALL FGETC(FILEIN , bufferedbyte , THE_status)
      codedsymbol = IACHAR(bufferedbyte)
!Can be hand optimized - optimization
      DO WHILE(THE_status == 0)
!         symbol = GETRAWBYTE()     ! Manual inline of function
          CALL FGETC(FILEIN , bufferedbyte , THE_status)
          symbol = IACHAR(bufferedbyte)
         IF( THE_status/=0 )CYCLE

         my_index = GETPOSITIONONDICTIONARY(codedsymbol , symbol)
         IF( SYMbolvalues(my_index)/= - 1 )THEN
            codedsymbol = SYMbolvalues(my_index)
         ELSE
            IF( nextsymbol<=MAX_CODE )THEN
               SYMbolvalues(my_index) = nextsymbol
               nextsymbol = nextsymbol + 1
               PREfixcodes(my_index) = codedsymbol
               CONcatenatedsymbols(my_index) = symbol
            END IF
            CALL SETOUTPUTCODE(codedsymbol)
            codedsymbol = symbol
         END IF
      END DO
      CALL SETOUTPUTCODE(codedsymbol)
      CALL SETOUTPUTCODE(MAX_VALUE)
      CALL SETOUTPUTCODE(0)
      END SUBROUTINE COMPRESS

function getPositionOnDictionary(hashPrefix, hashSymbol)
      integer, intent(in) :: hashPrefix
      integer, intent(in) :: hashSymbol
      integer             :: getPositionOnDictionary
      integer             :: index
      integer             :: offset

      index = ishft(hashSymbol, HASH_SHIFT)
      index = ieor(index, hashPrefix)
      if (index == 0) then
        offset = 1
      else
        offset = MAX_DICTIONARY_SIZE - index
      endif

      do
        if (symbolValues(index) == -1) then
          getPositionOnDictionary = index
          exit
        endif

        if (prefixCodes(index) == hashPrefix .and. &
            & concatenatedSymbols(index) == hashSymbol) then
          getPositionOnDictionary = index
          exit
        endif

        index = index - offset
        if (index < 0) then
          index = index + MAX_DICTIONARY_SIZE
        endif
      end do
      return
    end function

end module LZW_Encoder
! lzw_decoder.f90
!
! LZW Decoder (Expanssor)
!
! Author: Pedro Garcia Freitas <[email protected]>
! May, 2011
!
! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/
!
      MODULE LZW_DECODER
      USE LZW_SHARED_PARAMETERS
      USE CODECIO
      IMPLICIT NONE
!
! Derived Type definitions
!
      TYPE :: DECODE_BUFFER_STACK
         INTEGER , DIMENSION(0:MAX_DICTIONARY_SIZE)  ::  DECODERSTACK
         INTEGER  ::  TOP
      END TYPE DECODE_BUFFER_STACK
!
! Local variables
!
      TYPE(DECODE_BUFFER_STACK)  ::  stack
      CONTAINS
!
!       Can be hand optimized - optimization
      SUBROUTINE DECOMPRESS()
      IMPLICIT NONE
!
! Local variables
!
      INTEGER  ::  newsymbol
      INTEGER  ::  nextsymbol
      INTEGER  ::  oldsymbol
      INTEGER  ::  popedsymbol
      INTEGER  ::  symbol
!
      nextsymbol = COMPILER_INTEGER_SIZE*SYMBOL_SIZE
      oldsymbol = GETINPUTCODE()
      symbol = oldsymbol

      CALL SETRAWBYTE(oldsymbol)

      DO
         newsymbol = GETINPUTCODE()

         IF( newsymbol==MAX_VALUE )RETURN

         IF( newsymbol>=nextsymbol )THEN
            STAck%DECODERSTACK(0) = symbol
            CALL DECODESYMBOL(STAck%DECODERSTACK(1:) , oldsymbol)
         ELSE
            CALL DECODESYMBOL(STAck%DECODERSTACK(:) , newsymbol)
         END IF

         symbol = STAck%DECODERSTACK(STAck%TOP)

         DO WHILE ( STAck%TOP>=0 )
            popedsymbol = STAck%DECODERSTACK(STAck%TOP)
            CALL SETRAWBYTE(popedsymbol)
            STAck%TOP = STAck%TOP - 1
         END DO

         IF( nextsymbol<=MAX_CODE )THEN
            PREfixcodes(nextsymbol) = oldsymbol
            CONcatenatedsymbols(nextsymbol) = symbol
            nextsymbol = nextsymbol + 1
         END IF
         oldsymbol = newsymbol
      END DO
      RETURN
      END SUBROUTINE DECOMPRESS

      SUBROUTINE DECODESYMBOL(Buffer , Code)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  Code
      INTEGER , DIMENSION(:)  ::  Buffer
      INTENT (IN) Code
      INTENT (INOUT) Buffer
!
! Local variables
!
      INTEGER  ::  i
      INTEGER  ::  j
      INTEGER  ::  symbol
!
      j = 0
      symbol = Code
      STAck%TOP = 0
      DO WHILE ( symbol>=COMPILER_INTEGER_SIZE*SYMBOL_SIZE )
 !        IF( symbol<COMPILER_INTEGER_SIZE*SYMBOL_SIZE )EXIT

         IF( j>=MAX_CODE )THEN
            PRINT * , "Decoding error"
            STOP
         END IF

         i = STAck%TOP + 1
         Buffer(i) = CONcatenatedsymbols(symbol)
         symbol = PREfixcodes(symbol)
         STAck%TOP = STAck%TOP + 1
         j = j + 1
      END DO
      i = j + 1
      Buffer(i) = symbol
      END SUBROUTINE DECODESYMBOL
end module LZW_Decoder
! lzw.f90
!
! LZW Coder and Decoder
!
! Author: Pedro Garcia Freitas <[email protected]>
! May, 2011
!
! License: Creative Commons http://creativecommons.org/licenses/by-nc-nd/3.0/
!

      MODULE LZW
      USE LZW_SHARED_PARAMETERS
      USE LZW_ENCODER
      USE LZW_DECODER
      IMPLICIT NONE
      CONTAINS
      SUBROUTINE INIT(Input , Output , Operation , Filename)
      IMPLICIT NONE
!
! Dummy arguments
!
      CHARACTER(100)  ::  Filename
      CHARACTER(100)  ::  Input
      CHARACTER(1)  ::  Operation
      CHARACTER(100)  ::  Output
      INTENT (IN) Filename , Input , Operation , Output
!
      IF( Operation/='d' .AND. Operation/='e' )THEN
         PRINT * , "Usage: " // TRIM(Filename) // " <operation> input output"
         PRINT * , "Possible operations: "
         PRINT * , "    e -> encode (compress)"
         PRINT * , "    d -> decode (inflate)"
         STOP
      END IF

      OPEN(UNIT = FILEIN , FILE = Input , ACTION = "read" , STATUS = "old" ,              &
          &ACCESS = 'stream' , FORM = "formatted")
      OPEN(UNIT = FILEOUT , FILE = Output , ACTION = "write" , STATUS = "replace" ,       &
         & ACCESS = 'stream' , FORM = "formatted")

      IF( Operation=='d' )THEN
         PRINT * , "Decoding..."
         CALL DECOMPRESS()
      ELSE
         PRINT * , "Encoding..."
         CALL COMPRESS()
      END IF

      CLOSE(UNIT = FILEIN)
      CLOSE(UNIT = FILEOUT)
      END SUBROUTINE INIT
end module LZW
!
      PROGRAM MAIN
      USE LZW
      IMPLICIT NONE
!
! Local variables
!
      CHARACTER(100)  ::  filename
      REAL  ::  finish
      CHARACTER(100)  ::  input
      CHARACTER(1)  ::  operation
      CHARACTER(100)  ::  output
      REAL  ::  start
!
      CALL GETARG(0 , filename)
      CALL GETARG(1 , operation)
      CALL GETARG(2 , input)
      CALL GETARG(3 , output)
      CALL CPU_TIME(start)
      CALL INIT(input , output , operation , filename)
      CALL CPU_TIME(finish)
      PRINT '("Time = ",f6.3," seconds.")' , finish - start
      END PROGRAM MAIN


PRO Mandelbrot,xRange,yRange,xPixels,yPixels,iterations

xPixelstartVec = Lindgen( xPixels) * Float(xRange[1]-xRange[0]) / $
                 xPixels + xRange[0]
yPixelstartVec = Lindgen( yPixels) * Float(YRANGE[1]-yrange[0])$
                 / yPixels + yRange[0]

constArr = Complex( Rebin( xPixelstartVec, xPixels, yPixels),$
                     Rebin( Transpose(yPixelstartVec), xPixels, yPixels))

valArr = ComplexArr( xPixels, yPixels)

res = IntArr( xPixels, yPixels)

oriIndex = Lindgen( Long(xPixels) * yPixels)

FOR i = 0, iterations-1 DO BEGIN ; only one loop needed

    ; calculation for whole array at once
    valArr = valArr^2 - constArr

    whereIn = Where( Abs( valArr) LE 4.0d, COMPLEMENT=whereOut)

    IF whereIn[0] EQ -1 THEN BREAK

    valArr = valArr[ whereIn]

    constArr = constArr[ whereIn]

    IF whereOut[0] NE -1 THEN BEGIN

        res[ oriIndex[ whereOut]] = i+1

        oriIndex = oriIndex[ whereIn]
    ENDIF
ENDFOR

tv,res ; open a window and show the result

END

Mandelbrot,[-1.,2.3],[-1.3,1.3],640,512,200

END


puts "Enter a story, terminated by an empty line:"
story = ""
until (line = gets).chomp.empty?
  story << line
end

story.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var|
  print "Enter a value for '#{var}': "
  story.gsub!(/<#{var}>/, gets.chomp)
end

puts
puts story


temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(temp$,"<")
while k
    replace$   = mid$(temp$,k,instr(temp$,">")-k + 1)
    print "Replace:";replace$;" with:"; :input with$
    while k
        temp$  = left$(temp$,k-1) + with$ + mid$(temp$,k + len(replace$))
        k      = instr(temp$,replace$,k)
    wend
k = instr(temp$,"<")
wend
print temp$
wait


extern crate regex;

use regex::Regex;
use std::collections::HashMap;
use std::io;

fn main() {
    let mut input_line = String::new();
    let mut template = String::new();

    println!("Please enter a multi-line story template with <parts> to replace, terminated by a blank line.\n");
    loop {
        io::stdin()
            .read_line(&mut input_line)
            .expect("The read line failed.");
        if input_line.trim().is_empty() {
            break;
        }
        template.push_str(&input_line);
        input_line.clear();
    }

    let re = Regex::new(r"<[^>]+>").unwrap();
    let mut parts: HashMap<_, _> = re
        .captures_iter(&template)
        .map(|x| (x.get(0).unwrap().as_str().to_string(), "".to_string()))
        .collect();
    if parts.is_empty() {
        println!("No <parts> to replace.\n");
    } else {
        for (k, v) in parts.iter_mut() {
            println!("Please provide a replacement for {}: ", k);
            io::stdin()
                .read_line(&mut input_line)
                .expect("The read line failed.");
            *v = input_line.trim().to_string();
            println!();
            template = template.replace(k, v);
            input_line.clear();
        }
    }
    println!("Resulting story:\n\n{}", template);
}


object MadLibs extends App{
  val input = "<name> went for a walk in the park. <he or she>\nfound a <noun>. <name> decided to take it home."
  println(input)
  println

  val todo = "(<[^>]+>)".r
  val replacements = todo.findAllIn(input).toSet.map{found: String =>
    found -> readLine(s"Enter a $found ")
  }.toMap

  val output = todo.replaceAllIn(input, found => replacements(found.matched))
  println
  println(output)
}


' version 22-02-2019
' compile with: fbc -s console

Type dict
    prefix As Integer
    B      As String
End Type

Sub init(dictionary() As dict, ByRef last As ULong)

    For i As ULong  = 0 To 255
        dictionary(i).prefix = -1
        dictionary(i).B = Chr(i)
    Next
    last = 255

End Sub

Function encode_LZW(dictionary() As dict, last_entry As ULong, input_str As String) As String

    If Len(input_str) < 2 Then
        Print "input string is to short"
        Return ""
    End If

    Dim As String word, output_str, char
    Dim As ULong i = 1, index, j, len_input = Len(input_str)

    Do
        If i > len_input Then
            output_str = output_str + " " + Str(index)
            Return output_str ' no more chars to process. we are done
        End If
        char = Mid(Input_str, i, 1)
        i += 1
        For j = 0 To last_entry
            If dictionary(j).B = word + char Then
                word += char
                index = j
                Continue Do
            End If
        Next
        output_str = output_str + " " + Str(index)
        last_entry = last_entry +1
        dictionary(last_entry).B = word + char
        dictionary(last_entry).prefix = index
        word = char : index = Asc(char)
    Loop

End Function

Function decode_LZW(dictionary() As dict, last_entry As ULong, input_str As String) As String

    Dim As String temp, word, output_str
    Dim As ULong i, i1 = 1, j, index
    input_str = Trim(input_str)
    Dim As ULong len_input = Len(input_str)
    input_str = input_str + " "

    i = InStr(i1, input_str, " ")
    index = Val(Mid(Input_str, i1, i - i1))
    word = dictionary(index).B
    output_str = word
    i1 = i +1
    Do
        i = InStr(i1, input_str, " ")
        If i >= len_input Then
            index = Val(Mid(input_str, i1))
            output_str = output_str + dictionary(index).B
            Return output_str
        End If
        index = Val(Mid(Input_str, i1, i - i1))
        i1 = i +1
        If index <= last_entry Then
            temp = dictionary(index).B
        Else
            temp = word + Left(word, 1)
        End If
        output_str = output_str + temp
        last_entry = last_entry +1
        dictionary(last_entry).B = word + Left(temp, 1)
        word = temp
    Loop

End Function

' ------=< MAIN >=------

Dim As ULong last_entry, max_bit = 9
Dim As ULong dict_max = 1 Shl max_bit -1
Dim As String output_str, input_str = "TOBEORNOTTOBEORTOBEORNOT"
Dim As dict dictionary()

Print "  input str: ";input_str

ReDim dictionary(dict_max +1)
init(dictionary(), last_entry)
output_str = encode_LZW(dictionary(), last_entry, input_str)
Print "encoded str: ";output_str

ReDim dictionary(dict_max +1)
init(dictionary(), last_entry)
output_str = decode_LZW(dictionary(), last_entry, output_str)
Print "decoded str: "; output_str

' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End