MODULE HtmlTable {
	tag$=LAMBDA$ (a$)-> {
		=LAMBDA$ a$ -> {
			IF ISNUM THEN w$=STR$(NUMBER,0) ELSE w$=LETTER$
			READ ? part$
			="<"+a$+IF$(LEN(part$)>0->" "+part$,"")+">"+w$+"</"+a$+">"+CHR$(13)+CHR$(10)
		}
	}
	INVENTORY Fun
	STACK NEW {
		DATA "html", "head", "body", "table", "tr", "th", "td"
		WHILE NOT EMPTY
			OVER ' duplicate top of stack
			APPEND Fun, LETTER$:=tag$(LETTER$)
		END WHILE
	}
	DEF body0$="",body$=""
	STACK NEW {
		DATA "", "X", "Y", "Z"
		FOR i=1 TO 4
			body0$+=Fun$("th")(LETTER$)
			z$=""
			FOR j=1 TO 3 : z$+=Fun$("td")(RANDOM(0, 9999), {align="right"}) : NEXT j
			body$+=Fun$("tr")(Fun$("th")(i)+z$)
		NEXT i
	}
	table$=fun$("table")(fun$("tr")(body0$)+body$,"border=1 cellpadding=10 cellspacing=0")
	DOCUMENT final$="<!DOCTYPE html>"+CHR$(13)+CHR$(10)
	final$=fun$("html")(fun$("head")("")+fun$("body")(table$), {lang="en"})
	file$="c:\doc.html"
	REPORT final$
	CLIPBOARD final$
	SAVE.DOC final$, file$
	WIN file$  ' execute, no wait
}
HtmlTable


{def countSubstring
 {def countSubstring.r
  {lambda {:n :i :acc :s}
   {if {>= :i :n}
    then :acc
    else {countSubstring.r :n
                           {+ :i 1}
                           {if {W.equal? {W.get :i :s} ⫖}
                            then {+ :acc 1}
                            else :acc}
                           :s} }}}
 {lambda {:w :s}
  {countSubstring.r {W.length :s} 0 0
                    {S.replace \s by ⫕ in
                    {S.replace :w by ⫖ in :s}}}}}
-> countSubstring

{countSubstring th the three truths}
-> 3
{countSubstring ab ababa}
-> 2
{countSubstring aba ababa}
-> 1


writeln len indices q(th), q(the three truths)
writeln len indices q(abab), q(ababababab)


define countSubstring(str::string, substr::string)::integer => {
	local(i = 1, foundpos = -1, found = 0)
	while(#i < #str->size && #foundpos != 0) => {
		protect => {
			handle_error => { #foundpos = 0 }
			#foundpos = #str->find(#substr, -offset=#i)
		}
		if(#foundpos > 0) => {
			#found += 1
			#i = #foundpos + #substr->size
		else
			#i++
		}
	}
	return #found
}
define countSubstring_bothways(str::string, substr::string)::integer => {
	local(found = countSubstring(#str,#substr))
	#str->reverse
	local(found2 = countSubstring(#str,#substr))
	#found > #found2 ? return #found | return #found2
}
countSubstring_bothways('the three truths','th')
//3
countSubstring_bothways('ababababab','abab')
//2


function changes(amount::Int, coins::Array{Int})::Int128
    ways = zeros(Int128, amount + 1)
    ways[1] = 1
    for coin in coins, j in coin+1:amount+1
        ways[j] += ways[j - coin]
    end
    return ways[amount + 1]
end

@show changes(100, [1, 5, 10, 25])
@show changes(100000, [1, 5, 10, 25, 50, 100])


// version 1.0.6

fun countCoins(c: IntArray, m: Int, n: Int): Long {
    val table = LongArray(n + 1)
    table[0] = 1
    for (i in 0 until m)
        for (j in c[i]..n) table[j] += table[j - c[i]]
    return table[n]
}

fun main(args: Array<String>) {
    val c = intArrayOf(1, 5, 10, 25, 50, 100)
    println(countCoins(c, 4, 100))
    println(countCoins(c, 6, 1000 * 100))
}


function htmltable(fid,table,Label)
   fprintf(fid,'
\n
\n');
   if nargin<3,
       fprintf(fid,'
	X	Y	Z
\n
\n
\n');
   else
       fprintf(fid,'
	');
       fprintf(fid,'%s	',Label{:});
       fprintf(fid,'
\n
\n
\n');
   end;
   fprintf(fid,'
%2i	%5i	%5i	%5i
\n', [1:size(table,1);table']);
   fprintf(fid,'
\n
\n');
end


print countSubstring( "the three truths", "th")
print countSubstring( "ababababab", "abab")
end

function countSubstring( a$, s$)
    c =0
    la =len( a$)
    ls =len( s$)
    for i =1 to la -ls
        if mid$( a$, i, ls) =s$ then c =c +1: i =i +ls -1
    next i
    countSubstring =c
end function


:- object(counting).

    :- public(count/3).

    count(String, SubString, Count) :-
        count(String, SubString, 0, Count).

    count(String, SubString, Count0, Count) :-
        (   sub_atom(String, Before, Length, After, SubString) ->
            Count1 is Count0 + 1,
            Start is Before + Length,
            sub_atom(String, Start, After, 0, Rest),
            count(Rest, SubString, Count1, Count)
        ;   Count is Count0
        ).

:- end_object.


function countSubstring(s1, s2)
    return select(2, s1:gsub(s2, ""))
end

print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))


define cointcoins(
	target::integer,
	operands::array
) => {

	local(
		targetlength	= #target + 1,
		operandlength	= #operands -> size,
		output			= staticarray_join(#targetlength,0),
		outerloopcount
	)

	#output -> get(1) = 1

	loop(#operandlength) => {
		#outerloopcount = loop_count
		loop(#targetlength) => {

			if(loop_count >= #operands -> get(#outerloopcount) and loop_count - #operands -> get(#outerloopcount) > 0) => {
				#output -> get(loop_count) += #output -> get(loop_count - #operands -> get(#outerloopcount))
			}
		}
	}

	return #output -> get(#targetlength)
}

cointcoins(100, array(1,5,10,25,))
'<br />'
cointcoins(100000, array(1, 5, 10, 25, 50, 100))


function countSums (amount, values)
    local t = {}
    for i = 1, amount do t[i] = 0 end
    t[0] = 1
    for k, val in pairs(values) do
        for i = val, amount do t[i] = t[i] + t[i - val] end
    end
    return t[amount]
end

print(countSums(100, {1, 5, 10, 25}))
print(countSums(100000, {1, 5, 10, 25, 50, 100}))


MODULE testCGI;

FROM  InOut       IMPORT  WriteCard, WriteLn, WriteString, WriteBf;
FROM  Arguments   IMPORT  ArgTable, GetEnv;
FROM  Strings     IMPORT  Assign, Length, String;

VAR  EnvVars             : ArgTable;

PROCEDURE ReadEnvVar;

VAR   Value          : String;
      i              : CARDINAL;

BEGIN
   WriteString ('
');
   WriteString ('
Index	Length	Content
');
   i := 0;
   LOOP
      IF  EnvVars^ [i] = NIL  THEN  EXIT  END;
      Assign (Value, EnvVars^ [i]^);
      WriteString ('
');
      WriteCard (i, 2);
      WriteString ('	');
      WriteCard (Length (Value), 3);
      WriteString ('	');    WriteString (Value);
      WriteString ("
");
      WriteLn;
      INC (i)
   END;
   WriteString("
");
END ReadEnvVar;

BEGIN
   GetEnv (EnvVars);
   WriteString ('Content-type:text/html');
   WriteLn;
   WriteLn;
   WriteString ('');
   WriteString ('<title>CGI with the Mocka Modula-2 compiler</title>');
   WriteString ('');
   WriteLn;
   WriteString ('
CGI environment passed along by your browser

');
   ReadEnvVar;
   WriteString ('');
   WriteLn;
   WriteBf
END testCGI.


f:=proc(s::string,c::string,count::nonnegint) local n;
     n:=StringTools:-Search(c,s);
     if n>0 then 1+procname(s[n+length(c)..],c,count);
     else 0; end if;
end proc:

f("the three truths","th",0);

f("ababababab","abab",0);


StringPosition["the three truths","th",Overlaps->False]//Length
3
StringPosition["ababababab","abab",Overlaps->False]//Length
2


  % Count occurrences of a substring without overlap
  length(findstr("ababababab","abab",0))
  length(findstr("the three truths","th",0))

  % Count occurrences of a substring with overlap
  length(findstr("ababababab","abab",1))


scount(e, s) := block(
   [n: 0, k: 1],
   while integerp(k: ssearch(e, s, k)) do (n: n + 1, k: k + 1),
   n
)$

scount("na", "banana");
2


string.count = function(s)
    return self.split(s).len - 1
end function

print "the three truths".count("th")
print "ababababab".count("abab")


Module FindCoins {
      Function count(c(), n)  {
            dim table(n+1)[email protected] :  table(0)[email protected]
            for c=0 to len(c())-1 {
                 if c(c)>n then exit
            }
            if c else exit
            for i=0 to c-1 {for j=c(i) to n {table(j)+=table(j-c(i))}}
            =table(n)
      }
      Print "For 1$ ways to change:";count((1,5,10,25),100)
      Print "For 100$ (optional task ways to change):";count((1,5,10,25,50,100),100000)
}
FindCoins


CountCoins[amount_, coinlist_] := ( ways = ConstantArray[1, amount];
Do[For[j = coin, j <= amount, j++,
  If[ j - coin == 0,
    ways[[j]] ++,
    ways[[j]] += ways[[j - coin]]
]]
, {coin, coinlist}];
ways[[amount]])


import Nanoquery.Util

random = new(Random)

println "
"

// generate header
println "
	X	Y	Z
"

// generate five rows
for i in range(1, 5)
	println "
" + i + "	"
	println "" + int($random.getInt(8999) + 1000) + "	"
	println "" + int($random.getInt(8999) + 1000) + "	"
	println "" + int($random.getInt(8999) + 1000) + "	"
	println "
"
end for

println "
"


/* NetRexx */
options replace format comments java crossref symbols nobinary

-- create some test data.  Put the data in a Rexx indexed string
maxI = 1000
rng = Random()
xyz = ''
xyz[0] = 1; xyz[1] = '. X Y Z' -- use a dot to indicate an empty cell
loop r_ = 1 for 5
  ra = r_ rng.nextInt(maxI) rng.nextInt(maxI) rng.nextInt(maxI)
  xyz[0] = r_ + 1; xyz[r_ + 1] = ra
  end r_

-- build an HTML string
html = htmlHeader()
html = html || htmlTable(xyz)
html = html || htmlFooter()

-- display HTML at standard output device
say html

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- HTML boilerplate header
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlHeader() public static returns Rexx
  html = '<?xml version="1.0" encoding="UTF-8"?>\n' -
      || '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' -
      || '\n' -
      || '\n' -
      || '<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>\n' -
      || '<title>RCreateHTMLTable</title>\n' -
      || '\n' -
      || '\n' -
      || '\n' -
      || '
Rosetta Code – NetRexx Sample Output
\n' -
      || '
Create an HTML table
\n' -
      || ''

  return html

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- HTML footer
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlFooter() public static returns Rexx
  html = '\n' -
      || '\n' -
      || ''
  return html

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Create the table
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlTable(rows, caption = '') public static returns Rexx
  html = '
\n'
  if caption.length() > 0 then do
    html = html -
        || '
'caption'
\n' -
        || '
\n' -
        || ''
    end
  html = html -
      || htmlCsvTableRow(rows[1], 'th')'\n' -
      || '
\n' -
      || '
\n' -
      || ''
  loop r_ = 2 to rows[0]
    html = html -
        || htmlCsvTableRow(rows[r_])
    end r_
  html = html -
      || '
\n' -
      || '
\n' -
      || ''
  return html

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Add a row to the table
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method htmlCsvTableRow(row, tag = 'td', sep = ' ', emptyCell = '.') public static returns Rexx
  if tag = null then tag = 'td'
  row = row.strip('t')
  -- replace HTML special characters with symbol entities
  row = row.changestr('&', '&') -- need to do this one first to avoid double translation
  row = row.changestr('"', '"')
  row = row.changestr("'", ''')
  row = row.changestr('<', '<')
  row = row.changestr('>', '>')
  elmts = ''
  elmts[0] = 0
  e_ = 0
  loop while row.length() > 0
    parse row elmt (sep) row
    if elmt == emptyCell then elmt = ' ' -- replace empy cells with non-breaking spaces
    e_ = e_ + 1; elmts[0] = e_; elmts[e_] = elmt
    end
  html = '
\n' -
      || ''
  loop e_ = 1 to elmts[0]
    html = html -
        || '<'tag'>'elmts[e_]'</'tag'>\n' -
        || ''
    end e_
  html = html -
      || '
\n' -
      || ''
  return html


import java.util.regex.Pattern
import java.util.regex.Matcher

#The "remove and count the difference" method
def count_substring(pattern:string, source:string)
    (source.length() - source.replace(pattern, "").length()) / pattern.length()
end

puts count_substring("th", "the three truths")      # ==> 3
puts count_substring("abab", "ababababab")          # ==> 2
puts count_substring("a*b", "abaabba*bbaba*bbab")   # ==> 2

# The "split and count" method
def count_substring2(pattern:string, source:string)
    # the result of split() will contain one more element than the delimiter
	# the "-1" second argument makes it not discard trailing empty strings
    source.split(Pattern.quote(pattern), -1).length - 1
end

puts count_substring2("th", "the three truths")      # ==> 3
puts count_substring2("abab", "ababababab")          # ==> 2
puts count_substring2("a*b", "abaabba*bbaba*bbab")   # ==> 2

# This method does a match and counts how many times it matches
def count_substring3(pattern:string, source:string)
    result = 0
    Matcher m = Pattern.compile(Pattern.quote(pattern)).matcher(source);
    while (m.find())
        result = result + 1
    end
    result
end

puts count_substring3("th", "the three truths")      # ==> 3
puts count_substring3("abab", "ababababab")          # ==> 2
puts count_substring3("a*b", "abaabba*bbaba*bbab")   # ==> 2


def countSubstring(str, subStr)
        return int((len(str) - len(str.replace(subStr, ""))) / len(subStr))
end


using System.Console;

module CountSubStrings
{
    CountSubStrings(this text : string, target : string) : int
    {
        match (target) {
            |"" => 0
            |_ => (text.Length - text.Replace(target, "").Length) / target.Length
        }
    }

    Main() : void
    {
        def text1 = "the three truths";
        def target1 = "th";
        def text2 = "ababababab";
        def target2 = "abab";

        WriteLine($"$target1 occurs $(text1.CountSubStrings(target1)) times in $text1");
        WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2");
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method countSubstring(inStr, findStr) public static
  return inStr.countstr(findStr)

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
  strings = ''
  find = 'FIND'
  ix = 0
  ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'the three truths'; strings[ix, find] = 'th'
  ix = ix + 1; strings[0] = ix; find[0] = ix; strings[ix] = 'ababababab';       strings[ix, find] = 'abab'

  loop ix = 1 to strings[0]
    str = strings[ix]
    fnd = strings[ix, find]
    say 'there are' countSubstring(str, fnd) 'occurences of "'fnd'" in "'str'"'
    end ix

  return


%% Count_The_Coins
clear;close all;clc;
tic

for i = 1:2 % 1st loop is main challenge 2nd loop is optional challenge
    if (i == 1)
        amount = 100;                       % Matlab indexes from 1 not 0, so we need to add 1 to our target value
        amount = amount + 1;
        coins = [1 5 10 25];                % Value of coins we can use
    else
        amount = 100*1000;                  % Matlab indexes from 1 not 0, so we need to add 1 to our target value
        amount = amount + 1;
        coins = [1 5 10 25 50 100];         % Value of coins we can use
    end % End if
    ways = zeros(1,amount);                 % Preallocating for speed
    ways(1) = 1;                            % First solution is 1

    % Solves from smallest sub problem to largest (bottom up approach of dynamic programming).
    for j = 1:length(coins)
        for K = coins(j)+1:amount
            ways(K) = ways(K) + ways(K-coins(j));
        end % End for
    end % End for
        if (i == 1)
            fprintf(‘Main Challenge: %d \n', ways(amount));
        else
            fprintf(‘Bonus Challenge: %d \n', ways(amount));
        end % End if
end % End for
toc


:- module coins.
:- interface.
:- import_module int, io.
:- type coin ---> quarter; dime; nickel; penny.
:- type purse ---> purse(int, int, int, int).

:- pred sum_to(int::in, purse::out) is nondet.

:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module solutions, list, string.

:- func value(coin) = int.
value(quarter) = 25.
value(dime) = 10.
value(nickel) = 5.
value(penny) = 1.

:- pred supply(coin::in, int::in, int::out) is multi.
supply(C, Target, N) :- upto(Target div value(C), N).

:- pred upto(int::in, int::out) is multi.
upto(N, R) :- ( nondet_int_in_range(0, N, R0) -> R = R0 ; R = 0 ).

sum_to(To, Purse) :-
	Purse = purse(Q, D, N, P),
	sum(Purse) = To,
	supply(quarter, To, Q),
	supply(dime, To, D),
	supply(nickel, To, N),
	supply(penny, To, P).

:- func sum(purse) = int.
sum(purse(Q, D, N, P)) =
	value(quarter) * Q + value(dime) * D +
	value(nickel) * N + value(penny) * P.

main(!IO) :-
	solutions(sum_to(100), L),
	show(L, !IO),
	io.format("There are %d ways to make change for a dollar.\n",
                  [i(length(L))], !IO).

:- pred show(list(purse)::in, io::di, io::uo) is det.
show([], !IO).
show([P|T], !IO) :-
	io.write(P, !IO), io.nl(!IO),
	show(T, !IO).


; file:   html-table.lsp
; url:    http://rosettacode.org/wiki/Create_an_HTML_table
; author: oofoe 2012-01-29

(seed (time-of-day)) ; Initialize random number generator.

; The "tab" variable tracks the HTML indent. "pad" composes a line
; with the appropriate indent and a terminal newline.

(setq tab 0)
(define (pad text) (string (dup "  " tab) text "\n"))

; NewLISP allows almost any character in an identifier, so I can name
; my functions after the HTML elements they invoke. This one formats a
; single table data cell.

(define ( text) (pad (string "" text "	")))

; "
" will accept either a number of arguments, each one to be
; formatted as a table cell, or a single list argument, which is
; broken into table cells. For convenience, I format each list item
; with the "" function so I can feed it raw lists.

(define (
)
  (let ((data (args))
        (s    (pad "
")))

    (if (list? (data 0)) (setq data (data 0)))

    (inc tab)
    (dolist (el data) (extend s ( el)))
    (dec tab)

    (extend s (pad "
"))
    s))

; By defining "
" as a macro, I ensure that the rows won't be
; evaluated until I've got the table started, which preserves the
; formatting.

(define-macro (
)
  (let ((s (pad "
")))
    (inc tab) (doargs (row) (extend s (eval row)))  (dec tab)
    (extend s (pad "
"))
    s
    ))

; Test

(print (
 (
 "" "X" "Y" "Z")
                (
 (cons 0 (rand 1000 3)))
                (
 (cons 1 (rand 1000 3)))
                (
 (cons 2 (rand 1000 3)))
                ))

(exit)


; file:   stringcount.lsp
; url:    http://rosettacode.org/wiki/Count_occurrences_of_a_substring
; author: oofoe 2012-01-29

; Obvious (and non-destructive...)

; Note that NewLISP performs an /implicit/ slice on a string or list
; with this form "(start# end# stringorlist)". If the end# is omitted,
; the slice will go to the end of the string. This is handy here to
; keep removing the front part of the string as it gets matched.

(define (scount needle haystack)
  (let ((h (copy haystack)) ; Copy of haystack string.
        (i 0)               ; Cursor.
        (c 0))              ; Count of occurences.

    (while (setq i (find needle h))
      (inc c)
      (setq h ((+ i (length needle)) h)))

    c))                     ; Return count.

; Tricky -- Uses functionality from replace function to find all
; non-overlapping occurrences, replace them, and return the count of
; items replaced in system variable $0.

(define (rcount needle haystack)
  (replace needle haystack "X") $0)

; Test

(define (test f needle haystack)
  (println "Found " (f needle haystack)
           " occurences of '" needle "' in '" haystack "'."))

(dolist (f (list scount rcount))
        (test f "glart" "hinkerpop")
        (test f "abab"  "ababababab")
        (test f "th"    "the three truths")
        (println)
        )

(exit)


import strutils

proc count(s, sub: string): int =
  var i = 0
  while true:
    i = s.find(sub, i)
    if i < 0:
      break
    i += sub.len # i += 1 for overlapping substrings
    inc result

echo count("the three truths","th")

echo count("ababababab","abab")


@interface NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;
@end

@implementation NSString (CountSubstrings)
- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {
  return [[self componentsSeparatedByString:subStr] count] - 1;
}
@end

int main(int argc, const char *argv[]) {
  @autoreleasepool {

    NSLog(@"%lu", [@"the three truths" occurrencesOfSubstring:@"th"]);
    NSLog(@"%lu", [@"ababababab" occurrencesOfSubstring:@"abab"]);
    NSLog(@"%lu", [@"abaabba*bbaba*bbab" occurrencesOfSubstring:@"a*b"]);

  }
  return 0;
}


proc changes(amount: int, coins: openArray[int]): int =
  var ways = @[1]
  ways.setLen(amount+1)
  for coin in coins:
    for j in coin..amount:
      ways[j] += ways[j-coin]
  ways[amount]

echo changes(100, [1, 5, 10, 25])
echo changes(100000, [1, 5, 10, 25, 50, 100])


let changes amount coins =
  let ways = Array.make (amount + 1) 0L in
  ways.(0) <- 1L;
  List.iter (fun coin ->
    for j = coin to amount do
      ways.(j) <- Int64.add ways.(j) ways.(j - coin)
    done
  ) coins;
  ways.(amount)

let () =
  Printf.printf "%Ld\n" (changes    1_00 [25; 10; 5; 1]);
  Printf.printf "%Ld\n" (changes 1000_00 [100; 50; 25; 10; 5; 1]);
;;


import random, htmlgen
randomize()

template randTD(): string = td($rand(1000..9999))
proc randTR(x: int): string =
  tr(td($x, style="font-weight: bold"), randTD, randTD, randTD)

echo table(
  tr(th"", th"X", th"Y", th"Z"),
  randTR 1,
  randTR 2,
  randTR 3,
  randTR 4,
  randTR 5)


class CreateTable {
  function : Main(args : String[]) ~ Nil {
    s := String->New();

    s->Append("
");
    s->Append("
");
    s->Append("
	");
    td := "XYZ";
    for(i:=0; i<3; i+=1;) {
      s->Append("");
      s->Append(td->Get(i));
      s->Append("	");
    };
    s->Append("
");
    s->Append("
");
    s->Append("
");
    for(i:=0; i<3; i+=1;) {
      s->Append("
");
      s->Append(i);
      s->Append("	");
      for(j:=0; j<3; j+=1;) {
        s->Append("");
        s->Append((Float->Random() * 10000)->As(Int));
        s->Append("	");
      };
      s->Append("
");
    };
    s->Append("
");
    s->Append("
");

    s->PrintLine();
  }
}


let count_substring str sub =
  let sub_len = String.length sub in
  let len_diff = (String.length str) - sub_len
  and reg = Str.regexp_string sub in
  let rec aux i n =
    if i > len_diff then n else
      try
        let pos = Str.search_forward reg str i in
        aux (pos + sub_len) (succ n)
      with Not_found -> n
  in
  aux 0 0

let () =
  Printf.printf "count 1: %d\n" (count_substring "the three truth" "th");
  Printf.printf "count 2: %d\n" (count_substring "ababababab" "abab");
;;


: countSubString(s, sub)
   0 1 while(sub swap s indexOfAllFrom dup notNull) [ sub size +  1 under+ ]
   drop ;


 bag="the three truths"
 x="th"
 say left(bag,30) left(x,15) 'found' bag~countstr(x)

 bag="ababababab"
 x="abab"
 say left(bag,30) left(x,15) 'found' bag~countstr(x)

 -- can be done caselessly too
 bag="abABAbaBab"
 x="abab"
 say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x)


use 5.01;
use Memoize;

sub cc {
    my $amount = shift;
    return 0 if !@_ || $amount < 0;
    return 1 if $amount == 0;
    my $first = shift;
    cc( $amount, @_ ) + cc( $amount - $first, $first, @_ );
}
memoize 'cc';

# Make recursive algorithm run faster by sorting coins descending by value:
sub cc_optimized {
    my $amount = shift;
    cc( $amount, sort { $b <=> $a } @_ );
}

say 'Ways to change $ 1 with common coins: ',
    cc_optimized( 100, 1, 5, 10, 25 );
say 'Ways to change $ 1000 with addition of less common coins: ',
    cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 );


let () =
  let buf = Buffer.create 1 in
  let s = Buffer.add_string buf in
  Random.self_init();
  s "
";
  s "
";
  s "
	";
  List.iter (fun v ->
    s ("" ^ v ^ "	")
  ) ["X"; "Y"; "Z"];
  s "
";
  s "
";
  s "
";
  for i = 0 to pred 3 do
    s ("
" ^ string_of_int i ^ "	");
      for j = 0 to pred 3 do
        s ("" ^ string_of_int (Random.int 1000) ^ "	");
      done;
    s "
";
  done;
  s "
";
  s "
";
  print_endline (Buffer.contents buf)


subvec(v,u)={
	my(i=1,s);
	while(i+#u<=#v,
		for(j=1,#u,
			if(v[i+j-1]!=u[j], i++; next(2))
		);
		s++;
		i+=#u
	);
	s
};
substr(s1,s2)=subvec(Vec(s1),Vec(s2));
substr("the three truths","th")
substr("ababababab","abab")


sub countSubstring {
  my $str = shift;
  my $sub = quotemeta(shift);
  my $count = () = $str =~ /$sub/g;
  return $count;
#  or return scalar( () = $str =~ /$sub/g );
}

print countSubstring("the three truths","th"), "\n"; # prints "3"
print countSubstring("ababababab","abab"), "\n"; # prints "2"


function coin_count(sequence coins, integer amount)
    sequence s = repeat(0,amount+1)
    s[1] = 1
    for c=1 to length(coins) do
        for n=coins[c] to amount do
            s[n+1] += s[n-coins[c]+1]
        end for
    end for
    return s[amount+1]
end function


go =>
  Problems = [[      1*100, [25,10,5,1]],            % 1 dollar
              [    100*100, [100,50,25,10,5,1]],   % 100 dollars
              [  1_000*100, [100,50,25,10,5,1]],  % 1000 dollars
              [ 10_000*100, [100,50,25,10,5,1]], % 10000 dollars
              [100_000*100, [100,50,25,10,5,1]] % 100000 dollars
              ],
  foreach([N,L] in Problems)
     initialize_table, % clear the tabling from previous run
     println([n=N,l=L]),
     time(println(num_sols=coins(L,N,1)))
  end.

table
coins(Coins, Money, M) = Sum =>
    Sum1 = 0,
    Len = Coins.length,
    if M == Len then
      Sum1 := 1,
    else
       foreach(I in M..Len)
         if Money - Coins[I] == 0 then
            Sum1 := Sum1 + 1
         end,
         if Money - Coins[I] > 0 then
            Sum1 := Sum1 + coins(Coins, Money-Coins[I], I)
         end,
       end
    end,
    Sum = Sum1.


declare

[Roads] = {Module.link ['x-ozlib://wmeyer/roads/Roads.ozf']}

fun {Table Session}
   html(
      head(title("Show a table with row and column headings")
	   style(type:"text/css"
		 css(td 'text-align':center)
		))
      body(
	 {TagFromList table
	  tr(th th("X") th("Y") th("Z"))
	  |
	  {CreateRows 3 5}
	 }))
end

fun {CreateRows NumCols NumRows}
   {List.map {List.number 1 NumRows 1}
    fun {$ Row}
       {TagFromList tr
	td( {Int.toString Row} )
	|
	{List.map {List.number 1 NumCols 1}
	 fun {$ Col}
	    SequentialNumber = (Row-1)*NumCols + Col
	 in
	    td( {Int.toString SequentialNumber} )
	 end
	}}
    end
   }
end

TagFromList = List.toTuple

in

{Roads.registerFunction table Table}
{Roads.run}


sequence tests = {{"the three truths","th"},
                  {"ababababab","abab"},
                  {"ababababab","aba"},
                  {"ababababab","ab"},
                  {"ababababab","a"},
                  {"ababababab",""}}
integer start, count
string test, substring
for i=1 to length(tests) do
    start = 1
    count = 0
    {test, substring} = tests[i]
    while 1 do
        start = match(substring,test,start)
        if start=0 then exit end if
        start += length(substring)
        count += 1
    end while
    printf(1,"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n",{substring,count,test})
end for


<?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"


count_substrings_rec(S, SB) = C =>
    count_rec(S,SB,0,C).

count_rec([],_SB,Count,Count).
count_rec(SBRest,SB,Count0,Count) :-
  SBRest = SB ++ Rest, % "split" into substring and the rest of the string
  count_rec(Rest,SB,Count0+1,Count).
count_rec([T|Rest],SB,Count0,Count) :-
  T != SB, % this character is not a substring
  count_rec(Rest,SB,Count0,Count).


(de coins (Sum Coins)
   (let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins)  Prev)
      (do Sum
         (zero Prev)
         (for L Buf
            (inc (rot L) Prev)
            (setq Prev (car L)) ) )
      Prev ) )


:- use_module(library(clpfd)).

% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny
coins(Q, D, N, P, T) :-
	[Q,D,N,P] ins 0..T,
	T #= (Q * 25) + (D * 10) + (N * 5) + P.

coins_for(T) :-
	coins(Q,D,N,P,T),
	maplist(indomain, [Q,D,N,P]).


<@ SDCLIT>
	<@ DTBLIT>
		<@ DTRLITLIT>
			<@ DTDLITLIT>|[style]background-color:white</@>
			<@ DTD>X</@>
			<@ DTD>Y</@>
			<@ DTD>Z</@>|[style]width:100%; background-color:brown;color:white; text-align:center</@>
		<@ ITEFORLIT>10|
			<@ DTRLITCAP>
			<@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right</@>
			<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
			<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
			<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
			|[style]background-color:white;color:black</@>
		</@>
	</@>
|Number Table</@>


(de countSubstring (Str Sub)
   (let (Cnt 0  H (chop Sub))
      (for (S (chop Str)  S  (cdr S))
         (when (head H S)
            (inc 'Cnt)
            (setq S (map prog2 H S)) ) )
      Cnt ) )


write("%d %d\n",
      String.count("the three truths", "th"),
      String.count("ababababab", "abab"));


cnt: procedure options (main);
   declare (i, tally) fixed binary;
   declare (text, key) character (100) varying;

   get edit (text) (L); put skip data (text);
   get edit (key)  (L); put skip data (key);

   tally = 0; i = 1;
   do until (i = 0);
      i = index(text, key, i);
      if i > 0 then do; tally = tally + 1; i = i + length(key); end;
   end;
   put skip list (tally);
end cnt;


def changes(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1
    for coin in coins:
        for j in xrange(coin, amount + 1):
            ways[j] += ways[j - coin]
    return ways[amount]

print changes(100, [1, 5, 10, 25])
print changes(100000, [1, 5, 10, 25, 50, 100])


  [ stack ]                      is lim        (     --> s )

  [ swap dup 1+ lim put
    1 0 rot of join
    swap witheach
      [ 0 over of
        swap negate temp put
        lim share times
          [ over i^ peek
            over temp share peek
            + join ]
        temp take negate split
        nip nip ]
    -1 peek
    lim release ]                is makechange ( n [ --> n )

  say "With US coins." cr
  100 ' [ 1 5 10 25 ] makechange echo cr
  100000 ' [ 1 5 10 25 50 100 ] makechange echo cr
  cr
  say "With EU coins." cr
  100 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr
  100000 ' [ 1 2 5 10 20 50 100 200 ] makechange echo cr


my @heading = qw(X Y Z);
my $rows = 5;
print   '

',
        (map { "$_	" } @heading),
        "

";

for (1 .. $rows) {
        print   "
$_	",
                (map { "".int(rand(10000))."	" } @heading),
                "
";
}

print   "

";


100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;

/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
    DECLARE (P, N) ADDRESS, C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = N MOD 10 + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

/* COUNT OCCURRENCES OF SUBSTRING IN STRING */
COUNT$SUBSTRING: PROCEDURE (STR, MATCH) ADDRESS;
    DECLARE (STR, MATCH) ADDRESS, C BASED STR BYTE;
    DECLARE (SP, MP) ADDRESS, (SC BASED SP, MC BASED MP) BYTE;
    DECLARE COUNT ADDRESS;
    COUNT = 0;
    DO WHILE C <> '$';
        SP = STR;
        MP = MATCH;
        DO WHILE SC = MC;
            SP = SP + 1;
            MP = MP + 1;
        END;
        IF MC = '$' THEN DO;
            STR = SP;
            COUNT = COUNT + 1;
        END;
        ELSE DO;
            STR = STR + 1;
        END;
    END;
    RETURN COUNT;
END COUNT$SUBSTRING;

CALL PRINT$NUMBER(COUNT$SUBSTRING(.'THE THREE TRUTHS$', .'TH$')); /* PRINTS 3 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'ABABABABAB$', .'ABAB$')); /* PRINTS 2 */
CALL PRINT$NUMBER(COUNT$SUBSTRING(.'CAT$', .'DOG$')); /* PRINTS 0 */

CALL EXIT;
EOF


FUNCTION PBMAIN () AS LONG
    PRINT "the three truths, th:", TALLY("the three truths", "th")
    PRINT "ababababab, abab:", TALLY("ababababab", "abab")
END FUNCTION


[regex]::Matches("the three truths", "th").count


count_substring(String, Sub, Total) :-
    count_substring(String, Sub, 0, Total).

count_substring(String, Sub, Count, Total) :-
    ( substring_rest(String, Sub, Rest)
    ->
        succ(Count, NextCount),
        count_substring(Rest, Sub, NextCount, Total)
    ;
        Total = Count
    ).

substring_rest(String, Sub, Rest) :-
    sub_string(String, Before, Length, Remain, Sub),
    DropN is Before + Length,
    sub_string(String, DropN, Remain, 0, Rest).


#lang racket
(define (ways-to-make-change cents coins)
  (cond ((null? coins) 0)
        ((negative? cents) 0)
        ((zero? cents) 1)
        (else
         (+ (ways-to-make-change cents (cdr coins))
            (ways-to-make-change (- cents (car coins)) coins)))))

(ways-to-make-change 100 '(25 10 5 1)) ; -> 242


# Recursive (cached)
sub change-r($amount, @coins) {
    my @cache = [1 xx @coins], |([] xx $amount);

    multi ways($n where $n >= 0, @now [$coin,*@later]) {
        @cache[$n;+@later] //= ways($n - $coin, @now) + ways($n, @later);
    }
    multi ways($,@) { 0 }

    # more efficient to start with coins sorted in descending order
    ways($amount, @coins.sort(-*).list);
}

# Iterative
sub change-i(\n, @coins) {
    my @table = [1 xx @coins], [0 xx @coins] xx n;
    (1..n).map: -> \i {
        for ^@coins -> \j {
        my \c = @coins[j];
        @table[i;j] = [+]
            @table[i - c;j] // 0,
            @table[i;j - 1] // 0;
        }
    }
    @table[*-1][*-1];
}

say "Iterative:";
say change-i    1_00, [1,5,10,25];
say change-i 1000_00, [1,5,10,25,50,100];

say "\nRecursive:";
say change-r    1_00, [1,5,10,25];
say change-r 1000_00, [1,5,10,25,50,100];


puts(1,"
\n")
puts(1,"
	")
for j=1 to 3 do
    printf(1,"%s	",'W'+j)
end for
puts(1,"
\n")
for i=1 to 3 do
    printf(1,"
%d	",i)
    for j=1 to 3 do
        printf(1,"%d	",rand(10000))
    end for
    puts(1,"
\n")
end for
puts(1,"
")


a = CountString("the three truths","th")
b = CountString("ababababab","abab")
; a = 3
; b = 2


>>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2


  [ [] 95 times
    [ i^ space +
      join ] ]         constant is alphabet     (         --> $       )

  [ [ 2dup != while
      -1 split drop
      swap 1 split
      unrot drop again ]
    drop size ]                 is overlap      (     [ [ --> n       )

  [ temp put [] swap
    alphabet witheach
      [ over -1 poke
        over overlap
        dup temp share
        = if negate
        swap dip join ]
    drop temp release ]         is eachend      (     [ n --> [       )

  [ [] swap
    dup temp put
    size times
      [ temp share
        i 1+ split drop
        temp share size eachend
        nested swap join ]
    temp release ]              is buildfsm     (       $ --> [       )

  [ dup [] = iff -1
    else
      [ behead
        dup carriage = if
          [ drop space ]
        space - ]
    swap ]                      is nextcharn    (       $ --> n $     )

  [ swap dup size
    swap temp put
    swap 0
    [ over swap peek
      temp take
      nextcharn
      temp put
      dup 0 < iff
        [ 2drop 0 ] done
      peek
      dup 0 < until ]
    nip
    temp take size - + ]        is usefsm       (     $ [ --> n       )

  [ over size 0 = iff
      [ 2drop 0 ]
    else
      [ swap buildfsm
        usefsm ] ]              is find$        (     $ $ --> n       )


count = function(haystack, needle)
   {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length")
    if (identical(v, -1L)) 0 else length(v)}

print(count("hello", "l"))


/*REXX program counts the number of ways to make change with coins from an given amount.*/
numeric digits 20                                /*be able to handle large amounts of $.*/
parse arg N $                                    /*obtain optional arguments from the CL*/
if N='' | N=","     then N= 100                  /*Not specified?  Then Use $1  (≡100¢).*/
if $='' | $=","     then $= 1 5 10 25            /*Use penny/nickel/dime/quarter default*/
if left(N, 1)=='$'  then N= 100 * substr(N, 2)   /*the count was specified in  dollars. */
coins= words($)                                  /*the number of coins specified.       */
NN= N;              do j=1  for coins            /*create a fast way of accessing specie*/
                    _= word($, j)                /*define an array element for the coin.*/
                    if _=='1/2'  then _=.5       /*an alternate spelling of a half-cent.*/
                    if _=='1/4'  then _=.25      /* "     "         "     " " quarter-¢.*/
                    $.j= _                       /*assign the value to a particular coin*/
                    end   /*j*/
_= n//100;                       cnt=' cents'    /* [↓]  is the amount in whole dollars?*/
if _=0  then do;    NN= '$' || (NN%100);   cnt=  /*show the amount in dollars, not cents*/
             end                                 /*show the amount in dollars, not cents*/
say 'with an amount of '      comma(NN)cnt",  there are "         comma( MKchg(N, coins) )
say 'ways to make change with coins of the following denominations: '    $
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
comma: procedure; parse arg _;     n= _'.9';      #= 123456789;      b= verify(n, #, "M")
       e= verify(n, #'0', , verify(n, #"0.", 'M'))  -  4
            do j=e  to b  by -3;   _= insert(',', _, j);    end  /*j*/;          return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
MKchg: procedure expose $.;        parse arg a,k /*this function is invoked recursively.*/
       if a==0    then return 1                  /*unroll for a special case of  zero.  */
       if k==1    then return 1                  /*   "    "  "    "      "   "  unity. */
       if k==2    then f= 1                      /*handle this special case   of  two.  */
                  else f= MKchg(a, k-1)          /*count,  and then recurse the amount. */
       if a==$.k  then return f+1                /*handle this special case of A=a coin.*/
       if a <$.k  then return f                  /*   "     "     "      "   " A<a coin.*/
                       return f+MKchg(a-$.k,k)   /*use diminished amount ($) for change.*/


<?php
/**
 * @author Elad Yosifon
 * @desc HTML Table - normal style
 */
$cols = array('', 'X', 'Y', 'Z');
$rows = 3;

$html = '
<colgroup>';
foreach($cols as $col)
{
	$html .= '<col style="text-align: left;" />';
}
unset($col);
$html .= '</colgroup>

';

foreach($cols as $col)
{
	$html .= "{$col}	";
}
unset($col);

$html .= '

';
for($r = 1; $r <= $rows; $r++)
{
	$html .= '
';
	foreach($cols as $key => $col)
	{
		$html .= '' . (($key > 0) ? rand(1, 9999) : $r) . '	';
	}
	unset($col);
	$html .= '
';
}
$html .= '

';

echo $html;


(define count-substring
  (compose length regexp-match*))


sub count-substring($big, $little) { +$big.comb: / :r $little / }

say count-substring("the three truths", "th"); # 3
say count-substring("ababababab", "abab");     # 2

say count-substring(123123123, 12);            # 3


Red []

count-occurrences: function [string substring] [
    length? parse string [collect [some [keep substring to substring]]]
]

test-case-1: "the three truths"
test-case-2: "ababababab"

print [test-case-1 "-" count-occurrences test-case-1 "th"]
print [test-case-2 "-" count-occurrences test-case-2 "abab"]


/*REXX program counts the  occurrences  of a (non─overlapping)  substring  in a string. */
w=.                                                                 /*max. width so far.*/
bag= 'the three truths'    ;      x= "th"       ;        call showResult
bag= 'ababababab'          ;      x= "abab"     ;        call showResult
bag= 'aaaabacad'           ;      x= "aa"       ;        call showResult
bag= 'abaabba*bbaba*bbab'  ;      x= "a*b"      ;        call showResult
bag= 'abaabba*bbaba*bbab'  ;      x= " "        ;        call showResult
bag=                       ;      x= "a"        ;        call showResult
bag=                       ;      x=            ;        call showResult
bag= 'catapultcatalog'     ;      x= "cat"      ;        call showResult
bag= 'aaaaaaaaaaaaaa'      ;      x= "aa"       ;        call showResult
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
countstr:   procedure;  parse arg haystack,needle,start;      if start==''  then start=1
            width=length(needle)
                                  do $=0  until p==0;         p=pos(needle,haystack,start)
                                  start=width + p                    /*prevent overlaps.*/
                                  end   /*$*/
            return $                                                 /*return the count.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
showResult: if w==. then do;                   w=30        /*W:  largest haystack width.*/
                         say center('haystack',w)  center('needle',w%2)  center('count',5)
                         say left('', w, "═")      left('', w%2, "═")    left('', 5, "═")
                         end

            if bag==''  then bag= " (null)"                /*handle displaying of nulls.*/
            if   x==''  then   x= " (null)"                /*   "        "      "   "   */
            say left(bag, w)           left(x, w%2)            center(countstr(bag, x), 5)
            return


penny = 1
nickel = 1
dime = 1
quarter = 1
count = 0

for penny = 0 to 100
    for nickel = 0 to 20
        for dime = 0 to 10
            for quarter = 0 to 4
                if (penny + nickel * 5 + dime * 10 + quarter * 25) = 100
                   see "" + penny + " pennies " + nickel + " nickels " + dime + " dimes " + quarter + " quarters" + nl
                   count = count + 1
                ok
            next
        next
    next
next
see  count + " ways to make a dollar" + nl


def make_change(amount, coins)
  @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)}
  @coins = coins
  do_count(amount, @coins.length - 1)
end

def do_count(n, m)
  if n < 0 || m < 0
    0
  elsif @cache[n][m]
    @cache[n][m]
  else
    @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1)
  end
end

p make_change(   1_00, [1,5,10,25])
p make_change(1000_00, [1,5,10,25,50,100])


(load "@lib/xhtml.l")

(<table> NIL NIL '(NIL (NIL "X") (NIL "Y") (NIL "Z"))
   (for N 3
      (<row> NIL N 124 456 789) ) )


/* Create an HTML table.  6/2011  */

create: procedure options (main);

create_table: procedure (headings, table_contents);

   declare headings(*) character (10) varying;
   declare table_contents(*, *) fixed;
   declare (i, row, col) fixed;

   put skip edit ('
') (a);
   /* Headings. */
   put skip edit ('
	 ') (a);
                               /* For an empty column heading */
   do i = 1 to hbound(headings);
      put edit ('', headings(i), '	 ' ) (a);
   end;
   put edit ('
') (a);

   /* Table contents. */

   do row = 1 to hbound(table_contents, 1);
      /* row number */
      put skip edit ('
', row, '	 ') (a);
      /* row contents */
      do col = 1 to hbound(table_contents, 2);
         put edit ('', table_contents(row, col), '	 ' ) (a);
      end;
      put edit ('
') (a);
   end;
   put skip edit ('
' ) (a);
end create_table;

   declare headings (3) character (1) static initial ('X', 'Y', 'Z');

   declare table_contents(3, 3) fixed static initial (
      4, -3, 8,
      7, 2, -6,
      11, 1, 15);

   call create_table (headings, table_contents);

end create;


aString = "Ring Welcome Ring to the Ring Ring Programming Ring Language Ring"
bString = "Ring"
see count(aString,bString)

func count cString,dString
     sum = 0
     while substr(cString,dString) > 0
           sum++
           cString = substr(cString,substr(cString,dString)+len(string(sum)))
     end
     return sum


def countSubstrings str, subStr
  str.scan(subStr).length
end

p countSubstrings "the three truths", "th"      #=> 3
p countSubstrings "ababababab", "abab"          #=> 2


print countSubstring("the three truths","th")
print countSubstring("ababababab","abab")

FUNCTION countSubstring(s$,find$)
WHILE instr(s$,find$,i) <> 0
  countSubstring = countSubstring + 1
  i = instr(s$,find$,i) + len(find$)
WEND
END FUNCTION


fn main() {
    println!("{}","the three truths".matches("th").count());
    println!("{}","ababababab".matches("abab").count());
}


import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
   @tailrec def count(pos:Int, c:Int):Int={
      val idx=str1 indexOf(str2, pos)
      if(idx == -1) c else count(idx+str2.size, c+1)
   }
   count(0,0)
}


for penny         = 0 to 100
  for nickel      = 0 to 20
    for dime      = 0 to 10
      for quarter = 0 to 4
       if penny + nickel * 5 + dime * 10 + quarter * 25 = 100 then
        print penny;" pennies ";nickel;" nickels "; dime;" dimes ";quarter;" quarters"
        count = count + 1
      end if
      next quarter
    next dime
  next nickel
next penny
print count;" ways to make a buck"


fn make_change(coins: &[usize], cents: usize) -> usize {
    let size = cents + 1;
    let mut ways = vec![0; size];
    ways[0] = 1;
    for &coin in coins {
        for amount in coin..size {
            ways[amount] += ways[amount - coin];
        }
    }
    ways[cents]
}

fn main() {
    println!("{}", make_change(&[1,5,10,25], 100));
    println!("{}", make_change(&[1,5,10,25,50,100], 100_000));
}


/* call OPTMODEL procedure in SAS/OR */
proc optmodel;
   /* declare set and names of coins */
   set COINS = {1,5,10,25};
   str name {COINS} = ['penny','nickel','dime','quarter'];

   /* declare variables and constraint */
   var NumCoins {COINS} >= 0 integer;
   con Dollar:
      sum {i in COINS} i * NumCoins[i] = 100;

   /* call CLP solver */
   solve with CLP / findallsolns;

   /* write solutions to SAS data set */
   create data sols(drop=s) from [s]=(1.._NSOL_) {i in COINS} <col(name[i])=NumCoins[i].sol[s]>;
quit;

/* print all solutions */
proc print data=sols;
run;


# Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.
ConvertTo-Html -inputobject (Get-Date)

# Create a PowerShell object using a HashTable
$object = [PSCustomObject]@{
        'A'=(Get-Random -Minimum 0 -Maximum 10);
        'B'=(Get-Random -Minimum 0 -Maximum 10);
        'C'=(Get-Random -Minimum 0 -Maximum 10)}

$object | ConvertTo-Html


gosh> (use gauche.lazy)
#<undef>
gosh> (length (lrxmatch "th" "the three truths"))
3
gosh> (length (lrxmatch "abab" "ababababab"))
2


$ include "seed7_05.s7i";

const func integer: countSubstring (in string: stri, in string: searched) is func
  result
    var integer: count is 0;
  local
    var integer: offset is 0;
  begin
    offset := pos(stri, searched);
    while offset <> 0 do
      incr(count);
      offset := pos(stri, searched, offset + length(searched));
    end while;
  end func;

const proc: main is func
  begin
    writeln(countSubstring("the three truths", "th"));
    writeln(countSubstring("ababababab", "abab"));
  end func;


put the number of occurrences of "th" in "the three truths" --> 3
put the number of occurrences of "abab" in "ababababab" -- > 2


say "the three truths".count("th");
say "ababababab".count("abab");


def countChange(amount: Int, coins:List[Int]) = {
	  val ways = Array.fill(amount + 1)(0)
	  ways(0) = 1
	  coins.foreach (coin =>
	  for (j<-coin to amount)
		  ways(j) =  ways(j) + ways(j - coin)
		  )
	ways(amount)
  }

countChange (15, List(1, 5, 10, 25))


(define ways-to-make-change
  (lambda (x coins)
    (cond
      [(null? coins) 0]
      [(< x 0) 0]
      [(zero? x) 1]
      [else (+ (ways-to-make-change x (cdr coins)) (ways-to-make-change (- x (car coins)) coins))])))

(ways-to-make-change 100)


Title.s="Create an HTML table"

head.s=""
head.s+"<title>"+Title.s+"</title>"+chr(13)+chr(10)

tablehead.s
tablehead.s+"
"+chr(13)+chr(10)
tablehead.s+"
	X	Y	Z
"+chr(13)+chr(10)

index=0

tablebody.s=""
for row=1 to 4
index+1
tablebody.s+"
"+str(index)+"	"
for col=1 to 3
tablebody.s+""+str(Random(9999,1))+"	"
next
tablebody.s+"
"+chr(13)+chr(10)
next

tablefoot.s=""
tablefoot.s+"
"+chr(13)+chr(10)

foot.s=""
foot.s+""+chr(13)+chr(10)

FileName.s="Create_an_HTML_table.html"
If CreateFile(0,FileName.s)
    WriteString(0,head.s)
    WriteString(0,tablehead.s)
    WriteString(0,tablebody.s)
    WriteString(0,tablefoot.s)
    WriteString(0,foot.s)
    CloseFile(0)
    Else
    Debug "Not WriteString :"+FileName.s
EndIf

; RunProgram(FileName.s)


BEGIN

    INTEGER PROCEDURE COUNTSUBSTRING(T,TSUB); TEXT T,TSUB;
    BEGIN
        INTEGER N,I;
        I := 1;
        WHILE I+TSUB.LENGTH-1 <= T.LENGTH DO
          IF T.SUB(I,TSUB.LENGTH) = TSUB THEN
          BEGIN
              N := N+1;
              I := I+MAX(TSUB.LENGTH,1);
          END ELSE I := I+1;
        COUNTSUBSTRING:= N;
    END COUNTSUBSTRING;

    OUTINT(COUNTSUBSTRING("THE THREE TRUTHS", "TH"),0);
    OUTIMAGE;
    OUTINT(COUNTSUBSTRING("ABABABABAB", "ABAB"),0);
    OUTIMAGE;
END.


Transcript showCR:('the three truths' occurrencesOfString:'th').
Transcript showCR:('ababababab' occurrencesOfString:'abab')


        DEFINE("countSubstring(t,s)")

        OUTPUT = countSubstring("the three truths","th")
        OUTPUT = countSubstring("ababababab","abab")

        :(END)
countSubstring t ARB s = :F(RETURN)
        countSubstring = countSubstring + 1 :(countSubstring)
END
3
2


fun count_substrings (str, sub) =
  let
    fun aux (str', count) =
      let
        val suff = #2 (Substring.position sub str')
      in
        if Substring.isEmpty suff then
       	  count
        else
          aux (Substring.triml (size sub) suff, count + 1)
      end
  in
    aux (Substring.full str, 0)
  end;

print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n");


function strcount(s, x) {
	n = 0
	k = 1-(i=strlen(x))
	do {
		if (k = ustrpos(s, x, k+i)) n++
	} while(k)
	return(n)
}

strcount("peter piper picked a peck of pickled peppers", "pe")
  5

strcount("ababababab","abab")
  2


amount=100;
coins=[25 10 5 1];
n_coins=zeros(coins);
ways=0;

for a=0:4
    for b=0:10
        for c=0:20
            for d=0:100
                n_coins=[a b c d];
                change=sum(n_coins.*coins);
                if change==amount then
                    ways=ways+1;
                elseif change>amount
                    break
                end
            end
        end
    end
end

disp(ways);


$ include "seed7_05.s7i";
  include "bigint.s7i";

const func bigInteger: changeCount (in integer: amountCents, in array integer: coins) is func
  result
    var bigInteger: waysToChange is 0_;
  local
    var array bigInteger: t is 0 times 0_;
    var integer: pos is 0;
    var integer: s is 0;
    var integer: i is 0;
  begin
    t := length(coins) times 1_ & (length(coins) * amountCents) times 0_;
    pos := length(coins) + 1;
    for s range 1 to amountCents do
      if coins[1] <= s then
        t[pos] := t[pos - (length(coins) * coins[1])];
      end if;
      incr(pos);
      for i range 2 to length(coins) do
        if coins[i] <= s then
          t[pos] := t[pos - (length(coins) * coins[i])];
        end if;
        t[pos] +:= t[pos - 1];
        incr(pos);
      end for;
    end for;
    waysToChange := t[pos - 1];
  end func;

const proc: main is func
  local
    const array integer: usCoins is [] (1, 5, 10, 25, 50, 100);
    const array integer: euCoins is [] (1, 2, 5, 10, 20, 50, 100, 200);
  begin
    writeln(changeCount(    100, usCoins[.. 4]));
    writeln(changeCount( 100000, usCoins));
    writeln(changeCount(1000000, usCoins));
    writeln(changeCount( 100000, euCoins));
    writeln(changeCount(1000000, euCoins));
  end func;


func cc(_)                { 0 }
func cc({ .is_neg  }, *_) { 0 }
func cc({ .is_zero }, *_) { 1 }

func cc(amount, first, *rest) is cached {
    cc(amount, rest...) + cc(amount - first, first, rest...);
}

func cc_optimized(amount, *rest) {
    cc(amount, rest.sort_by{|v| -v }...);
}

var x = cc_optimized(100, 1, 5, 10, 25);
say "Ways to change $1 with common coins: #{x}";

var y = cc_optimized(1000 * 100, 1, 5, 10, 25, 50, 100);
say "Ways to change $1000 with addition of less common coins: #{y}";


import random

def rand9999():
    return random.randint(1000, 9999)

def tag(attr='', **kwargs):
    for tag, txt in kwargs.items():
        return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())

if __name__ == '__main__':
    header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
    rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
                                    + ''.join(tag(td=rand9999())
                                              for j in range(3)))
                     for i in range(1, 6))
    table = tag(table='\n' + header + rows + '\n')
    print(table)


import Foundation

func countSubstring(str: String, substring: String) -> Int {
  return str.components(separatedBy: substring).count - 1
}

print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab"))


proc countSubstrings {haystack needle} {
    regexp -all ***=$needle $haystack
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"]


#lang transd

MainModule: {
    countSubstring: (λ s String() sub String()
        (with n 0 pl 0
            (while (> (= pl (find s sub pl)) -1)
                (+= pl (size sub)) (+= n 1))
            (lout n))
    ),
    _start: (λ
        (countSubstring "the three truths" "th")
        (countSubstring "ababababab" "abab")
    )
}


$$ MODE TUSCRIPT, {}
occurences=COUNT ("the three truths",  ":th:")
occurences=COUNT ("ababababab",   ":abab:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")


import BigInt

func countCoins(amountCents cents: Int, coins: [Int]) -> BigInt {
  let cycle = coins.filter({ $0 <= cents }).map({ $0 + 1 }).max()! * coins.count
  var table = [BigInt](repeating: 0, count: cycle)

  for x in 0..<coins.count {
    table[x] = 1
  }

  var pos = coins.count

  for s in 1..<cents+1 {
    for i in 0..<coins.count {
      if i == 0 && pos >= cycle {
        pos = 0
      }

      if coins[i] <= s {
        let q = pos - coins[i] * coins.count
        table[pos] = q >= 0 ? table[q] : table[q + cycle]
      }

      if i != 0 {
        table[pos] += table[pos - 1]
      }

      pos += 1
    }
  }

  return table[pos - 1]
}

let usCoins = [100, 50, 25, 10, 5, 1]
let euCoins = [200, 100, 50, 20, 10, 5, 2, 1]

for set in [usCoins, euCoins] {
  print(countCoins(amountCents: 100, coins: Array(set.dropFirst(2))))
  print(countCoins(amountCents: 100000, coins: set))
  print(countCoins(amountCents: 1000000, coins: set))
  print(countCoins(amountCents: 10000000, coins: set))
  print()
}


templates makeChange&{coins:}
  def paid: $;
  @: [1..$paid -> 0];
  $coins... -> \(def coin: $;
    @makeChange($coin): [email protected]($coin) + 1;
    $coin+1..$paid -> @makeChange($): [email protected]($) + [email protected]($-$coin);
  \) -> !VOID
  [email protected]($paid)!
end makeChange

100 -> makeChange&{coins: [1,5,10,25]} -> '$; ways to change a dollar
' -> !OUT::write
100000 -> makeChange&{coins: [1,5,10,25,50,100]} -> '$; ways to change 1000 dollars with all coins
' -> !OUT::write


package require Tcl 8.5

proc makeChange {amount coins} {
    set table [lrepeat [expr {$amount+1}] [lrepeat [llength $coins] {}]]
    lset table 0 [lrepeat [llength $coins] 1]
    for {set i 1} {$i <= $amount} {incr i} {
	for {set j 0} {$j < [llength $coins]} {incr j} {
	    set k [expr {$i - [lindex $coins $j]}]
	    lset table $i $j [expr {
		($k < 0 ? 0 : [lindex $table $k $j]) +
		($j < 1 ? 0 : [lindex $table $i [expr {$j-1}]])
	    }]
	}
    }
    return [lindex $table end end]
}

puts [makeChange 100 {1 5 10 25}]
puts [makeChange 100000 {1 5 10 25 50 100}]
# Making change with the EU coin set:
puts [makeChange 100 {1 2 5 10 20 50 100 200}]
puts [makeChange 100000 {1 2 5 10 20 50 100 200}]


#lang racket

(require xml)

(define xexpr
  `(html
    (head)
    (body
     (table
      (tr (td) (td "X") (td "Y") (td "Z"))
      ,@(for/list ([i (in-range 1 4)])
          `(tr (td ,(~a i))
               (td ,(~a (random 10000)))
               (td ,(~a (random 10000)))
               (td ,(~a (random 10000)))))))))

(display-xml/content (xexpr->xml xexpr))


my @header =  <  X Y Z>;
my $rows = 5;

sub tag ($tag, $string, $param?) { return "<$tag" ~ ($param ?? " $param" !! '') ~ ">$string" ~ "</$tag>" };

my $table = tag('tr', ( tag('th', $_) for @header));

for 1 .. $rows -> $row {
    $table ~=  tag('tr', ( tag('td', $row, 'align="right"')
    ~ (tag('td', (^10000).pick, 'align="right"') for 1..^@header)));
}

say tag('table', $table, 'cellspacing=4 style="text-align:right; border: 1px solid;"');


@(next :args)
@(do (defun count-occurrences (haystack needle)
       (for* ((occurrences 0)
              (old-pos 0)
              (new-pos (search-str haystack needle old-pos nil)))
             (new-pos occurrences)
             ((inc occurrences)
              (set old-pos (+ new-pos (length needle)))
              (set new-pos (search-str haystack needle old-pos nil))))))
@ndl
@hay
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end)


#!/bin/bash

function countString(){
	input=$1
	cnt=0

	until [ "${input/$2/}" == "$input" ]; do
		input=${input/$2/}
		let cnt+=1
	done
	echo $cnt
}

countString "the three truths" "th"
countString "ababababab" "abab"


Function CountStringInString(stLookIn As String, stLookFor As String)
    CountStringInString = UBound(Split(stLookIn, stLookFor))
End Function


Function CountSubstring(str,substr)
	CountSubstring = 0
	For i = 1 To Len(str)
		If Len(str) >= Len(substr) Then
			If InStr(i,str,substr) Then
				CountSubstring = CountSubstring + 1
				i = InStr(i,str,substr) + Len(substr) - 1
			End If
		Else
			Exit For
		End If
	Next
End Function

WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf


c = 0
for p       = 0 to 100
  for n     = 0 to 20
    for d   = 0 to 10
      for q = 0 to 4
       if p + n * 5 + d * 10 + q * 25 = 100 then
         print p;" pennies ";n;" nickels "; d;" dimes ";q;" quarters"
         c = c + 1
       endif
      next q
    next d
  next n
next p
print c;" ways to make a buck"


function count_change {
  local -i amount=$1 coin j
  local ways=(1)
  shift
  for coin; do
    for (( j=coin; j <= amount; j++ )); do
      let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0}
    done
  done
  echo "${ways[amount]}"
}
count_change 100 25 10 5 1
count_change 100000 100 50 25 10 5 1


Private Function coin_count(coins As Variant, amount As Long) As Variant 'return type will be Decimal
    'sequence s = Repeat(0, amount + 1)
    Dim s As Variant
    ReDim s(amount + 1)
    Dim c As Integer
    s(1) = CDec(1)
    For c = 1 To UBound(coins)
        For n = coins(c) To amount
            s(n + 1) = CDec(s(n + 1) + s(n - coins(c) + 1))
        Next n
    Next c
    coin_count = s(amount + 1)
End Function
Public Sub main2()
    Dim us_commons_coins As Variant
    'The next line creates a base 1 array
    us_common_coins = [{25, 10, 5, 1}]
    Debug.Print coin_count(us_common_coins, 100)
    Dim us_coins As Variant
    us_coins = [{100,50,25, 10, 5, 1}]
    Debug.Print coin_count(us_coins, 100000)
End Sub


import IO;
import util::Math;

str html(str title, str content) = item("html", item("title", title) + item("body", content));
str item(str op, str content) = "\<<op>\><content>\</<op>\>";
str table(str content) = item("table border=\"0\"", content);
str tr(str content) = item("tr", content);
str td(str content) = item("td", content);

public str generateTable(int rows){
	int i(){return arbInt(10000);};
	rows = (tr(td("")+td("X")+td("Y")+td("Z"))
			| it + tr(td("<x>")+td("<i()>")+td("<i()>")+td("<i()>"))
			| x <- [1..rows]);
	writeFile(|file:///location|,
	           html("Rosetta Code Table", table(rows)));
	return "written";
}


Create an HTML table

The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right
of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or
sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.

Red [
    Problem: %http://www.rosettacode.org/wiki/Create_an_HTML_table
    Code: %https://github.com/metaperl/red-rosetta/blob/master/html-table.r
    Acknowledgements: "@endo64 @toomsav"
]

result: func[][simple-tag "table" trs]

trs: func [][rejoin [
        first-tr
        rand-tr 1
        rand-tr 2
        rand-tr 3
        rand-tr 4
        rand-tr 5
    ]]

table-data: func [][999 + (random 9000)]
rand-td: func [][simple-tag "td" table-data]
rand-tr: func [i][rejoin [
        simple-tag "tr"
            rejoin [(simple-tag "td" i) rand-td rand-td rand-td]
    ]]
first-tr: func[][rejoin [
        simple-tag "tr" rejoin [
            simple-tag "th" ""
            simple-tag "th" "X"
            simple-tag "th" "Y"
            simple-tag "th" "Z"
            ]
    ]]

simple-tag: func [tag contents /attr a][rejoin
    ["<" tag (either attr [rejoin [" " a/1 "=" {"} a/2 {"}]][]) ">"
        newline contents newline "</" tag ">"]]


Module Count_Occurrences_of_a_Substring
    Sub Main()
        Console.WriteLine(CountSubstring("the three truths", "th"))
        Console.WriteLine(CountSubstring("ababababab", "abab"))
        Console.WriteLine(CountSubstring("abaabba*bbaba*bbab", "a*b"))
        Console.WriteLine(CountSubstring("abc", ""))
    End Sub

    Function CountSubstring(str As String, substr As String) As Integer
        Dim count As Integer = 0
        If (Len(str) > 0) And (Len(substr) > 0) Then
            Dim p As Integer = InStr(str, substr)
            Do While p <> 0
                p = InStr(p + Len(substr), str, substr)
                count += 1
            Loop
        End If
        Return count
    End Function
End Module


fn main(){
    println('the three truths'.count('th'))
    println('ababababab'.count('abab'))
}


@let {
  c &[s t] #!s.match &(t)g

  [[
    !!c "the three truths" "th"
    !!c "ababababab" "abab"
  ]]
}


import "/pattern" for Pattern
import "/fmt" for Fmt

var countSubstring = Fn.new { |str, sub|
    var p = Pattern.new(sub)
    return p.findAll(str).count
}

var tests = [
    ["the three truths", "th"],
    ["ababababab", "abab"],
    ["abaabba*bbaba*bbab", "a*b"],
    ["aaaaaaaaaaaaaa", "aa"],
    ["aaaaaaaaaaaaaa", "b"],
]

for (test in tests) {
    var count = countSubstring.call(test[0], test[1])
    Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
}


Function count(coins,m,n)
	ReDim table(n+1)
	table(0) = 1
	i = 0
	Do While i < m
		j = coins(i)
		Do While j <= n
			table(j) = table(j) + table(j - coins(i))
			j = j + 1
		Loop
		i = i + 1
	Loop
	count = table(n)
End Function

'testing
arr = Array(1,5,10,25)
m = UBound(arr) + 1
n = 100
WScript.StdOut.WriteLine count(arr,m,n)


Option Explicit
'----------------------------------------------------------------------
Private Function coin_count(coins As Variant, amount As Long) As Variant
'return type will be Decimal
Dim s() As Variant
Dim n As Long, c As Long

  ReDim s(amount + 1)
  s(1) = CDec(1)
  For c = LBound(coins) To UBound(coins)
    For n = coins(c) To amount
      s(n + 1) = CDec(s(n + 1) + s(n - coins(c) + 1))
    Next n
  Next c
  coin_count = s(amount + 1)
End Function
'----------------------------------------------------------------------
Sub Main()
Dim us_common_coins As Variant
Dim us_coins As Variant

  'The next line creates 0-based array
  us_common_coins = Array(25, 10, 5, 1)
  Debug.Print coin_count(us_common_coins, 100)

  us_coins = Array(100, 50, 25, 10, 5, 1)
  Debug.Print coin_count(us_coins, 100000)

End Sub


fn main() {
    amount := 100
    println("amount, ways to make change: $amount ${count_change(amount)}"))
}

fn count_change(amount int) i64 {
    return cc(amount, 4)
}

fn cc(amount int, kinds_of_coins int) i64 {
    if amount == 0 {
        return 1
    } else if amount < 0 || kinds_of_coins == 0 {
        return 0
    }
    return cc(amount, kinds_of_coins-1) +
        cc(amount - first_denomination(kinds_of_coins), kinds_of_coins)
}

fn first_denomination(kinds_of_coins int) int {
    match kinds_of_coins {
		1 {
			return 1
		}
		2 {
			return 5
		}
		3 {
			return 10
		}
		4 {
			return 25
		}
	}
}


needs casket::html'
with casket::html'

: rnd ( -$ ) random 1000 mod toString ;

[ [ [     ] td [ "x" ] td [ "y" ] td [ "z" ] td ] tr
  [ [ "1" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
  [ [ "2" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
  [ [ "3" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
  [ [ "4" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
  [ [ "5" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
  [ [ "6" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
] table


/*REXX program  creates (and displays)  an  HTML table of five rows  and  three columns.*/
parse arg rows .                                 /*obtain optional argument from the CL.*/
if rows=='' | rows==","   then rows=5            /*no ROWS specified?  Then use default.*/
      cols = 3                                   /*specify three columns for the table. */
   maxRand = 9999                                /*4-digit numbers, allows negative nums*/
headerInfo = 'X Y Z'                             /*specifify column header information. */
      oFID = 'a_table.html'                      /*name of the  output  file.           */
         w = 0                                   /*number of writes to the output file. */

call wrt  ""
call wrt  ""
call wrt  ""
call wrt  "
"

  do r=0  to rows                                /* [↓]  handle row  0 as being special.*/
  if r==0  then call wrt  "
	"        /*when it's     the zeroth row.        */
           else call wrt  "
"  r  "	" /*  "    "  not  "    "     "          */

      do c=1  for cols                           /* [↓]  for row 0,  add the header info*/
      if r==0  then call wrt  ""   word(headerInfo,c)   "	"
               else call wrt  ""    rnd()   "	"
      end   /*c*/
  end       /*r*/

call wrt  "
"
call wrt  ""
call wrt  ""
say;         say  w    ' records were written to the output file: '   oFID
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rnd: return right(random(0,maxRand*2)-maxRand,5) /*RANDOM doesn't generate negative ints*/
wrt: call lineout oFID,arg(1);   say '══►'  arg(1);   w=w+1;    return          /*write.*/


include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated strings, instead of MSb terminated

func    StrNCmp(A, B, N); \Compare string A to string B up to N bytes long
\This returns:
\       >0 if A > B
\       =0 if A = B
\       <0 if A < B
char    A, B;           \strings to be compared
int     N;              \number of bytes to compare
int     I;
[for I:= 0 to N-1 do
    if A(I) # B(I) then
        return A(I) - B(I);
return 0;               \they're equal
];      \StrNCmp

func    StrLen(Str);    \Return the number of characters in an ASCIIZ string
char    Str;
int     I;
for I:= 0 to -1>>1-1 do
        if Str(I) = 0 then return I;

func    SubStr(A, B);   \Count number of times string B occurs in A
char    A, B;
int     LA, LB, C, I;
[LA:= StrLen(A);  LB:= StrLen(B);
C:= 0;  I:= 0;
while I < LA do
        if StrNCmp(B, A+I, LB) = 0 then [C:= C+1;  I:= I+LB]
        else I:= I+1;
return C;
];

[IntOut(0, SubStr("the three truths", "th"));  CrLf(0);
 IntOut(0, SubStr("ababababab", "abab"));  CrLf(0);
]


fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;
   while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
   cnt
}


10 LET t$="ABABABABAB": LET p$="ABAB": GO SUB 1000
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
30 STOP
1000 PRINT t$: LET c=0
1010 LET lp=LEN p$
1020 FOR i=1 TO LEN t$-lp+1
1030 IF (t$(i TO i+lp-1)=p$) THEN LET c=c+1: LET i=i+lp-1
1040 NEXT i
1050 PRINT p$;"=";c''
1060 RETURN


import "/big" for BigInt
import "/fmt" for Fmt

var countCoins = Fn.new { |c, m, n|
    var table = List.filled(n + 1, null)
    table[0] = BigInt.one
    for (i in 1..n) table[i] = BigInt.zero
    for (i in 0...m) {
        for (j in c[i]..n) table[j] = table[j] + table[j-c[i]]
    }
    return table[n]
}

var c = [1, 5, 10, 25, 50, 100]
Fmt.print("Ways to make change for $$1 using 4 coins     = $,i", countCoins.call(c, 4, 100))
Fmt.print("Ways to make change for $$1,000 using 6 coins = $,i", countCoins.call(c, 6, 1000 * 100))


fcn ways_to_make_change(x, coins=T(25,10,5,1)){
   if(not coins) return(0);
   if(x<0)  return(0);
   if(x==0) return(1);
   ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins)
}
ways_to_make_change(100).println();


# Project: Create an HTML table

load "stdlib.ring"

str = ""
ncols = 3
nrows = 4

str = str + "" + windowsnl()
str = str + "
" + windowsnl()

for row = 0 to nrows
     if row = 0
        str = str + "
	"
    else
        str = str + "
" + row + "	"
    ok
    for col = 1 to ncols
         if row = 0
            str = str + "" + char(87 + col) + "	"
         else
            str = str + "" + random(9999) + "	"
         ok
    next
    str = str + windowsnl() + "
" +windowsnl()
next

str = str + "
" + windowsnl()
str = str + "" + windowsnl()

remove("temp.htm")
write("temp.htm",str)
see str + nl
systemcmd("temp.htm")


def r
  rand(10000)
end

STDOUT << "".tap do |html|
  html << "
"
  [
    ['X', 'Y', 'Z'],
    [r ,r ,r],
    [r ,r ,r],
    [r ,r ,r],
    [r ,r ,r]

  ].each_with_index do |row, index|
    html << "
"
    html << "#{index > 0 ? index : nil }	"
    html << row.map { |e| "#{e}	"}.join
    html << "
"
  end

  html << "
"
end


10 LET amount=100
20 GO SUB 1000
30 STOP
1000 LET nPennies=amount
1010 LET nNickles=INT (amount/5)
1020 LET nDimes=INT (amount/10)
1030 LET nQuarters=INT (amount/25)
1040 LET count=0
1050 FOR p=0 TO nPennies
1060 FOR n=0 TO nNickles
1070 FOR d=0 TO nDimes
1080 FOR q=0 TO nQuarters
1090 LET s=p+n*5+d*10+q*25
1100 IF s=100 THEN LET count=count+1
1110 NEXT q
1120 NEXT d
1130 NEXT n
1140 NEXT p
1150 PRINT count
1160 RETURN


html "

Row	X	Y	Z
"
for i = 1 to 5
  html "
"
  for j = 1 to 4
    if j = 1 then html "";i;"	" else html "";i;j;"	"
  next j
html "
"
next i
html "
"


extern crate rand;

use rand::Rng;

fn random_cell<R: Rng>(rng: &mut R) -> u32 {
    // Anything between 0 and 10_000 (exclusive) has 4 digits or fewer. Using `gen_range::<u32>`
    // is faster for smaller RNGs.  Because the parameters are constant, the compiler can do all
    // the range construction at compile time, removing the need for
    // `rand::distributions::range::Range`
    rng.gen_range(0, 10_000)
}

fn main() {
    let mut rng = rand::thread_rng(); // Cache the RNG for reuse

    println!("

	X	Y	Z

");

    for row in 0..3 {
        let x = random_cell(&mut rng);
        let y = random_cell(&mut rng);
        let z = random_cell(&mut rng);
        println!("
{}	{}	{}	{}
", row, x, y, z);
    }

    println!("
");
}


object TableGenerator extends App {
  val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33))

  def generateTable(data: List[List[Any]]) = {

      {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}.
      map(row =>

      {row.map(cell =>

          {cell}
        	)}

)}

  }

  println(generateTable(data))
}


(define table #(
                #("" "X" "Y" "Z")
                #(1 1 2 3)
                #(2 4 5 6)
                #(3 7 8 9)))

(display "
")
(do ((r 0 (+ r 1))) ((eq? r (vector-length table)))
        (display "
")
        (do ((c 0 (+ c 1))) ((eq? c (vector-length (vector-ref table r))))
                (if (eq? r 0)
                        (display ""))
                (if (> r 0)
                        (display ""))
                (display (vector-ref (vector-ref table r) c))
                (if (eq? r 0)
                        (display "	"))
                (if (> r 0)
                        (display "	")))
        (display "
"))
(display "
")


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: line is 0;
    var integer: column is 0;
  begin
    writeln("
");
    writeln("
	X	Y	Z
");
    for line range 1 to 3 do
      write("
" <& line <& "	");
      for column range 1 to 3 do
        write("" <& rand(0, 9999) <& "	");
      end for;
      writeln("
");
    end for;
    writeln("
")
  end func;


class HTML {
    method _attr(Hash h) {
        h.keys.sort.map {|k| %Q' #{k}="#{h{k}}"' }.join('')
    }

    method _tag(Hash h, name, value) {
        "<#{name}" + self._attr(h) + '>' + value + "</#{name}>"
    }

    method table(Hash h, *data) { self._tag(h, 'table', data.join('')) }
    method table(*data)         { self.table(Hash(), data...) }
}

class Table < HTML {
    method th(Hash h, value) { self._tag(h, 'th', value) }
    method th(value)         { self.th(Hash(), value) }

    method tr(Hash h, *rows) { self._tag(h, 'tr', rows.join('')) }
    method tr(*rows)         { self.tr(Hash(), rows...) }

    method td(Hash h, value) { self._tag(h, 'td', value) }
    method td(value)         { self.td(Hash(), value) }
}

var header = %w(  X Y Z);
var rows = 5;

var html = HTML.new;
var table = Table.new;

say html.table(
    # attributes
    Hash(
        cellspacing => 4,
        style => "text-align:right; border: 1px solid;"
     ),

    # header
    table.tr(header.map{|elem| table.th(elem)}...),

    # rows
    (1..rows).map { |i|
        table.tr(
            table.td(:(align => 'right'), i),
            (header.len - 1).of {
                table.td(Hash(align => 'right'), 10000.rand.int)
            }...
        )
    }...
);


* HTML Table
	output = "
"
	output = "
	X	Y	Z
"
	i = 1
o1	output = "
" i "	"
	j = 1
o2	output = "" i j "	"
	j = lt(j,3) j + 1 :s(o2)
	output = "
"
	i = lt(i,3) i + 1 :s(o1)
	output = "
"
end


(*
 * val mkHtmlTable : ('a list * 'b list) -> ('a -> string * 'b -> string)
 * 			-> (('a * 'b) -> string) -> string
 * The int list is list of colums, the function returns the values
 * at a given colum and row.
 * returns the HTML code of the generated table.
 *)
fun mkHtmlTable (columns, rows) (rowToStr, colToStr) values =
	let
	  val text = ref "
\n
	"
	in
	  (* Add headers *)
	  map (fn colum => text := !text ^ "" ^ (colToStr colum) ^ "	") columns;

	  text := !text ^ "
\n";
	  (* Add data rows *)
	  map (fn row =>
		(* row name *)
	  	(text := !text ^ "
" ^ (rowToStr row) ^ "	";
		(* data *)
		 map (fn col => text := !text ^ "" ^ (values (row, col)) ^ "	") columns;
		 text := !text ^ "
\n")
	      ) rows;
	  !text ^ "
"
	end

fun mkHtmlWithBody (title, body) = "\n\n<title>" ^ title ^ "</title>\n\n\n" ^ body ^ "\n\n\n"

fun samplePage () = mkHtmlWithBody ("Sample Page",
			mkHtmlTable ([1.0,2.0,3.0,4.0,5.0], [1.0,2.0,3.0,4.0])
			            (Real.toString, Real.toString)
				    (fn (a, b) => Real.toString (Math.pow (a, b))))

val _ = print (samplePage ())


program mat2html
local nr = rowsof(`1')
local nc = colsof(`1')
local rn `: rownames `1''
local cn `: colnames `1''
tempname f
qui file open `f' using `2', write text replace
file write `f' "<!doctype html>" _n
file write `f' "" _n
file write `f' "" _n
file write `f' `"<meta charset="UTF-8">"' _n
file write `f' "" _n
file write `f' "" _n
file write `f' `"
"' _n
* write column names
file write `f' "
" _n
file write `f' "	" _n
forv j = 1/`nc' {
	local s `: word `j' of `cn''
	file write `f' `"`s'	"' _n
}
file write `f' "
" _n
* write row names & data
forv i = 1/`nr' {
	file write `f' "
" _n
	local s `: word `i' of `rn''
	file write `f' `"`s'	"' _n
	forv j = 1/`nc' {
		file write `f' `"`=el(`1',`i',`j')'	"' _n
	}
	file write `f' "
" _n
}
file write `f' "
" _n
file write `f' "" _n
file write `f' "" _n
file close `f'
end


# Make ourselves a very simple templating lib; just two commands
proc TAG {name args} {
    set body [lindex $args end]
    set result "<$name"
    foreach {t v} [lrange $args 0 end-1] {
	append result " $t=\"" $v "\""
    }
    append result ">" [string trim [uplevel 1 [list subst $body]]] "</$name>"
}
proc FOREACH {var lst str} {
    upvar 1 $var v
    set result {}
    set s [list subst $str]
    foreach v $lst {append result [string trim [uplevel 1 $s]]}
    return $result
}

# Build the data we're displaying
set titles {"" "X" "Y" "Z"}
set data {}
for {set x 0} {$x < 4} {incr x} {
    # Inspired by the Go solution, but with extra arbitrary digits to show 4-char wide values
    lappend data [list \
	    [expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]]
}

# Write the table to standard out
puts [TAG table border 1 {
    [TAG tr bgcolor #f0f0f0 {
	[FOREACH head $titles {
	    [TAG th {$head}]
	}]
    }]
    [FOREACH row $data {
	[TAG tr bgcolor #ffffff {
	    [FOREACH col $row {
		[TAG td align right {$col}]
	    }]
	}]
    }]
}]


V input_csv = ‘Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!’

print("
\n
", end' ‘’)

L(c) input_csv
   print(S c {
            "\n"{"
\n
"}
            ‘,’ {‘	’}
            ‘<’ {‘<’}
            ‘>’ {‘>’}
            ‘&’ {‘&’}
            E   {c}
   }, end' ‘’)

print("
\n
")


$$ MODE TUSCRIPT
tablefile="table.html"
ERROR/STOP CREATE (tablefile,FDF-o,-std-)
ACCESS d: WRITE/ERASE/RECORDS/utf8 $tablefile s,tablecontent
tablecontent=*
WRITE d "<!DOCTYPE html system>"
WRITE d "<title>create html table</title>"
WRITE d "

"
WRITE d "
 	x	y	z
"
WRITE d "
"
WRITE d "
"
LOOP n=1,5
x=RANDOM_NUMBERS (1,9999,1)
y=RANDOM_NUMBERS (1,9999,1)
z=RANDOM_NUMBERS (1,9999,1)
WRITE d "
{n}	{x}	{y}	{z}
"
ENDLOOP
WRITE d "

"
ENDACCESS d
BROWSE $tablefile


function emit_table {
    nameref d=$1
    typeset -i idx=0
    echo "
"
    emit_row th "" "${d[idx++][@]}"
    for (( ; idx<${#d[@]}; idx++ )); do
        emit_row td $idx "${d[idx][@]}"
    done
    echo "
"
}

function emit_row {
    typeset tag=$1; shift
    typeset row="
"
    for elem; do
        row+=$(printf "<%s>%s</%s>" "$tag" "$elem" "${tag## *}")
    done
    row+="
"
    echo "$row"
}

function addrow {
    nameref d=$1
    typeset n=${#d[@]}
    typeset -i i
    for ((i=0; i<$2; i++)); do
        d[n][i]=$(( $RANDOM % 10000 ))
    done
}

n=3
typeset -a data
data[0]=("X" "Y" "Z")
for i in {1..4}; do
    addrow data $n
done

emit_table data


with Ada.Strings.Fixed;
with Ada.Text_IO;
with Templates_Parser;

procedure Csv2Html is
   use type Templates_Parser.Vector_Tag;

   Chars : Templates_Parser.Vector_Tag;
   Speeches : Templates_Parser.Vector_Tag;

   CSV_File : Ada.Text_IO.File_Type;
begin
   -- read the csv data
   Ada.Text_IO.Open (File => CSV_File,
                     Mode => Ada.Text_IO.In_File,
                     Name => "data.csv");

   -- fill the tags
   while not Ada.Text_IO.End_Of_File (CSV_File) loop
      declare
         Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File);
         Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, ",");
      begin
         Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1);
         Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last);
      end;
   end loop;

   Ada.Text_IO.Close (CSV_File);

   -- build translation table and output html
   declare
      Translations : constant Templates_Parser.Translate_Table :=
        (1 => Templates_Parser.Assoc ("CHAR", Chars),
         2 => Templates_Parser.Assoc ("SPEECH", Speeches));
   begin
      Ada.Text_IO.Put_Line
        (Templates_Parser.Parse ("table.tmplt", Translations));
   end;
end Csv2Html;


decl ursa.util.random random

out "
" endl console

# generate header
out "
	X	Y	Z
" endl console

# generate five rows
decl int i
for (set i 1) (< i 6) (inc i)
        out "
" i "	" console
        out "" (int (+ 1000 (random.getint 8999))) "	" console
        out "" (int (+ 1000 (random.getint 8999))) "	" console
        out "" (int (+ 1000 (random.getint 8999))) "	" console
        out "
" endl console
end for

out "
" endl console


Public Sub BuildHTMLTable()
'simple HTML table, represented as a string matrix "cells"
Const nRows = 6
Const nCols = 4
Dim cells(1 To nRows, 1 To nCols) As String
Dim HTML As String 'the HTML table
Dim temp As String
Dim attr As String

' fill table
' first row with titles
cells(1, 1) = ""
cells(1, 2) = "X"
cells(1, 3) = "Y"
cells(1, 4) = "Z"
'next rows with index & random numbers
For i = 2 To nRows
  cells(i, 1) = Format$(i - 1)
  For j = 2 To nCols
    cells(i, j) = Format$(Int(Rnd() * 10000))
  Next j
Next i

'build the HTML
HTML = ""
For i = 1 To nRows
  temp = ""
  'first row as header row
  If i = 1 Then attr = "th" Else attr = "td"
  For j = 1 To nCols
    temp = temp & HTMLWrap(cells(i, j), attr)
  Next j
  HTML = HTML & HTMLWrap(temp, "tr")
Next i
HTML = HTMLWrap(HTML, "table", "style=""text-align:center; border: 1px solid""")
Debug.Print HTML
End Sub

Public Function HTMLWrap(s As String, tag As String, ParamArray attributes()) As String
  'returns string s wrapped in HTML tag with optional "attribute=value" strings
  'ex.: HTMLWrap("Link text", "a", "href=""http://www.somesite.org""")
  'returns: Link text

  Dim sOpenTag As String
  Dim sClosingTag As String

  sOpenTag = "<" & tag
  For Each attr In attributes
    sOpenTag = sOpenTag & " " & attr
  Next
  sOpenTag = sOpenTag & ">"
  sClosingTag = "</" & tag & ">"
  HTMLWrap = sOpenTag & s & sClosingTag
End Function


#!/usr/local/bin/a68g --script #

[6]STRING rows := []STRING(
    "Character,Speech",
    "The multitude,The messiah! Show us the messiah!",
    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>",
    "The multitude,Who are you?",
    "Brians mother,I'm his mother; that's who!",
    "The multitude,Behold his mother! Behold his mother!"
);

[max abs char]STRING encoded; FOR i TO UPB encoded DO encoded[i]:=REPR i OD;
# encoded[ABS""""] := """; optional #
  encoded[ABS "&"] := "&";
  encoded[ABS "<"] := "<";
# encoded[ABS ">"] := ">"; optional #

OP ENCODE = (STRING s)STRING: (
  STRING out := "";
  FOR i TO UPB s DO out+:= encoded[ABS s[i]] OD;
  out
);

PROC head = (STRING title)VOID: (
  printf((
    $""l$,
      $"<TITLE>"g"</TITLE>"l$, title,
      $""l$,
    $""l$
  ))
);

# define HTML tags using Algol68's "reverent" block structuring #
PROC html = VOID: print(("", new line)),
       body = VOID: print(("", new line)),
         table = VOID: print(("
", new line)),
           table row = VOID: print(("
")),
             th = (STRING s)VOID: printf(($""g"	"$, s)),
             td = (STRING s)VOID: printf(($""g"	"$, s)),
           elbat row = VOID: print(("
", new line)),
         elbat = VOID: print(("
", new line)),
       ydob = VOID: print(("", new line)),
     lmth = VOID: print(("", new line));

FILE row input; STRING row; CHAR ifs = ",";
associate(row input, row); make term(row input, ifs);

html;
  head("CSV to HTML translation - Extra Credit");
  body;
    table;
      FOR nr TO UPB rows DO
        row := rows[nr];
        table row;
          on logical file end(row input, (REF FILE row input)BOOL: row end);
          FOR nf DO
            STRING field; get(row input,field);
            (nr=1|th|td)(ENCODE field);
            get(row input, space)
          OD;
          row end: reset(row input);
        elbat row
      OD;
    elbat;
  ydob;
lmth


Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the input csv file for reading. The file is in the same folder as the script.
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
	"\in.csv",1)

'Create the output html file.
Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
	"\out.html",2,True)

'Write the html opening tags.
objOutHTML.Write "" & vbCrLf

'Declare table properties.
objOutHTML.Write "
" & vbCrLf

'Write column headers.
objOutHTML.Write "
	X	Y	Z
" & vbCrLf

'Go through each line of the input csv file and write to the html output file.
n = 1
Do Until objInFile.AtEndOfStream
	line = objInFile.ReadLine
	If Len(line) > 0 Then
		token = Split(line,",")
		objOutHTML.Write "
" & n & "	"
		For i = 0 To UBound(token)
			objOutHTML.Write "" & token(i) & "	"
		Next
		objOutHTML.Write "
" & vbCrLf
	End If
	n = n + 1
Loop

'Write the html closing tags.
objOutHTML.Write "
"

objInFile.Close
objOutHTML.Close
Set objFSO = Nothing


Module Program
    Sub Main()
        Const ROWS = 3
        Const COLS = 3

        Dim rand As New Random(0)
        Dim getNumber = Function() rand.Next(10000)

        Dim result =

        X
        Y
        Z

    <%= From c In Enumerable.Range(1, COLS) Select

            <%= c %>
            <%= From r In Enumerable.Range(1, ROWS) Select
                <%= getNumber() %>
            %>

    %>

        Console.WriteLine(result)
    End Sub
End Module


//  Create an HTML Table from comma seperated values
//  Nigel Galloway - June 2nd., 2013
grammar csv2html;
dialog : {System.out.println("
");}header body+{System.out.println("
");} ;
header : {System.out.println("

");}row{System.out.println("
</THEAD");};
body   : {System.out.println("

");}row{System.out.println("
</TBODY");};
row    : field ',' field '\r'? '\n';
field  : Field{System.out.println("" + $Field.text.replace("<","<").replace(">",">") + "	");};
Field  : ~[,\n\r]+;


import "random" for Random
import "/fmt" for Fmt

var r = Random.new()
var sb = ""
var i = "   "  // indent
sb = sb + "\n\n"
sb = sb + "\n\n\n"
sb = sb + "
\n"
sb = sb + "%(i)
\n"
sb = sb + "%(i)%(i)
	"
for (c in "XYZ") sb = sb + "%(c)	"
sb = sb + "
\n"
sb = sb + "%(i)
\n"
sb = sb + "%(i)
\n"
var f = "%(i)%(i)
$d	$d	$d	$d
\n"
for (j in 1..4) sb = sb + Fmt.swrite(f, j, r.int(1e4), r.int(1e4), r.int(1e4))
sb = sb + "%(i)
\n"
sb = sb + "
\n"
sb = sb + "\n"
System.print(sb)


in: {
    Character,Speech
    The multitude,The messiah! Show us the messiah!
    Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitude,Who are you?
    Brians mother,I'm his mother; that's who!
    The multitude,Behold his mother! Behold his mother!
}

table: function [content]
    -> join @["
" join content "
"]

row: function [data]
    -> join @[
        "
" escape.xml first data "	"
        "" escape.xml last data "
"
    ]

print table map read.csv in => row


CSVData =
(
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
)
TableData := "
"
Loop Parse, CSVData,`n
{
   TableData .= "`n
"
   Loop Parse, A_LoopField, CSV
      TableData .= "" HTMLEncode(A_LoopField) "	"
   TableData .= "
"
}
TableData .= "`n
"
HTMLEncode(str){
   static rep := "&<lt;>gt;""quot"
   Loop Parse, rep,;
      StringReplace, str, str, % SubStr(A_LoopField, 1, 1), % "&" . SubStr(A_LoopField, 2) . ";", All
   return str
}
MsgBox % clipboard := TableData


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" version="4.01" indent="yes"/>

    <xsl:param name="column-count" select="3"/>

    <xsl:template match="/">

                <title>Rosetta Code: Create an HTML table (XSLT)</title>

                <xsl:apply-templates/>

        <xsl:variable name="values" select="/*/*"/>
    </xsl:template>

    <xsl:template match="/numbers">

                X
                Y
                Z

            <xsl:apply-templates select="number[position() mod $column-count = 1]"/>

    </xsl:template>

    <xsl:template match="number">

                <xsl:value-of select="position()"/>

            <xsl:for-each select=". | following-sibling::number[position() < $column-count]">

                    <xsl:value-of select="."/>

            </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>


Local $ascarray[4] = [34,38,60,62]
	$String = "Character,Speech" & @CRLF
	$String &= "The multitude,The messiah! Show us the messiah!" & @CRLF
	$String &= "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>" & @CRLF
	$String &= "The multitude,Who are you?" & @CRLF
	$String &= "Brians mother,I'm his mother; that's who!" & @CRLF
	$String &= "The multitude,Behold his mother! Behold his mother!"
	For $i = 0 To UBound($ascarray) -1
		$String = Stringreplace($String, chr($ascarray[$i]), "&#"&$ascarray[$i]&";")
	Next
	$newstring = "
" & @CRLF
	$crlfsplit = StringSplit($String, @CRLF, 1)
	For $i = 1 To $crlfsplit[0]
		If $i = 1 Then $newstring &= "
" & @CRLF
		$newstring &= "
" & @CRLF
		$komsplit = StringSplit($crlfsplit[$i], ",")
		For $k = 1 To $komsplit[0]
			If $i = 1 Then
				$newstring &= "" &$komsplit[$k] & "	" & @CRLF
			Else
				$newstring &= "" &$komsplit[$k] & "	" & @CRLF
			EndIf
		Next
		$newstring &= "
" & @CRLF
		If $i = 1 Then $newstring &= "
" & @CRLF
	Next
	$newstring &= "
"
	ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console


table:=0'|
|
         "	X	Y	Z
";
table=Sink(table);
foreach n in ([1..3]){
   table.write("\n
",n,"	");
   foreach n in (3){ table.write("",(0).random(10000),"	"); }
   table.write("
");
}
table.write("\n
\n").close().print();


#!/usr/bin/awk -f
BEGIN {
        FS=","
        print "
"
}

{
        gsub(/</, "\\<")
        gsub(/>/, "\\>")
        gsub(/&/, "\\>")
        print "\t
"
        for(f = 1; f <= NF; f++)  {
                if(NR == 1 && header) {
                        printf "\t\t%s	\n", $f
                }
                else printf "\t\t%s	\n", $f
        }
        print "\t
"
}

END {
        print "
"
}


::Batch Files are terrifying when it comes to string processing.
::But well, a decent implementation!
@echo off

REM Below is the CSV data to be converted.
REM Exactly three colons must be put before the actual line.

:::Character,Speech
:::The multitude,The messiah! Show us the messiah!
:::Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
:::The multitude,Who are you?
:::Brians mother,I'm his mother; that's who!
:::The multitude,Behold his mother! Behold his mother!

setlocal disabledelayedexpansion
echo ^<table^>
for /f "delims=" %%A in ('findstr "^:::" "%~f0"') do (
   set "var=%%A"
   setlocal enabledelayedexpansion
      REM The next command removes the three colons...
      set "var=!var:~3!"

      REM The following commands to the substitions per line...
      set "var=!var:&=&!"
      set "var=!var:<=<!"
      set "var=!var:>=>!"
      set "var=!var:,=</td><td>!"

      echo ^<tr^>^<td^>!var!^</td^>^</tr^>
   endlocal
)
echo ^</table^>


DATA "Character,Speech"
      DATA "The multitude,The messiah! Show us the messiah!"
      DATA "Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>"
      DATA "The multitude,Who are you?"
      DATA "Brian's mother,I'm his mother; that's who!"
      DATA "The multitude,Behold his mother! Behold his mother!"
      DATA "***"

      *SPOOL CSVtoHTML.htm
      PRINT ""
      PRINT ""
      PRINT ""
      PRINT ""
      PRINT "
"

      header% = TRUE
      REPEAT
        READ csv$
        IF csv$ = "***" THEN EXIT REPEAT

        IF header% PRINT "
"; ELSE PRINT "
";
        FOR i% = 1 TO LEN(csv$)
          c$ = MID$(csv$, i%, 1)
          CASE c$ OF
            WHEN ",": IF header% PRINT "	"; ELSE PRINT "	";
            WHEN "<": PRINT "<";
            WHEN ">": PRINT ">";
            WHEN "&": PRINT "&";
            OTHERWISE: PRINT c$;
          ENDCASE
        NEXT i%
        IF header% PRINT "
" ELSE PRINT "
"

        header% = FALSE
      UNTIL FALSE

      PRINT "
"
      PRINT ""
      PRINT ""
      *spool

      SYS "ShellExecute", @hwnd%, 0, "CSVtoHTML.htm", 0, 0, 1


( ( CSVtoHTML
  =   p q Character Speech swor rows row
    .   0:?p
      & :?swor:?rows
      & ( @( !arg
           :   ?
               ( [!p ?Character "," ?Speech \n [?q ?
               & !q:?p
               &     (tr.,(th.,!Character) (th.,!Speech))
                     !swor
                 : ?swor
               & ~
               )
           )
        |     whl
            ' ( !swor:%?row %?swor
              & !row \n !rows:?rows
              )
          &   toML
            $ (table.,(thead.,!swor) \n (tbody.,!rows))
        )
  )
&   CSVtoHTML
  $ "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
"
)


#include <stdio.h>

const char *input =
	"Character,Speech\n"
	"The multitude,The messiah! Show us the messiah!\n"
	"Brians mother,<angry>Now you listen here! He's not the messiah; "
		"he's a very naughty boy! Now go away!</angry>\n"
	"The multitude,Who are you?\n"
	"Brians mother,I'm his mother; that's who!\n"
	"The multitude,Behold his mother! Behold his mother!";

int main()
{
	const char *s;
	printf("
\n
");
	for (s = input; *s; s++) {
		switch(*s) {
		case '\n': printf("
\n
"); break;
		case ',':  printf("	"); break;
		case '<':  printf("<"); break;
		case '>':  printf(">"); break;
		case '&':  printf("&"); break;
		default:   putchar(*s);
		}
	}
	puts("
\n
");

	return 0;
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

    class Program
    {
        private static string ConvertCsvToHtmlTable(string csvText)
        {
            //split the CSV, assume no commas or line breaks in text
            List<List<string>> splitString = new List<List<string>>();
            List<string> lineSplit = csvText.Split('\n').ToList();
            foreach (string line in lineSplit)
            {
                splitString.Add(line.Split(',').ToList());
            }

            //encode text safely, and create table
            string tableResult = "
";
            foreach(List<string> splitLine in splitString)
            {
                tableResult += "
";
                foreach(string splitText in splitLine)
                {
                    tableResult += "" + WebUtility.HtmlEncode(splitText) + "	";
                }
                tableResult += "
";
            }
            tableResult += "
";
            return tableResult;
        }
    }


#include <string>
#include <boost/regex.hpp>
#include <iostream>

std::string csvToHTML( const std::string & ) ;

int main( ) {
   std::string text = "Character,Speech\n"
                            "The multitude,The messiah! Show us the messiah!\n"
			    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
	                    "The multitude,Who are you?\n"
		            "Brians mother,I'm his mother; that's who!\n"
		            "The multitude,Behold his mother! Behold his mother!\n" ;
  std::cout << csvToHTML( text ) ;
  return 0 ;
}

std::string csvToHTML( const std::string & csvtext ) {
   //the order of the regexes and the replacements is decisive!
   std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
   const char* replacements [ 5 ] = { "<" , ">" , "
$1" , "	", "
\n"  } ;
   boost::regex e1( regexes[ 0 ] ) ;
   std::string tabletext = boost::regex_replace( csvtext , e1 ,
     replacements[ 0 ] , boost::match_default | boost::format_all ) ;
   for ( int i = 1 ; i < 5 ; i++ ) {
      e1.assign( regexes[ i ] ) ;
      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
   }
   tabletext = std::string( "
\n" ) + tabletext ;
   tabletext.append( "
\n" ) ;
   return tabletext ;
}


Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!


String::__defineGetter__ 'escaped', () ->
	this.replace(/&/g, '&')
	    .replace(/</g, '<')
	    .replace(/>/g, '>')
	    .replace(/"/g, '"') // rosettacode doesn't like "

text = '''
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
'''

lines = (line.split ',' for line in text.split /[\n\r]+/g)

header = lines.shift()

console.log """

		#{header[0]}
		#{header[1]}

"""

for line in lines
	[character, speech] = line
	console.log """
		#{character}
		#{speech.escaped}
	"""

console.log """

	"""