(import (scheme base)
        (scheme write)
        (only (srfi 13) string-join string-tokenize))

;; word wrap, using greedy algorithm with minimum lines
(define (simple-word-wrap str width)
  (let loop ((words (string-tokenize str))
             (line-length 0)
             (line '())
             (lines '()))
    (cond ((null? words)
           (reverse (cons (reverse line) lines)))
          ((> (+ line-length (string-length (car words)))
              width)
           (if (null? line)
             (loop (cdr words) ; case where word exceeds line length
                   0
                   '()
                   (cons (list (car words)) lines))
             (loop words ; word must go to next line, so finish current line
                   0
                   '()
                   (cons (reverse line) lines))))
          (else
            (loop (cdr words) ; else, add word to current line
                  (+ 1 line-length (string-length (car words)))
                  (cons (car words) line)
                  lines)))))

;; run examples - text from RnRS report
(define *text* "Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible enough to support most of the major programming paradigms in use today.")

(define (show-para algorithm width)
  (display (make-string width #\-)) (newline)
  (for-each (lambda (line) (display (string-join line " ")) (newline))
            (algorithm *text* width)))

(show-para simple-word-wrap 50)
(show-para simple-word-wrap 60)


$ include "seed7_05.s7i";

const func string: wrap (in string: aText, in integer: lineWidth) is func
  result
    var string: wrapped is "";
  local
    var array string: words is 0 times "";
    var string: word is "";
    var integer: spaceLeft is 0;
  begin
    words := split(aText, " ");
    if length(words) <> 0 then
      wrapped := words[1];
      words := words[2 ..];
      spaceLeft := lineWidth - length(wrapped);
      for word range words do
        if length(word) + 1 > spaceLeft then
          wrapped &:= "\n" & word;
          spaceLeft := lineWidth - length(word);
        else
          wrapped &:= " " & word;
          spaceLeft -:= 1 + length(word);
        end if;
      end for;
    end if;
  end func;

const proc: main is func
  local
    const string: frog is "In olden times when wishing still helped one, there lived \
        \a king whose daughters were all beautiful, but the youngest was so beautiful \
        \that the sun itself, which has seen so much, was astonished whenever it \
        \shone in her face. Close by the king's castle lay a great dark forest, and \
        \under an old lime-tree in the forest was a well, and when the day was very \
        \warm, the king's child went out into the forest and sat down by the side of \
        \the cool fountain, and when she was bored she took a golden ball, and threw \
        \it up on high and caught it, and this ball was her favorite plaything.";
    var integer: width is 0;
  begin
    for width range [] (72, 80) do
      writeln("Wrapped at " <& width <& ":");
      writeln(wrap(frog, width));
    end for;
  end func;


 #Include "file.bi"
 type tally
      as string s
      as long l
end type

Sub quicksort(array() As String,begin As Long,Finish As Long)
 Dim As Long i=begin,j=finish
 Dim As String x =array(((I+J)\2))
 While I <= J
 While array(I) < X :I+=1:Wend
 While array(J) > X :J-=1:Wend
 If I<=J Then Swap array(I),array(J): I+=1:J-=1
 Wend
 If J >begin Then quicksort(array(),begin,J)
 If I <Finish Then quicksort(array(),I,Finish)
End Sub

Sub tallysort(array() As tally,begin As Long,Finish As long)
 Dim As Long i=begin,j=finish
 Dim As tally x =array(((I+J)\2))
 While I <= J
 While array(I).l > X .l:I+=1:Wend
 While array(J).l < X .l:J-=1:Wend
 If I<=J Then Swap array(I),array(J): I+=1:J-=1
 Wend
 If J >begin Then tallysort(array(),begin,J)
 If I <Finish Then tallysort(array(),I,Finish)
 End Sub

Function loadfile(file As String) As String
	If Fileexists(file)=0 Then Print file;" not found":Sleep:End
   Dim As Long  f=Freefile
    Open file For Binary Access Read As #f
    Dim As String text
    If Lof(f) > 0 Then
      text = String(Lof(f), 0)
      Get #f, , text
    End If
    Close #f
    Return text
End Function

Function String_Split(s_in As String,chars As String,result() As String) As Long
    Dim As Long ctr,ctr2,k,n,LC=Len(chars)
    Dim As boolean tally(Len(s_in))
    #macro check_instring()
    n=0
    While n<Lc
        If chars[n]=s_in[k] Then
            tally(k)=true
            If (ctr2-1) Then ctr+=1
            ctr2=0
            Exit While
        End If
        n+=1
    Wend
    #endmacro

    #macro splice()
    If tally(k) Then
        If (ctr2-1) Then ctr+=1:result(ctr)=Mid(s_in,k+2-ctr2,ctr2-1)
        ctr2=0
    End If
    #endmacro
    '==================  LOOP TWICE =======================
    For k  =0 To Len(s_in)-1
        ctr2+=1:check_instring()
    Next k
     If ctr=0 Then
         If Len(s_in) Andalso Instr(chars,Chr(s_in[0])) Then ctr=1':
         End If
    If ctr Then Redim result(1 To ctr): ctr=0:ctr2=0 Else  Return 0
    For k  =0 To Len(s_in)-1
        ctr2+=1:splice()
    Next k
    '===================== Last one ========================
    If ctr2>0 Then
        Redim Preserve result(1 To ctr+1)
        result(ctr+1)=Mid(s_in,k+1-ctr2,ctr2)
    End If

    Return Ubound(result)
End Function

Redim As String s()
redim as tally t()
dim as string p1,p2,deliminators
dim as long count,jmp
dim as double tm=timer

Var L=loadfile("rosettalesmiserables.txt")
L=lcase(L)
'get deliminators
for n as long=1 to 96
      p1+=chr(n)
next
for n as long=123 to 255
    p2+=chr(n)
next

deliminators=p1+p2

string_split(L,deliminators,s())

quicksort(s(),lbound(s),ubound(s))

For n As Long=lbound(s)  To ubound(s)-1
      if s(n+1)=s(n) then jmp+=1
      if s(n+1)<>s(n) then
            count+=1
            redim preserve t(1 to count)
            t(count).s=s(n)
            t(count).l=jmp
            jmp=0
            end if
Next

tallysort(t(),lbound(t),ubound(t))'sort by frequency
print "frequency","word"
print
for n as long=lbound(t) to lbound(t)+9
      print t(n).l,t(n).s
      next

Print
print "time for operation  ";timer-tm;" seconds"
sleep


class String {
    method wrap(width) {
        var txt = self.gsub(/\s+/, " ");
        var len = txt.len;
        var para = [];
        var i = 0;
        while (i < len) {
            var j = (i + width);
            while ((j < len) && (txt.char_at(j) != ' ')) { --j };
            para.append(txt.substr(i, j-i));
            i = j+1;
        };
        return para.join("\n");
    }
}

var text = 'aaa bb cc ddddd';
say text.wrap(6);


fun wordWrap n s =
  let
    fun appendLine (line, text) =
      text ^ line ^ "\n"
    fun wrap (word, prev as (line, text)) =
      if size line + 1 + size word > n
      then (word, appendLine prev)
      else (line ^ " " ^ word, text)
  in
    case String.tokens Char.isSpace s of
      [] => ""
    | (w :: ws) => appendLine (foldl wrap (w, "") ws)
  end

val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn


d = new dict
for w = select[wordList[read[normalizeUnicode["https://www.gutenberg.org/files/135/135-0.txt", "UTF-8"]]], %r/[[:alnum:]]/ ]
   d.increment[lc[w], 1]

println[join["\n", first[reverse[sort[array[d], {|a,b| [email protected] <=> [email protected]}]], 10]]]


include "NSLog.incl"

local fn WordFrequency( textStr as CFStringRef, caseSensitive as Boolean, ascendingOrder as Boolean ) as CFStringRef
'~'1
CFStringRef     wrd
CFDictionaryRef dict

// Depending on the value of the caseSensitive Boolean function parameter above, lowercase incoming text
if caseSensitive == NO then textStr = fn StringLowercaseString( textStr )

// Trim non-alphabetic characters from string, and separate individual words with a space
CFStringRef tempStr = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( textStr, fn CharacterSetInvertedSet( fn CharacterSetLetterSet ) ), @" " )

// Prepare separators to parse string into array
CFMutableCharacterSetRef separators = fn MutableCharacterSetInit

// Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on.
MutableCharacterSetFormUnionWithCharacterSet( separators, fn CharacterSetPunctuationSet )

// A character set containing all the whitespace and newline characters including characters in Unicode General Category Z*, U+000A U+000D, and U+0085.
MutableCharacterSetFormUnionWithCharacterSet( separators, fn CharacterSetWhitespaceAndNewlineSet )

// Create array of separated words
CFArrayRef tempArr = fn StringComponentsSeparatedByCharactersInSet( tempStr, separators )

// Create a counted set with each word and its frequency
CountedSetRef freqencies = fn CountedSetWithArray( tempArr )

// Enumerate each word-frequency pair in the counted set...
EnumeratorRef enumRef = fn CountedSetObjectEnumerator( freqencies )

// .. and use it to create array of words in counted set
CFArrayRef array = fn EnumeratorAllObjects( enumRef )

// Create an empty mutable array
CFMutableArrayRef wordArr = fn MutableArrayWithCapacity( 0 )

// Create word counter
NSInteger totalWords = 0
// Enumerate each unique word, get its frequency, create its own key/value pair dictionary, add each dictionary into master array
for wrd in array
totalWords++
// Create dictionary with frequency and matching word
dict = @{ @"count":fn NumberWithUnsignedInteger( fn CountedSetCountForObject( freqencies, wrd ) ), @"object":wrd }
// Add each dictionary to the master mutable array, checking for a valid word by length
if ( fn StringLength( wrd ) != 0 )
MutableArrayAddObject( wordArr, dict )
end if
next

// Store the total words as a global application property
AppSetProperty( @"totalWords", fn StringWithFormat( @"%d", totalWords - 1 ) )

// Sort the array in ascending or descending order as determined by the ascendingOrder Boolean function input parameter
SortDescriptorRef descriptors = fn SortDescriptorWithKey( @"count", ascendingOrder )
CFArrayRef sortedArray = fn ArraySortedArrayUsingDescriptors( wordArr, @[descriptors] )

// Create an empty mutable string
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )

// Use each dictionary in sorted array to build the formatted output string
NSInteger count = 1
for dict in sortedArray
MutableStringAppendString( mutStr, fn StringWithFormat( @"%-7d %-7lu %@\n", count, fn StringIntegerValue( fn DictionaryValueForKey( dict, @"count" ) ), fn DictionaryValueForKey( dict, @"object"  ) ) )
count++
next

// Create an immutable output string from mutable the string
CFStringRef resultStr = fn StringWithFormat( @"%@", mutStr )
end fn = resultStr

local fn ParseTextFromWebsite( webSite as CFStringRef )
// Convert incoming string to URL
CFURLRef textURL = fn URLWithString( webSite )
// Read contents of URL into a string
CFStringRef textStr = fn StringWithContentsOfURL( textURL, NSUTF8StringEncoding, NULL )

// Start timer
CFAbsoluteTime startTime = fn CFAbsoluteTimeGetCurrent
// Calculate frequency of words in text and sort by occurrence
CFStringRef frequencyStr = fn WordFrequency( textStr, NO, NO )
// Log results and post post processing time
NSLogClear
NSLog( @"%@", frequencyStr )
NSLog( @"Total unique words in document: %@", fn AppProperty( @"totalWords" ) )
// Stop timer and log elapsed processing time
NSLog( @"Elapsed time: %f milliseconds.", ( fn CFAbsoluteTimeGetCurrent - startTime ) * 1000.0 )
end fn

dispatchglobal
// Pass url for Les Misérables on Project Gutenberg and parse in background
fn ParseTextFromWebsite( @"https://www.gutenberg.org/files/135/135-0.txt" )
dispatchend

HandleEvents


package require Tcl 8.5

proc wrapParagraph {n text} {
    regsub -all {\s+} [string trim $text] " " text
    set RE "^(.{1,$n})(?:\\s+(.*))?$"
    for {set result ""} {[regexp $RE $text -> line text]} {} {
    append result $line "\n"
    }
    return [string trimright $result "\n"]
}

set txt \
"In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face.  Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything."

puts "[string repeat - 80]"
puts [wrapParagraph 80 $txt]
puts "[string repeat - 72]"
puts [wrapParagraph 72 $txt]


The kings youngest daughter was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face.


$$ MODE TUSCRIPT
text="In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face.  Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything."

ERROR/STOP CREATE ("text",seq-E,-std-)

length=80
line=REPEAT ("-",length)
FILE "text" = line
firstline=nextlines=""
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext

length=72
line=REPEAT ("-",length)
FILE "text" = line
firstline=CONCAT ("Length ",length,": ")
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext


with Gtk.Window;  use Gtk.Window;
with Gtk.Widget;  use Gtk.Widget;

with Gtk.Handlers;
with Gtk.Main;

procedure Windowed_Application is
   Window : Gtk_Window;

   package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
   package Return_Handlers is
      new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);

   function Delete_Event (Widget : access Gtk_Widget_Record'Class)
      return Boolean is
   begin
      return False;
   end Delete_Event;

   procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
   begin
     Gtk.Main.Main_Quit;
   end Destroy;

begin
   Gtk.Main.Init;
   Gtk.Window.Gtk_New (Window);
   Return_Handlers.Connect
   (  Window,
      "delete_event",
      Return_Handlers.To_Marshaller (Delete_Event'Access)
   );
   Handlers.Connect
   (  Window,
      "destroy",
      Handlers.To_Marshaller (Destroy'Access)
   );
   Show (Window);

   Gtk.Main.Main;
end Windowed_Application;


package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "regexp"
    "sort"
    "strings"
)

type keyval struct {
    key string
    val int
}

func main() {
    reg := regexp.MustCompile(`\p{Ll}+`)
    bs, err := ioutil.ReadFile("135-0.txt")
    if err != nil {
        log.Fatal(err)
    }
    text := strings.ToLower(string(bs))
    matches := reg.FindAllString(text, -1)
    groups := make(map[string]int)
    for _, match := range matches {
        groups[match]++
    }
    var keyvals []keyval
    for k, v := range groups {
        keyvals = append(keyvals, keyval{k, v})
    }
    sort.Slice(keyvals, func(i, j int) bool {
        return keyvals[i].val > keyvals[j].val
    })
    fmt.Println("Rank  Word  Frequency")
    fmt.Println("====  ====  =========")
    for rank := 1; rank <= 10; rank++ {
        word := keyvals[rank-1].key
        freq := keyvals[rank-1].val
        fmt.Printf("%2d    %-4s    %5d\n", rank, word, freq)
    }
}


column = 60
text = "In olden times when wishing still helped one, there lived a king " &_
    "whose daughters were all beautiful, but the youngest was so beautiful "&_
    "that the sun itself, which has seen so much, was astonished whenever "&_
    "it shone-in-her-face.  Close-by-the-king's castle lay a great dark "&_
    "forest, and under an old lime-tree in the forest was a well, and when "&_
    "the day was very warm, the king's child went out into the forest and "&_
    "sat down by the side of the cool-fountain, and when she was bored she "&_
    "took a golden ball, and threw it up on high and caught it, and this "&_
    "ball was her favorite plaything."

Call wordwrap(text,column)

Sub wordwrap(s,n)
    word = Split(s," ")
    row = ""
    For i = 0 To UBound(word)
        If Len(row) = 0 Then
            row = row & word(i)
        ElseIf Len(row & " " & word(i)) <= n Then
            row = row & " " & word(i)
        Else
            WScript.StdOut.WriteLine row
            row = word(i)
        End If
    Next
    If Len(row) > 0 Then
        WScript.StdOut.WriteLine row
    End If
End Sub


fn wrap(text string, line_width int) string {
    mut wrapped := ''
    words := text.fields()
    if words.len == 0 {
        return wrapped
    }
    wrapped = words[0]
    mut space_left := line_width - wrapped.len
    for word in words[1..] {
        if word.len+1 > space_left {
            wrapped += "\n" + word
            space_left = line_width - word.len
        } else {
            wrapped += " " + word
            space_left -= 1 + word.len
        }
    }
    return wrapped
}

const frog = "
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face.  Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything."

fn main() {
    println("wrapped at 80:")
    println(wrap(frog, 80))
    println("wrapped at 72:")
    println(wrap(frog, 72))
}


PROGRAM firstgtk CONTEXT VOID
USE standard
BEGIN
MODE GDATA = REF BITS;
MODE GUINT = BITS;
MODE GSIZE = BITS;
MODE GTYPE = GSIZE;
MODE GTYPECLASS = STRUCT(GTYPE g type);
MODE GTYPEINSTANCE = STRUCT(REF GTYPECLASS g class);
MODE GTKWIDGETPRIVATE = REF BITS;

MODE GOBJECT = STRUCT(
                GTYPEINSTANCE g type instance,
                GUINT ref count,
                REF GDATA qdata);

MODE GTKWIDGET = STRUCT(
                GOBJECT parent instance,
      REF GTKWIDGETPRIVATE priv);

PROC(REF INT,REF CCHARPTRPTR)VOID gtk init = ALIEN "GTK_INIT"
        "#define GTK_INIT(argc,argv) gtk_init(argc,argv)";
PROC(INT)REF GTKWIDGET gtk window new = ALIEN "GTK_WINDOW_NEW"
        "#define GTK_WINDOW_NEW(type) (void *)gtk_window_new(type)";
PROC(REF GTKWIDGET)VOID gtk widget show = ALIEN "GTK_WIDGET_SHOW"
        "#define GTK_WIDGET_SHOW(widget) gtk_widget_show((void *)widget)";
PROC gtk main = VOID: CODE "gtk_main();";

INT gtk window toplevel = 0;
FILE argf;
REF GTKWIDGET window;

open(argf,"",arg channel);
gtk init(argc,argv);
window:=gtk window new(gtk window toplevel);
gtk widget show(window);
gtk main
END
FINISH


def topWordCounts = { String content, int n ->
    def mapCounts = [:]
    content.toLowerCase().split(/\W+/).each {
        mapCounts[it] = (mapCounts[it] ?: 0) + 1
    }
    def top = (mapCounts.sort { a, b -> b.value <=> a.value }.collect{ it })[0..<n]
    println "Rank Word Frequency\n==== ==== ========="
    (0..<n).each { printf ("%4d %-4s %9d\n", it+1, top[it].key, top[it].value) }
}


module Main where

import Control.Category   -- (>>>)
import Data.Char          -- toLower, isSpace
import Data.List          -- sortBy, (Foldable(foldl')), filter -- '
import Data.Ord           -- Down
import System.IO          -- stdin, ReadMode, openFile, hClose
import System.Environment -- getArgs

-- containers
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.IntMap.Strict as IM

-- text
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T

frequencies :: Ord a => [a] -> Map a Integer
frequencies = foldl' (\m k -> M.insertWith (+) k 1 m) M.empty -- '
{-# SPECIALIZE frequencies :: [Text] -> Map Text Integer #-}

main :: IO ()
main = do
  args <- getArgs
  (n,hand,filep) <- case length args of
    0 -> return (10,stdin,False)
    1 -> return (read $ head args,stdin,False)
    _ -> let (ns:fp:_) = args
         in fmap (\h -> (read ns,h,True)) (openFile fp ReadMode)
  T.hGetContents hand >>=
    (T.map toLower
      >>> T.split isSpace
      >>> filter (not <<< T.null)
      >>> frequencies
      >>> M.toList
      >>> sortBy (comparing (Down <<< snd)) -- sort the opposite way
      >>> take n
      >>> print)
  when filep (hClose hand)


var greedyWordWrap = Fn.new { |text, lineWidth|
    var words = text.split(" ")
    var sb = words[0]
    var spaceLeft = lineWidth - words[0].count
    for (word in words.skip(1)) {
        var len = word.count
        if (len + 1 > spaceLeft) {
            sb = sb + "\n" + word
            spaceLeft = lineWidth - len
        } else {
            sb = sb + " " + word
            spaceLeft = spaceLeft - len - 1
        }
    }
    return sb
}

var text =
    "In olden times when wishing still helped one, there lived a king " +
    "whose daughters were all beautiful, but the youngest was so beautiful " +
    "that the sun itself, which has seen so much, was astonished whenever " +
    "it shone in her face.  Close by the king's castle lay a great dark " +
    "forest, and under an old lime tree in the forest was a well, and when " +
    "the day was very warm, the king's child went out into the forest and " +
    "sat down by the side of the cool fountain, and when she was bored she " +
    "took a golden ball, and threw it up on high and caught it, and this " +
    "ball was her favorite plaything."

System.print("Greedy algorithm - wrapped at 72:")
System.print(greedyWordWrap.call(text, 72))
System.print("\nGreedy algorithm - wrapped at 80:")
System.print(greedyWordWrap.call(text, 80))


t$ = "In olden times when wishing still helped one, there lived a king "
t$ = t$ + "whose daughters were all beautiful, but the youngest was so beautiful "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
t$ = t$ + "it shone in her face.\n\n"
t$ = t$ + t$

t$ = trim$(t$)

input "Width: " width // user specifies width

dim p$(1)

d$ = " .,\n"

n = words(t$, p$(), d$)

for i = 1 to n
  if p$(i) = "\n" or len(docOut$) + len(p$(i)) > width then
    print docOut$
    docOut$ = ""
  end if
  if p$(i) <> "\n" docOut$ = docOut$ + p$(i)
next i
print docOut$

sub words(w$, p$(), d$)
    local n, i, p

    n = split(w$, p$(), d$)
    p = 1

    for i = 1 to n
        p$(i) = p$(i) + mid$(w$, p + len(p$(i)), 1)
        p = p + len(p$(i))
    next i
    return n
end sub


GUICreate("Test")
GUISetState(@SW_SHOW)

Do
	Switch GUIGetMsg()
		Case -3 ; $GUI_EVENT_CLOSE
			Exit
	EndSwitch
Until False


REM empty window
INCLUDE "hug.bac"

mainwin = WINDOW("Rosetta Code empty", 400, 300)

REM start gtk event loop...
DISPLAY


clg
text (50,50, "I write in the graphics area")


      INSTALL @lib$+"WINLIB2"
      dlg% = FN_newdialog("GUI Window", 0, 0, 200, 150, 8, 1000)
      PROC_showdialog(dlg%)


   10{.\:~(#;{.)/.~;:tolower((e.&(a.-.Alpha_j_,' '))`(,:&' '))}1!:1<jpath'~/downloads/books/LesMis.txt'
┌─────┬────┐
│41093│the │
├─────┼────┤
│19954│of  │
├─────┼────┤
│14943│and │
├─────┼────┤
│14558│a   │
├─────┼────┤
│13953│to  │
├─────┼────┤
│11219│in  │
├─────┼────┤
│9649 │he  │
├─────┼────┤
│8622 │was │
├─────┼────┤
│7924 │that│
├─────┼────┤
│6661 │it  │
└─────┴────┘


fcn formatText(text,   // text can be String,Data,File, -->Data
       length=72, calcIndents=True){
   sink:=Data();
   getIndents:='wrap(w){    // look at first two lines to indent paragraph
      reg lines=L(), len=0, prefix="", one=True;
      do(2){
     if(w._next()){
        lines.append(line:=w.value);
        word:=line.split(Void,1)[0,1]; // get first word, if line !blank
        if(word){
           p:=line[0,line.find(word[0]]);
           if(one){ sink.write(p); len=p.len(); one=False; }
           else prefix=p;
        }
     }
      }
      w.push(lines.xplode());  // put first two lines back to be formated
      return(len,prefix);
   };

   reg len=0, prefix="", w=text.walker(1);  // lines
   if(calcIndents) len,prefix=getIndents(w);
   foreach line in (w){
      if(not line.strip()){ // blank line
     sink.write("\n",line); // blank line redux
     if(calcIndents) len,prefix=getIndents(w);
     else len=0;  // restart formating
      }else
     len=line.split().reduce('wrap(len,word){
        n:=word.len();
        if(len==0) { sink.write(word); return(n); }
        nn:=n+1+len; if(nn<=length) { sink.write(" ",word); return(nn); }
        sink.write("\n",prefix,word); return(prefix.len()+word.len());
     },len);
   }
   sink
}


/*
 *   Opens an 800x600 16bit color window.
 *   Done here with ANSI C.
 */

#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"

int main()
{
  SDL_Surface *screen;

  if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
    return 1;
  }
  atexit(SDL_Quit);
  screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );

  return 0;
}


using System;
using System.Windows.Forms;

public class Window {
    [STAThread]
    static void Main() {
        Form form = new Form();

        form.Text = "Window";
        form.Disposed += delegate { Application.Exit(); };

        form.Show();
        Application.Run();
    }
}


#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
 QApplication app(argc, argv);
 QMainWindow window;
 window.show();
 return app.exec();
}


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class WordCount {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("135-0.txt");
        byte[] bytes = Files.readAllBytes(path);
        String text = new String(bytes);
        text = text.toLowerCase();

        Pattern r = Pattern.compile("\\p{javaLowerCase}+");
        Matcher matcher = r.matcher(text);
        Map<String, Integer> freq = new HashMap<>();
        while (matcher.find()) {
            String word = matcher.group();
            Integer current = freq.getOrDefault(word, 0);
            freq.put(word, current + 1);
        }

        List<Map.Entry<String, Integer>> entries = freq.entrySet()
            .stream()
            .sorted((i1, i2) -> Integer.compare(i2.getValue(), i1.getValue()))
            .limit(10)
            .collect(Collectors.toList());

        System.out.println("Rank  Word  Frequency");
        System.out.println("====  ====  =========");
        int rank = 1;
        for (Map.Entry<String, Integer> entry : entries) {
            String word = entry.getKey();
            Integer count = entry.getValue();
            System.out.printf("%2d    %-4s    %5d\n", rank++, word, count);
        }
    }
}


(import '(javax.swing JFrame))

(let [frame (JFrame. "A Window")]
	   (doto frame
		 (.setSize 600 800)
		 (.setVisible true)))


(capi:display (make-instance 'capi:interface :title "A Window"))


 module Window;

 import fltk4d.all;

 void main() {
     auto window = new Window(300, 300, "A window");
     window.show;
     FLTK.run;
 }


// The project file (Project1.dpr)
program Project1;

uses
  Forms,
  // Include file with Window class declaration (see below)
  Unit0 in 'Unit1.pas' {Form1};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

// The Window class declaration
unit Unit1;

interface

uses
  Forms;

type
  TForm1 = class(TForm)
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm} // The window definition resource (see below)

end.

// A textual rendition of the Window (form) definition file (Unit1.dfm)
object Form1: TForm1
  Left = 469
  Top = 142
  Width = 800
  Height = 600
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Shell Dlg 2'
  Font.Style = []
  OldCreateOrder = False
  Position = poScreenCenter
  PixelsPerInch = 96
  TextHeight = 13
end


< 135-0.txt jq -nR --argjson n 10 '
def bow(stream):
  reduce stream as $word ({}; .[($word|tostring)] += 1);

bow(inputs | gsub("[^-a-zA-Z]"; " ") | splits("  *") | ascii_downcase | select(test("^[a-z][-a-z]*$")))
| to_entries
| sort_by(.value)
| .[- $n :]
| reverse
| from_entries
'


using FreqTables

txt = read("les-mis.txt", String)
words = split(replace(txt, r"\P{L}"i => " "))
table = sort(freqtable(words); rev=true)
println(table[1:10])


∇ stats (file) {
	content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file
	sorted ← (⍋⊇⊢) content
	selection ← 1,2≢/sorted
	words ← selection / sorted
	{⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection
}


// version 1.1.3

import java.io.File

fun main(args: Array<String>) {
    val text = File("135-0.txt").readText().toLowerCase()
    val r = Regex("""\p{javaLowerCase}+""")
    val matches = r.findAll(text)
    val wordGroups = matches.map { it.value }
                    .groupBy { it }
                    .map { Pair(it.key, it.value.size) }
                    .sortedByDescending { it.second }
                    .take(10)
    println("Rank  Word  Frequency")
    println("====  ====  =========")
    var rank = 1
    for ((word, freq) in wordGroups)
        System.out.printf("%2d    %-4s    %5d\n", rank++, word, freq)
}


select "GUI"

window = newWindow("Window")
window.setSize(400,600)
window.setVisible()


when (currentVat.morphInto("awt")) -> {
    def w := <swing:makeJFrame>("Window")
    w.setContentPane(<swing:makeJLabel>("Contents"))
    w.pack()
    w.show()
}


class
    APPLICATION
inherit
    EV_APPLICATION
create
    make_and_launch
feature {NONE} -- Initialization
    make_and_launch
            -- Initialize and launch application
        do
            default_create
            create first_window
            first_window.show
            launch
        end
feature {NONE} -- Implementation
    first_window: MAIN_WINDOW
            -- Main window.
end


include arwen.ew

constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0})

WinMain(win, SW_NORMAL)


dim words$(100000,2)'words$(a,1)=the word, words$(a,2)=the count
dim lines$(150000)
open "135-0.txt" for input as #txt
while EOF(#txt)=0 and total < 150000
    input #txt, lines$(total)
    total=total+1
wend
for a = 1 to total
    token$ = "?"
    index=0
    new=0
    while token$ <> ""
        new=0
        index = index + 1
        token$ = lower$(word$(lines$(a),index))
        token$=replstr$(token$,".","")
        token$=replstr$(token$,",","")
        token$=replstr$(token$,";","")
        token$=replstr$(token$,"!","")
        token$=replstr$(token$,"?","")
        token$=replstr$(token$,"-","")
        token$=replstr$(token$,"_","")
        token$=replstr$(token$,"~","")
        token$=replstr$(token$,"+","")
        token$=replstr$(token$,"0","")
        token$=replstr$(token$,"1","")
        token$=replstr$(token$,"2","")
        token$=replstr$(token$,"3","")
        token$=replstr$(token$,"4","")
        token$=replstr$(token$,"5","")
        token$=replstr$(token$,"6","")
        token$=replstr$(token$,"7","")
        token$=replstr$(token$,"8","")
        token$=replstr$(token$,"9","")
        token$=replstr$(token$,"/","")
        token$=replstr$(token$,"<","")
        token$=replstr$(token$,">","")
        token$=replstr$(token$,":","")
        for b = 1 to newwordcount
            if words$(b,1)=token$ then
                num=val(words$(b,2))+1
                num$=str$(num)
                if len(num$)=1 then num$="0000"+num$
                if len(num$)=2 then num$="000"+num$
                if len(num$)=3 then num$="00"+num$
                if len(num$)=4 then num$="0"+num$
                words$(b,2)=num$
                new=1
                exit for
            end if
        next b
        if new<>1 then newwordcount=newwordcount+1:words$(newwordcount,1)=token$:words$(newwordcount,2)="00001":print newwordcount;" ";token$
    wend
next a
print
sort words$(), 1, newwordcount, 2
print "Count Word"
print "===== ================="
for a = newwordcount to newwordcount-10 step -1
    print words$(a,2);" ";words$(a,1)
next a
print "-----------------------"
print newwordcount;" unique words found."
print "End of program"
close #txt
end


 open System.Windows.Forms

 [<System.STAThread>]
 do
     Form(Text = "F# Window")
     |> Application.Run


USING: ui ui.gadgets.labels ;

"This is a window..." <label> "Really?" open-window


using fwt

class Main
{
  public static Void main ()
  {
    Window().open
  }
}


include ffl/gsv.fs

\ Open the connection to the gtk-server and load the Gtk2 definitions
s" gtk-server.cfg" s" ffl-fifo" gsv+open 0= [IF]

\ Convert the string event to a widget id
: event>widget
  0. 2swap >number 2drop d>s
;

0 value window

: window-creation
  gtk_init

  \ Create the window
  GTK_WINDOW_TOPLEVEL gtk_window_new to window

  window gtk_widget_show

  \ Wait for an event
  BEGIN
    s" WAIT" gtk_server_callback
    event>widget window =
  UNTIL

  0 gtk_exit
;

window-creation

gsv+close drop
[THEN]


#Include "windows.bi"

Dim As HWND Window_Main
Dim As MSG msg

'Create the window:
Window_Main = CreateWindow("#32770", "I am a window - close me!", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)

'Windows message loop:
While GetMessage(@msg, Window_Main, 0, 0)
  TranslateMessage(@msg)
  DispatchMessage(@msg)
  If msg.hwnd = Window_Main And msg.message = WM_COMMAND Then End
Wend

End


-- This program takes two optional command line arguments.  The first (arg[1])
-- specifies the input file, or defaults to standard input.  The second
-- (arg[2]) specifies the number of results to show, or defaults to 10.

-- in freq, each key is a word and each value is its count
local freq = {}
for line in io.lines(arg[1]) do
	-- %a stands for any letter
	for word in string.gmatch(string.lower(line), "%a+") do
		if not freq[word] then
			freq[word] = 1
		else
			freq[word] = freq[word] + 1
		end
	end
end

-- in array, each entry is an array whose first value is the count and whose
-- second value is the word
local array = {}
for word, count in pairs(freq) do
	table.insert(array, {count, word})
end
table.sort(array, function (a, b) return a[1] > b[1] end)

for i = 1, arg[2] or 10 do
	io.write(string.format('%7d %s\n', array[i][1] , array[i][2]))
end


package main

import (
    "github.com/mattn/go-gtk/glib"
    "github.com/mattn/go-gtk/gtk"
)

func main() {
    gtk.Init(nil)
    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
    window.Connect("destroy",
        func(*glib.CallbackContext) { gtk.MainQuit() }, "")
    window.Show()
    gtk.Main()
}


 import groovy.swing.SwingBuilder

 new SwingBuilder().frame(title:'My Window', size:[200,100]).show()


function [result,count] = word_frequency()
URL='https://www.gutenberg.org/files/135/135-0.txt';
text=webread(URL);
DELIMITER={' ', ',', ';', ':', '.', '/', '*', '!', '?', '<', '>', '(', ')', '[', ']','{', '}', '&','$','§','"','”','“','-','—','‘','\t','\n','\r'};
words  = sort(strsplit(lower(text),DELIMITER));
flag   = [find(~strcmp(words(1:end-1),words(2:end))),length(words)];
dwords = words(flag);   % get distinct words, and ...
count  = diff([0,flag]);  % ... the corresponding occurance frequency
[tmp,idx] = sort(-count);       % sort according to occurance
result = dwords(idx);
count  = count(idx);
for k  =  1:10,
        fprintf(1,'%d\t%s\n',count(k),result{k})
end


import tables, strutils, sequtils, httpclient

proc take[T](s: openArray[T], n: int): seq[T] = s[0 ..< min(n, s.len)]

var client = newHttpClient()
var text = client.getContent("https://www.gutenberg.org/files/135/135-0.txt")

var wordFrequencies = text.toLowerAscii.splitWhitespace.toCountTable
wordFrequencies.sort
for (word, count) in toSeq(wordFrequencies.pairs).take(10):
  echo alignLeft($count, 8), word


import Graphics.HGL

aWindow =  runGraphics $
  withWindow_ "Rosetta Code task: Creating a window" (300, 200) $ \ w -> do
	drawInWindow w $ text (100, 100) "Hello World"
	getKey w


WINDOW(WINdowhandle=handle, Width=80, Height=-400, X=1, Y=1/2, TItle="Rosetta Window_creation Example")
! window units: as pixels < 0,  as relative window size 0...1,  ascurrent character sizes > 1

WRITE(WINdowhandle=handle) '... some output ...'


Id = WIDGET_BASE(TITLE='Window Title',xsize=200,ysize=100)
WIDGET_CONTROL, /REALIZE, id


link graphics

procedure main(arglist)

WOpen("size=300, 300", "fg=blue", "bg=light gray")
WDone()
end


use System.IO.File;
use Collection;
use RegEx;

class Rosetta {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() <> 1) {
      return;
    };

    input := FileReader->ReadFile(args[0]);
    filter := RegEx->New("\\w+");
    words := filter->Find(input);

    word_counts := StringMap->New();
    each(i : words) {
      word := words->Get(i)->As(String);
      if(word <> Nil & word->Size() > 0) {
        word := word->ToLower();
        if(word_counts->Has(word)) {
          count := word_counts->Find(word)->As(IntHolder);
          count->Set(count->Get() + 1);
        }
        else {
          word_counts->Insert(word, IntHolder->New(1));
        };
      };
    };

    count_words := IntMap->New();
    words := word_counts->GetKeys();
    each(i : words) {
      word := words->Get(i)->As(String);
      count := word_counts->Find(word)->As(IntHolder);
      count_words->Insert(count->Get(), word);
    };

    counts := count_words->GetKeys();
    counts->Sort();

    index := 1;
    "Rank\tWord\tFrequency"->PrintLine();
    "====\t====\t===="->PrintLine();
    for(i := count_words->Size() - 1; i >= 0; i -= 1;) {
      if(count_words->Size() - 10 <= i) {
        count := counts->Get(i);
        word := count_words->Find(count)->As(String);
        "{$index}\t{$word}\t{$count}"->PrintLine();
        index += 1;
      };
    };
  }
}


wdinfo 'Hamlet';'To be, or not to be: that is the question:'


import javax.swing.JFrame;

public class Main {
     public static void main(String[] args) throws Exception {
         JFrame w = new JFrame("Title");
         w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         w.setSize(800,600);
         w.setVisible(true);
     }
}


# v0.6

using Tk

w = Toplevel("Example")


import javax.swing.JFrame

fun main(args : Array<String>) {
    JFrame("Title").apply {
        setSize(800, 600)
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }
}


nomainwin
open "GUI Window" for window as #1
wait


let () =
  let n =
    try int_of_string Sys.argv.(1)
    with _ -> 10
  in
  let ic = open_in "135-0.txt" in
  let h = Hashtbl.create 97 in
  let w = Str.regexp "[^A-Za-zéèàêâôîûœ]+" in
  try
    while true do
      let line = input_line ic in
      let words = Str.split w line in
      List.iter (fun word ->
        let word = String.lowercase_ascii word in
        match Hashtbl.find_opt h word with
        | None -> Hashtbl.add h word 1
        | Some x -> Hashtbl.replace h word (succ x)
      ) words
    done
  with End_of_file ->
    close_in ic;
    let l = Hashtbl.fold (fun word count acc -> (word, count)::acc) h [] in
    let s = List.sort (fun (_, c1) (_, c2) -> compare c2 c1) l in
    let r = List.init n (fun i -> List.nth s i) in
    List.iter (fun (word, count) ->
      Printf.printf "%d  %s\n" count word
    ) r


$top = 10;

open $fh, "<", '135-0.txt';
($text = join '', <$fh>) =~ tr/A-Z/a-z/
    or die "Can't open '135-0.txt': $!\n";

@matcher = (
    qr/[a-z]+/,     # simple 7-bit ASCII
    qr/\w+/,        # word characters with underscore
    qr/[a-z0-9]+/,  # word characters without underscore
);

for $reg (@matcher) {
    print "\nTop $top using regex: " . $reg . "\n";
    @matches = $text =~ /$reg/g;
    my %words;
    for $w (@matches) { $words{$w}++ };
    $c = 0;
    for $w ( sort { $words{$b} <=> $words{$a} } keys %words ) {
        printf "%-7s %6d\n", $w, $words{$w};
        last if ++$c >= $top;
    }
}


win = window().new("New Window")
w = 320
h = 240
firstScreen = _system.deskTopRectList[1]
x = firstScreen.width/2 - w/2
y = firstScreen.height/2- h/2
win.rect = rect(x,y,x+w,y+h)
-- Director needs a binary movie file (*.dir) for opening new windows. But this
-- movie file can be totally empty, and if it's write protected in the filesystem,
-- it can be re-used for multiple windows.
win.filename = _movie.path & "empty.dir"
win.open()


local iup = require "iuplua"

iup.dialog{
  title = "Window";
  iup.vbox{
    margin = "10x10";
    iup.label{title = "A window"}
  }
}:show()

iup.MainLoop()


Module DisplayWindow {
      Declare MyForm Form
      Method MyForm,"Show",1
}
DisplayWindow


alias CreateMyWindow {
 .window -Cp +d @WindowName 600 480
}


without javascript_semantics
?"loading..."
constant subs = '\t'&"\r\n_.,\"\'!;:?][()|=<>#/*{}[email protected]%&$",
         reps = repeat(' ',length(subs)),
         fn = open("135-0.txt","r")
string text = lower(substitute_all(get_text(fn),subs,reps))
close(fn)
sequence words = append(sort(split(text,no_empty:=true)),"")
constant wf = new_dict()
string last = words[1]
integer count = 1
for i=2 to length(words) do
    if words[i]!=last then
        setd({count,last},0,wf)
        count = 0
        last = words[i]
    end if
    count += 1
end for
count = 10
function visitor(object key, object /*data*/, object /*user_data*/)
    ?key
    count -= 1
    return count>0
end function
traverse_dict(routine_id("visitor"),0,wf,true)


include ..\Utilitys.pmt

"loading..." ?
"135-0.txt" "r" fopen var fn
" "
true
while
    fn fgets number? if drop fn fclose false else lower " " chain chain true endif
endwhile

"process..." ?
len for
    var i
    i get dup 96 > swap 123 < and not if 32 i set endif
endfor
split sort

"count..." ?
( ) var words
"" var prev
1 var n
len for
    var i
    i get dup prev ==
    if
        drop n 1 + var n
    else
        words ( n prev ) 0 put var words var prev 1 var n
    endif
endfor
drop
words sort
10 for
    -1 * get ?
endfor
drop


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

import javax.swing.JFrame
import javax.swing.JLabel
import java.awt.BorderLayout
import java.awt.Font
import java.awt.Color

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
parse arg showText .
select
  when showText.length = 0          then addText = isTrue
  when 'YES'.abbrev(showText.upper) then addText = isTrue
  when showText = '.'               then addText = isTrue
  otherwise                              addText = isFalse
  end
title = 'Rosetta Code - Window Creation'
createFrame(title, addText)

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method createFrame(title, addText = boolean 0) public static
  do
    fenester = JFrame(title)
    fenester.setSize(600, 200)
    fenester.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    if addText then decorate(fenester)
    fenester.setVisible(isTrue)

  catch ex = Exception
    ex.printStackTrace()
  end

  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method decorate(fenester = JFrame, textStr = 'This page intentionally left blank.') private static returns JFrame
  textlbl  = JLabel(textStr)
  textfont = Font(Font.SERIF, Font.BOLD, 20)
  textlbl.setHorizontalAlignment(JLabel.CENTER)
  textlbl.setFont(textfont)
  textlbl.setForeground(Color.ORANGE)
  fenester.add(textlbl, BorderLayout.CENTER)

  return fenester

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isTrue() public static returns boolean
  return (1 == 1)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isFalse() public static returns boolean
  return \(1 == 1)


import gintro/[glib, gobject, gtk, gio]

proc activate(app: Application) =
  ## Activate the application.
  let window = newApplicationWindow(app)
  window.setTitle("Window for Rosetta")
  window.setSizeRequest(640, 480)
  window.showAll()

let app = newApplication(Application, "Rosetta.Window")
discard app.connect("activate", activate)
discard app.run()


use Gtk2;

bundle Default {
  class GtkHello {
    function : Main(args : String[]) ~ Nil {
      window := GtkWindow->New();
      delete_callback := Events->DeleteEvent(GtkWidget) ~ Nil;
      window->SignalConnect(Signal->Destroy, window->As(GtkWidget), delete_callback);
      window->SetTitle("Title");
      window->Show();
      Appliction->Main();
    }
  }
}


<?php

preg_match_all('/\w+/', file_get_contents($argv[1]), $words);
$frecuency = array_count_values($words[0]);
arsort($frecuency);

echo "Rank\tWord\tFrequency\n====\t====\t=========\n";
$i = 1;
foreach ($frecuency as $word => $count) {
    echo $i . "\t" . $word . "\t" . $count . "\n";
    if ($i >= 10) {
        break;
    }
    $i++;
}


main =>
  NTop = 10,
  File = "les_miserables.txt",
  Chars = read_file_chars(File),

  % Remove the Project Gutenberg header/footer
  find(Chars,"*** START OF THE PROJECT GUTENBERG EBOOK LES MISÉRABLES ***",_,HeaderEnd),
  find(Chars,"*** END OF THE PROJECT GUTENBERG EBOOK LES MISÉRABLES ***",FooterStart,_),

  Book = [to_lowercase(C) : C in slice(Chars,HeaderEnd+1,FooterStart-1)],

  % Split into words (different set of split characters)
  member(SplitType,[all,space_punct,space]),
  println(split_type=SplitType),
  split_chars(SplitType,SplitChars),
  Words = split(Book,SplitChars),

  println(freq(Words).to_list.sort_down(2).take(NTop)),
  nl,
  fail.

freq(L) = Freq =>
  Freq = new_map(),
  foreach(E in L)
    Freq.put(E,Freq.get(E,0)+1)
  end.

% different set of split chars
split_chars(all,"\n\r \t,;!.?()[]”\"-“—-__‘’*").
split_chars(space_punct,"\n\r \t,;!.?").
split_chars(space,"\n\r \t").


(setq *Delim " ^I^J^M-_.,\"'*[]?!&@#$%^\(\):;")
(setq *Skip (chop *Delim))

(de word+ NIL
   (prog1
      (lowc (till *Delim T))
      (while (member (peek) *Skip) (char)) ) )

(off B)
(in "135-0.txt"
   (until (eof)
      (let W (word+)
         (if (idx 'B W T) (inc (car @)) (set W 1)) ) ) )
(for L (head 10 (flip (by val sort (idx 'B))))
   (println L (val L)) )


#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

@interface Win : NSWindow
{
}
- (void)applicationDidFinishLaunching: (NSNotification *)notification;
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;
@end

@implementation Win : NSWindow
-(instancetype) init
{
  if ((self = [super
    initWithContentRect: NSMakeRect(0, 0, 800, 600)
    styleMask: (NSTitledWindowMask | NSClosableWindowMask)
    backing: NSBackingStoreBuffered
    defer: NO])) {

    [self setTitle: @"A Window"];
    [self center];
  }
  return self;
}

- (void)applicationDidFinishLaunching: (NSNotification *)notification
{
  [self orderFront: self];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification
{
  return YES;
}
@end

int main()
{
  @autoreleasepool {

    [NSApplication sharedApplication];
    Win *mywin = [[Win alloc] init];
    [NSApp setDelegate: mywin];
    [NSApp runModalForWindow: mywin];

  }
  return EXIT_SUCCESS;
}


let () =
  let top = Tk.openTk() in
  Wm.title_set top "An Empty Window";
  Wm.geometry_set top "240x180";
  Tk.mainLoop ();
;;


  DEFINE VAR C-Win AS WIDGET-HANDLE NO-UNDO.

  CREATE WINDOW C-Win ASSIGN
         HIDDEN             = YES
         TITLE              = "OpenEdge Window Display"
         HEIGHT             = 10.67
         WIDTH              = 95.4
         MAX-HEIGHT         = 16
         MAX-WIDTH          = 95.4
         VIRTUAL-HEIGHT     = 16
         VIRTUAL-WIDTH      = 95.4
         RESIZE             = yes
         SCROLL-BARS        = no
         STATUS-AREA        = no
         BGCOLOR            = ?
         FGCOLOR            = ?
         KEEP-FRAME-Z-ORDER = yes
         THREE-D            = yes
         MESSAGE-AREA       = no
         SENSITIVE          = yes.

    VIEW C-Win.

    ON WINDOW-CLOSE OF C-Win /* <insert window title> */
    DO:
      /* This event will close the window and terminate the procedure.  */
      APPLY "CLOSE":U TO THIS-PROCEDURE.
      RETURN NO-APPLY.
    END.

    WAIT-FOR CLOSE OF THIS-PROCEDURE.


functor
import
   Application
   QTk at 'x-oz://system/wp/QTk.ozf'
define
   proc {OnClose}
      {Application.exit 0}
   end

   %% Descripe the GUI in a declarative style.
   GUIDescription = td(label(text:"Hello World!")
		       action:OnClose %% Exit app when window closes.
		      )

   %% Create a window object from the description and show it.
   Window = {QTk.build GUIDescription}
   {Window show}
end


print_top_words(File, N):-
    read_file_to_string(File, String, [encoding(utf8)]),
    re_split("\\w+", String, Words),
    lower_case(Words, Lower),
    sort(1, @=<, Lower, Sorted),
    merge_words(Sorted, Counted),
    sort(2, @>, Counted, Top_words),
    writef("Top %w words:\nRank\tCount\tWord\n", [N]),
    print_top_words(Top_words, N, 1).

lower_case([_], []):-!.
lower_case([_, Word|Words], [Lower - 1|Rest]):-
    string_lower(Word, Lower),
    lower_case(Words, Rest).

merge_words([], []):-!.
merge_words([Word - C1, Word - C2|Words], Result):-
    !,
    C is C1 + C2,
    merge_words([Word - C|Words], Result).
merge_words([W|Words], [W|Rest]):-
    merge_words(Words, Rest).

print_top_words([], _, _):-!.
print_top_words(_, 0, _):-!.
print_top_words([Word - Count|Rest], N, R):-
    writef("%w\t%w\t%w\n", [R, Count, Word]),
    N1 is N - 1,
    R1 is R + 1,
    print_top_words(Rest, N1, R1).

main:-
    print_top_words("135-0.txt", 10).


EnableExplicit

Structure wordcount
  wkey$
  count.i
EndStructure

Define token.c, word$, idx.i, start.i, arg$
NewMap wordmap.i()
NewList wordlist.wordcount()

If OpenConsole("")
  arg$ = ProgramParameter(0)
  If arg$ = "" : End 1 : EndIf
  start = ElapsedMilliseconds()
  If ReadFile(0, arg$, #PB_Ascii)
    While Not Eof(0)
      token = ReadCharacter(0, #PB_Ascii)
      Select token
        Case 'A' To 'Z', 'a' To 'z'
          word$ + LCase(Chr(token))
        Default
          If word$
            wordmap(word$) + 1
            word$ = ""
          EndIf
      EndSelect
    Wend
    CloseFile(0)
    ForEach wordmap()
      AddElement(wordlist())
      wordlist()\wkey$ = MapKey(wordmap())
      wordlist()\count = wordmap()
    Next
    SortStructuredList(wordlist(), #PB_Sort_Descending, OffsetOf(wordcount\count), TypeOf(wordcount\count))
    PrintN("Elapsed milliseconds: " + Str(ElapsedMilliseconds() - start))
    PrintN("File: " + GetFilePart(arg$))
    PrintN(~"Rank\tCount\t\t  Word")
    If FirstElement(wordlist())
      For idx = 1 To 10
        Print(RSet(Str(idx), 2))
        Print(~"\t")
        Print(wordlist()\wkey$)
        Print(~"\t\t")
        PrintN(RSet(Str(wordlist()\count), 6))
        If NextElement(wordlist()) = 0
          Break
        EndIf
      Next
    EndIf
  EndIf
  Input()
EndIf

End


Program WindowCreation_SDL;

{$linklib SDL}

uses
  SDL,
  SysUtils;

var
  screen: PSDL_Surface;

begin
  SDL_Init(SDL_INIT_VIDEO);
  screen := SDL_SetVideoMode( 800, 600, 16, (SDL_SWSURFACE or SDL_HWPALETTE) );
  sleep(2000);
  SDL_Quit;
end.


  use Tk;

  MainWindow->new();
  MainLoop;


-- demo\rosetta\Window_creation.exw
with javascript_semantics
include pGUI.e
IupOpen()
IupShow(IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200"),"TITLE=Hello"))
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


(load "@lib/openGl.l")

(glutInit)
(glutCreateWindow "Goodbye, World!")
(keyboardFunc '(() (bye)))
(glutMainLoop)


import collections
import re
import string
import sys

def main():
  counter = collections.Counter(re.findall(r"\w+",open(sys.argv[1]).read().lower()))
  print counter.most_common(int(sys.argv[2]))

if __name__ == "__main__":
  main()


wordcount<-function(file,n){
  punctuation=c("`","~","!","@","#","$","%","^","&","*","(",")","_","+","=","{","[","}","]","|","\\",":",";","\"","<",",",">",".","?","/","'s")
  wordlist=scan(file,what=character())
  wordlist=tolower(wordlist)
  for(i in 1:length(punctuation)){
    wordlist=gsub(punctuation[i],"",wordlist,fixed=T)
  }
  df=data.frame("Word"=sort(unique(wordlist)),"Count"=rep(0,length(unique(wordlist))))
  for(i in 1:length(unique(wordlist))){
    df[i,2]=length(which(wordlist==df[i,1]))
  }
  df=df[order(df[,2],decreasing = T),]
  row.names(df)=1:nrow(df)
  return(df[1:n,])
}


#lang racket

(define (all-words f (case-fold string-downcase))
  (map case-fold (regexp-match* #px"\\w+" (file->string f))))

(define (l.|l| l) (cons (car l) (length l)))

(define (counts l (>? >)) (sort (map l.|l| (group-by values l)) >? #:key cdr))

(module+ main
  (take (counts (all-words "data/les-mis.txt")) 10))


?- new(D, window('Prolog Window')), send(D, open).


Define MyWin.i, Event.i

MyWin = OpenWindow(#PB_Any, 412, 172, 402, 94, "PureBasic")

; Event loop
Repeat
   Event = WaitWindowEvent()
   Select Event
      Case #PB_Event_Gadget
         ; Handle any gadget events here
      Case #PB_Event_CloseWindow
         Break
   EndSelect
ForEver


  import Tkinter

  w = Tkinter.Tk()
  w.mainloop()


#lang racket/gui
(send (new frame%
           [label "New Window"]
           [width 100] [height 100])
      show #t)


use GTK::Simple;
use GTK::Simple::App;

my GTK::Simple::App $app .= new(title => 'Simple GTK Window');

$app.size-request(250, 100);

$app.set-content(
    GTK::Simple::VBox.new(
        my $button = GTK::Simple::Button.new(label => 'Exit'),
    )
);

$app.border-width = 40;

$button.clicked.tap: { $app.exit }

$app.run;


sub MAIN ($filename, $top = 10) {
    my $file = $filename.IO.slurp.lc.subst(/ (<[\w]-[_]>'-')\n(<[\w]-[_]>) /, {$0 ~ $1}, :g );
    my @matcher = (
        rx/ <[a..z]>+ /,    # simple 7-bit ASCII
        rx/ \w+ /,          # word characters with underscore
        rx/ <[\w]-[_]>+ /,  # word characters without underscore
        rx/ <[\w]-[_]>+[["'"|'-'|"'-"]<[\w]-[_]>+]* /   # word characters without underscore but with hyphens and contractions
    );
    for @matcher -> $reg {
        say "\nTop $top using regex: ", $reg.raku;
        .put for $file.comb( $reg ).Bag.sort(-*.value)[^$top];
    }
}


/*REXX pgm displays top 10 words in a file (includes foreign letters),  case is ignored.*/
parse arg fID top .                              /*obtain optional arguments from the CL*/
if fID=='' | fID==","  then fID= 'les_mes.txt'   /*None specified? Then use the default.*/
if top=='' | top==","  then top= 10              /*  "      "        "   "   "     "    */
call init                                        /*initialize varied bunch of variables.*/
call rdr
say right('word', 40)  " "  center(' rank ', 6)  "  count "   /*display title for output*/
say right('════', 40)  " "  center('══════', 6)  " ═══════"   /*   "    title separator.*/

     do  until otops==tops | tops>top            /*process enough words to satisfy  TOP.*/
     WL=;         mk= 0;    otops= tops          /*initialize the word list (to a NULL).*/

          do n=1  for c;    z= !.n;      k= @.z  /*process the list of words in the file*/
          if k==mk  then WL= WL z                /*handle cases of tied number of words.*/
          if k> mk  then do;  mk=k;  WL=z;  end  /*this word count is the current max.  */
          end   /*n*/

     wr= max( length(' rank '), length(top) )    /*find the maximum length of the rank #*/

          do d=1  for words(WL);  y= word(WL, d) /*process all words in the  word list. */
          if d==1  then w= max(10, length(@.y) ) /*use length of the first number used. */
          say right(y, 40)         right( commas(tops), wr)          right(commas(@.y), w)
          @.y= .                                 /*nullify word count for next go 'round*/
          end   /*d*/                            /* [↑]  this allows a non-sorted list. */

     tops= tops + words(WL)                      /*correctly handle any  tied  rankings.*/
     end        /*until*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
16bit:  do k=1 for xs; _=word(x,k); $=changestr('├'left(_,1),$,right(_,1)); end;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
init:   x= 'Çà åÅ çÇ êÉ ëÉ áà óâ ªæ ºç ¿è ⌐é ¬ê ½ë «î »ï ▒ñ ┤ô ╣ù ╗û ╝ü';     xs= words(x)
        abcL="abcdefghijklmnopqrstuvwxyz'"       /*lowercase letters of Latin alphabet. */
        abcU= abcL;            upper abcU        /*uppercase version of Latin alphabet. */
        accL= 'üéâÄàÅÇêëèïîìéæôÖòûùÿáíóúÑ'       /*some lowercase accented characters.  */
        accU= 'ÜéâäàåçêëèïîìÉÆôöòûùÿáíóúñ'       /*  "  uppercase    "         "        */
        accG= 'αßΓπΣσµτΦΘΩδφε'                   /*  "  upper/lowercase Greek letters.  */
        ll= abcL || abcL ||accL ||accL || accG               /*chars of  after letters. */
        uu= abcL || abcU ||accL ||accU || accG || xrange()   /*  "    " before    "     */
        @.= 0;    q= "'";    totW= 0;    !.= @.;    c= 0;    tops= 1;          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
rdr:   do #=0  while lines(fID)\==0; $=linein(fID) /*loop whilst there're lines in file.*/
       if pos('├', $) \== 0  then call 16bit       /*are there any  16-bit  characters ?*/
       $= translate( $, ll, uu)                    /*trans. uppercase letters to lower. */
          do while $ \= '';    parse var  $  z  $  /*process each word in the  $  line. */
          parse var  z     z1  2  zr  ''  -1  zL   /*obtain: first, middle, & last char.*/
          if z1==q  then do; z=zr; if z==''  then iterate; end /*starts with apostrophe?*/
          if zL==q  then z= strip(left(z, length(z) - 1))      /*ends     "       "    ?*/
          if z==''  then iterate                               /*if Z is now null, skip.*/
          if @.z==0  then do;  c=c+1; !.c=z;  end  /*bump word cnt; assign word to array*/
          totW= totW + 1;      @.z= @.z + 1        /*bump total words; bump a word count*/
          end   /*while*/
       end      /*#*/
    say commas(totW)     ' words found  ('commas(c)    "unique)  in "    commas(#),
                         ' records read from file: '     fID;        say;          return


with Ada.Text_IO;

procedure Wieferich_Primes is

   function Is_Prime (V : Positive) return Boolean is
      D : Positive := 5;
   begin
      if V < 2       then return False; end if;
      if V mod 2 = 0 then return V = 2; end if;
      if V mod 3 = 0 then return V = 3; end if;
      while D * D <= V loop
         if V mod D = 0 then
            return False;
         end if;
         D := D + 2;
      end loop;
      return True;
   end Is_Prime;

   function Is_Wieferich (N : Positive) return Boolean is
      Q : Natural := 1;
   begin
      if not Is_Prime (N) then
         return False;
      end if;
      for P in 2 .. N loop
         Q := (2 * Q) mod N**2;
      end loop;
      return Q = 1;
   end Is_Wieferich;

begin

   Ada.Text_IO.Put_Line ("Wieferich primes below 5000:");
   for N in 1 .. 4999 loop
      if Is_Wieferich (N) then
         Ada.Text_IO.Put_Line (N'Image);
      end if;
   end loop;

end Wieferich_Primes;


  create form as qform
     center
     width=500
     height=400
  end create
  form.showModal


Load "guilib.ring"

MyApp = New qApp {
        win1 = new qWidget() {
               setwindowtitle("Hello World")
               setGeometry(100,100,370,250)
               show()}
        exec()}


 require 'tk'

 window = TkRoot::new()
 window::mainloop()


html "Close me!"
button #c, "Close Me", [doExit]
wait

' -----------------------------------------------------------------------------------
' Get outta here. depending on how may layers you are into the window (history level)
' If you are at the top level then close the window
' ----------------------------------------------------------------------------------
[doExit]
html "<script language='javascript' type='text/javascript'>
var a = history.length;
a = a - 1;
window.open('','_parent','');
window.close();
history.go(-a);
</script>"
wait


use winit::event::{Event, WindowEvent};  // winit 0.24
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;

fn main() {
    let event_loop = EventLoop::new();
    let _win = WindowBuilder::new()
        .with_title("Window")
        .build(&event_loop).unwrap();

    event_loop.run(move |ev, _, flow| {
        match ev {
            Event::WindowEvent {
                event: WindowEvent::CloseRequested, ..
            } => {
                *flow = ControlFlow::Exit;
            }
            _ => {}
        }
    });
}


# project : Word count

fp = fopen("Miserables.txt","r")
str = fread(fp, getFileSize(fp))
fclose(fp)

mis =substr(str, " ", nl)
mis = lower(mis)
mis = str2list(mis)
count = list(len(mis))
ready = []
for n = 1 to len(mis)
     flag = 0
     for m = 1 to len(mis)
           if mis[n] = mis[m] and n != m
              for p = 1 to len(ready)
                    if m = ready[p]
                       flag = 1
                    ok
              next
              if flag = 0
                 count[n] = count[n] + 1
              ok
           ok
     next
     if flag = 0
        add(ready, n)
     ok
next
for n = 1 to len(count)
     for m = n + 1 to len(count)
          if count[m] > count[n]
             temp = count[n]
             count[n] = count[m]
             count[m] = temp
             temp = mis[n]
             mis[n] = mis[m]
             mis[m] = temp
          ok
     next
next
for n = 1 to 10
     see mis[n] + " " + (count[n] + 1) + nl
next

func getFileSize fp
        c_filestart = 0
        c_fileend = 2
        fseek(fp,0,c_fileend)
        nfilesize = ftell(fp)
        fseek(fp,0,c_filestart)
        return nfilesize

func swap(a, b)
        temp = a
        a = b
        b = temp
        return [a, b]


class String
  def wc
  n = Hash.new(0)
  downcase.scan(/[A-Za-zÀ-ÿ]+/) { |g| n[g] += 1 }
  n.sort{|n,g| n[1]<=>g[1]}
  end
end

open('135-0.txt') { |n| n.read.wc[-10,10].each{|n| puts n[0].to_s+"->"+n[1].to_s} }


      ⎕CY 'dfns' ⍝ import dfns namespace
                 ⍝ pco ← prime finder
                 ⍝ nats ← natural number arithmetic (uses strings)
      ⍝ Get all Wieferich primes below n:
      wief←{{⍵/⍨{(,'0')≡(×⍨⍵)|nats 1 -nats⍨ 2 *nats ⍵-1}¨⍵}⍸1 pco⍳⍵}
      wief 5000
1093 3511


wieferich?: function [n][
    and? -> prime? n
         -> zero? (dec 2 ^ n-1) % n ^ 2
]

print ["Wieferich primes less than 5000:" select 1..5000 => wieferich?]


# syntax: GAWK -f WIEFERICH_PRIMES.AWK
# converted from FreeBASIC
BEGIN {
    start = 1
    stop = 4999
    for (i=start; i<=stop; i++) {
      if (is_wieferich_prime(i)) {
        printf("%d\n",i)
        count++
      }
    }
    printf("Wieferich primes %d-%d: %d\n",start,stop,count)
    exit(0)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (n % 2 == 0) { return(n == 2) }
    if (n % 3 == 0) { return(n == 3) }
    while (d*d <= n) {
      if (n % d == 0) { return(0) }
      d += 2
      if (n % d == 0) { return(0) }
      d += 4
    }
    return(1)
}
function is_wieferich_prime(p,  p2,q) {
    if (!is_prime(p)) { return(0) }
    q = 1
    p2 = p^2
    while (p > 1) {
      q = (2*q) % p2
      p--
    }
    return(q == 1)
}


print "Wieferich primes less than 5000: "
for i = 1 to 5000
    if isWeiferich(i) then print i
next i
end

function isWeiferich(p)
    if not isPrime(p) then return False
    q = 1
    p2 = p ^ 2
    while p > 1
        q = (2 * q) mod p2
        p -= 1
    end while
    if q = 1 then return True else return False
end function

function isPrime(v)
    if v < 2 then return False
    if v mod 2 = 0 then return v = 2
    if v mod 3 = 0 then return v = 3
    d = 5
    while d * d <= v
        if v mod d = 0 then return False else d += 2
    end while
    return True
end function


import javax.swing.JFrame

object ShowWindow{
  def main(args: Array[String]){
    var jf = new JFrame("Hello!")

    jf.setSize(800, 600)
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    jf.setVisible(true)
  }
}


#!r6rs

;; PS-TK example: display simple frame

(import (rnrs)
        (lib pstk main) ; change this to refer to your installation of PS/Tk
        )

(define tk (tk-start))
(tk/wm 'title tk "PS-Tk Example: Frame")

(tk-event-loop tk)


$ include "seed7_05.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const proc: main is func
  begin
    screen(200, 200);
    KEYBOARD := GRAPH_KEYBOARD;
    ignore(getc(KEYBOARD));
  end func;


var tk = require('Tk');
%s'MainWindow'.new;
tk.MainLoop;


open XWindows ;
open Motif ;

val showWindow = fn () =>

 let
  val shell = XtAppInitialise    ""    "demo" "top" [] [XmNwidth 400, XmNheight 300 ] ;
  val main  = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ;
  val buttn = XmCreateDrawnButton main "stop" [ XmNlabelString "Exit"] ;
  val quit  = fn (w,c,t) => (XtUnrealizeWidget shell; t) ;
 in

  (
  XtSetCallbacks   buttn [ (XmNactivateCallback, quit) ] XmNarmCallback ;
  XtManageChildren [buttn];
  XtManageChild    main;
  XtRealizeWidget  shell
  )

end;


use std::cmp::Reverse;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

extern crate regex;
use regex::Regex;

fn word_count(file: File, n: usize) {
    let word_regex = Regex::new("(?i)[a-z']+").unwrap();

    let mut words = HashMap::new();
    for line in BufReader::new(file).lines() {
        word_regex
            .find_iter(&line.expect("Read error"))
            .map(|m| m.as_str())
            .for_each(|word| {
                *words.entry(word.to_lowercase()).or_insert(0) += 1;
            });
    }

    let mut words: Vec<_> = words.iter().collect();
    words.sort_unstable_by_key(|&(word, count)| (Reverse(count), word));

    for (word, count) in words.iter().take(n) {
        println!("{:8} {:>8}", word, count);
    }
}

fn main() {
    word_count(File::open("135-0.txt").expect("File open error"), 10)
}


import scala.io.Source

object WordCount extends App {

  val url = "http://www.gutenberg.org/files/135/135-0.txt"
  val header = "Rank Word  Frequency\n==== ======== ======"

  def wordCnt =
    Source.fromURL(url).getLines()
      .filter(_.nonEmpty)
      .flatMap(_.split("""\W+""")).toSeq
      .groupBy(_.toLowerCase())
      .mapValues(_.size).toSeq
      .sortWith { case ((_, v0), (_, v1)) => v0 > v1 }
      .take(10).zipWithIndex

  println(header)
  wordCnt.foreach {
    case ((word, count), rank) => println(f"${rank + 1}%4d $word%-8s $count%6d")
  }

  println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")

}


$ include "seed7_05.s7i";
  include "gethttp.s7i";
  include "strifile.s7i";
  include "scanfile.s7i";
  include "chartype.s7i";
  include "console.s7i";

const type: wordHash is hash [string] integer;
const type: countHash is hash [integer] array string;

const proc: main is func
  local
    var file: inFile is STD_NULL;
    var string: aWord is "";
    var wordHash: numberOfWords is wordHash.EMPTY_HASH;
    var countHash: countWords is countHash.EMPTY_HASH;
    var array integer: countKeys is 0 times 0;
    var integer: index is 0;
    var integer: number is 0;
  begin
    OUT := STD_CONSOLE;
    inFile := openStrifile(getHttp("www.gutenberg.org/files/135/135-0.txt"));
    while hasNext(inFile) do
      aWord := lower(getSimpleSymbol(inFile));
      if aWord <> "" and aWord[1] in letter_char then
        if aWord in numberOfWords then
          incr(numberOfWords[aWord]);
        else
          numberOfWords @:= [aWord] 1;
        end if;
      end if;
    end while;
    countWords := flip(numberOfWords);
    countKeys := sort(keys(countWords));
    writeln("Word    Frequency");
    for index range length(countKeys) downto length(countKeys) - 9 do
      number := countKeys[index];
      for aWord range sort(countWords[number]) do
        writeln(aWord rpad 8 <& number);
      end for;
    end for;
  end func;


#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>

#define LIMIT 5000
static bool PRIMES[LIMIT];

static void prime_sieve() {
    uint64_t p;
    int i;

    PRIMES[0] = false;
    PRIMES[1] = false;
    for (i = 2; i < LIMIT; i++) {
        PRIMES[i] = true;
    }

    for (i = 4; i < LIMIT; i += 2) {
        PRIMES[i] = false;
    }

    for (p = 3;; p += 2) {
        uint64_t q = p * p;
        if (q >= LIMIT) {
            break;
        }
        if (PRIMES[p]) {
            uint64_t inc = 2 * p;
            for (; q < LIMIT; q += inc) {
                PRIMES[q] = false;
            }
        }
    }
}

uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
    uint64_t result = 1;

    if (mod == 1) {
        return 0;
    }

    base %= mod;
    for (; exp > 0; exp >>= 1) {
        if ((exp & 1) == 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
    }
    return result;
}

void wieferich_primes() {
    uint64_t p;

    for (p = 2; p < LIMIT; ++p) {
        if (PRIMES[p] && modpow(2, p - 1, p * p) == 1) {
            printf("%lld\n", p);
        }
    }
}

int main() {
    prime_sieve();

    printf("Wieferich primes less than %d:\n", LIMIT);
    wieferich_primes();

    return 0;
}


#include <cstdint>
#include <iostream>
#include <vector>

std::vector<bool> prime_sieve(uint64_t limit) {
    std::vector<bool> sieve(limit, true);
    if (limit > 0)
        sieve[0] = false;
    if (limit > 1)
        sieve[1] = false;
    for (uint64_t i = 4; i < limit; i += 2)
        sieve[i] = false;
    for (uint64_t p = 3; ; p += 2) {
        uint64_t q = p * p;
        if (q >= limit)
            break;
        if (sieve[p]) {
            uint64_t inc = 2 * p;
            for (; q < limit; q += inc)
                sieve[q] = false;
        }
    }
    return sieve;
}

uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
    if (mod == 1)
        return 0;
    uint64_t result = 1;
    base %= mod;
    for (; exp > 0; exp >>= 1) {
        if ((exp & 1) == 1)
            result = (result * base) % mod;
        base = (base * base) % mod;
    }
    return result;
}

std::vector<uint64_t> wieferich_primes(uint64_t limit) {
    std::vector<uint64_t> result;
    std::vector<bool> sieve(prime_sieve(limit));
    for (uint64_t p = 2; p < limit; ++p)
        if (sieve[p] && modpow(2, p - 1, p * p) == 1)
            result.push_back(p);
    return result;
}

int main() {
    const uint64_t limit = 5000;
    std::cout << "Wieferich primes less than " << limit << ":\n";
    for (uint64_t p : wieferich_primes(limit))
        std::cout << p << '\n';
}


V allstates = ‘Ht. ’
V head      = allstates[0]
V tail      = allstates[1]
V conductor = allstates[2]
V empty     = allstates[3]

V w =
|‘tH.........
  .   .
     ...
  .   .
  Ht.. ......’

T WW
   [[Char]] world
   Int w
   Int h
   F (world, w, h)
      .world = world
      .w = w
      .h = h

F readfile(f)
   V world = f.map(row -> row.rtrim(Array[Char]("\r\n")))
   V height = world.len
   V width = max(world.map(row -> row.len))
   V nonrow = [‘ ’(‘ ’ * width)‘ ’]
   V world2 = nonrow [+] world.map(row -> ‘ ’String(row).ljust(@width)‘ ’) [+] nonrow
   V world3 = world2.map(row -> Array(row))
   R WW(world3, width, height)

F newcell(currentworld, x, y)
   V istate = currentworld[y][x]
   assert(istate C :allstates, ‘Wireworld cell set to unknown value "#."’.format(istate))
   V ostate = :empty
   I istate == :head
      ostate = :tail
   E I istate == :tail
      ostate = :conductor
   E I istate == :empty
      ostate = :empty
   E
      V n = sum([(-1, -1), (-1, +0), (-1, +1),
                 (+0, -1),           (+0, +1),
                 (+1, -1), (+1, +0), (+1, +1)].map((dx, dy) -> Int(@currentworld[@y + dy][@x + dx] == :head)))
      ostate = I n C 1..2 {:head} E :conductor
   R ostate

F nextgen(ww)
   V (world, width, height) = ww
   V newworld = copy(world)
   L(x) 1 .. width
      L(y) 1 .. height
         newworld[y][x] = newcell(world, x, y)
   R WW(newworld, width, height)

F world2string(ww)
   R ww.world[1 .< (len)-1].map(row -> (row[1 .< (len)-1]).join(‘’).rtrim((‘ ’, "\t", "\r", "\n"))).join("\n")

V ww = readfile(w.split("\n"))

L(gen) 10
   print(("\n#3 ".format(gen))‘’(‘=’ * (ww.w - 4))"\n")
   print(world2string(ww))
   ww = nextgen(ww)


new GuiControl(GuiName)
{
	profile = "GuiDefaultProfile";
	horizSizing = "right";
	vertSizing = "bottom";
	position = "0 0";
	extent = "640 480";
	minExtent = "8 2";
	enabled = 1;
	visible = 1;
	clipToParent = 1;

	new GuiWindowCtrl()
	{
		profile = "GuiWindowProfile";
		horizSizing = "right";
		vertSizing = "bottom";
		position = "0 0";
		extent = "100 200";
		minExtent = "8 2";
		enabled = 1;
		visible = 1;
		clipToParent = 1;
		command = "canvas.popDialog(GuiName);";
		accelerator = "escape";
		maxLength = 255;
		resizeWidth = 1;
		resizeHeight = 1;
		canMove = 1;
		canClose = 1;
		canMinimize = 1;
		canMaximize = 1;
		minSize = "50 50";
		closeCommand = "canvas.popDialog(GuiName);";
	};
};

canvas.pushDialog(GuiName);


(defvarl SDL_INIT_VIDEO #x00000020)
(defvarl SDL_SWSURFACE #x00000000)
(defvarl SDL_HWPALETTE #x20000000)

(typedef SDL_Surface (cptr SDL_Surface))

(typedef SDL_EventType (enumed uint8 SDL_EventType
                          (SDL_KEYUP 3)
                          (SDL_QUIT 12)))

(typedef SDL_Event (union SD_Event
                     (type SDL_EventType)
		     (pad (array 8 uint32))))

(with-dyn-lib "libSDL.so"
  (deffi SDL_Init "SDL_Init" int (uint32))
  (deffi SDL_SetVideoMode "SDL_SetVideoMode"
    SDL_Surface (int int int uint32))
  (deffi SDL_GetError "SDL_GetError" str ())
  (deffi SDL_WaitEvent "SDL_WaitEvent" int ((ptr-out SDL_Event)))
  (deffi SDL_Quit "SDL_Quit" void ()))

(when (neql 0 (SDL_Init SDL_INIT_VIDEO))
  (put-string `unable to initialize SDL: @(SDL_GetError)`)
  (exit nil))

(unwind-protect
  (progn
    (SDL_SetVideoMode 800 600 16 (logior SDL_SWSURFACE SDL_HWPALETTE))
    (let ((e (make-union (ffi SDL_Event))))
      (until* (memql (union-get e 'type) '(SDL_KEYUP SDL_QUIT))
        (SDL_WaitEvent e))))
  (SDL_Quit))


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Need to reference the following object library (From the Tools menu, choose References)
    Microsoft Forms 2.0 Object Library
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
And :
Programmatic Access to Visual Basic Project must be trusted. See it in Macro's security!


var count = Hash()
var file = File(ARGV[0] \\ '135-0.txt')

file.open_r.each { |line|
    line.lc.scan(/[\pL]+/).each { |word|
        count{word} := 0 ++
    }
}

var top = count.sort_by {|_,v| v }.last(10).flip

top.each { |pair|
    say "#{pair.key}\t-> #{pair.value}"
}


COMMENT COMPILE WITH
$ cim -m64 word-count.sim
;
BEGIN

    COMMENT ----- CLASSES FOR GENERAL USE ;

    ! ABSTRACT HASH KEY TYPE ;
    CLASS HASHKEY;
    VIRTUAL:
        PROCEDURE HASH IS
            INTEGER PROCEDURE HASH;;
        PROCEDURE EQUALTO IS
            BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;;
    BEGIN
    END HASHKEY;

    ! ABSTRACT HASH VALUE TYPE ;
    CLASS HASHVAL;
    BEGIN
        ! THERE IS NOTHING REQUIRED FOR THE VALUE TYPE ;
    END HASHVAL;

    CLASS HASHMAP;
    BEGIN
        CLASS INNERHASHMAP(N); INTEGER N;
        BEGIN

            INTEGER PROCEDURE INDEX(K); REF(HASHKEY) K;
            BEGIN
                INTEGER I;
                IF K == NONE THEN
                    ERROR("HASHMAP.INDEX: NONE IS NOT A VALID KEY");
                I := MOD(K.HASH,N);
            LOOP:
                IF KEYTABLE(I) == NONE OR ELSE KEYTABLE(I).EQUALTO(K) THEN
                    INDEX := I
                ELSE BEGIN
                    I := IF I+1 = N THEN 0 ELSE I+1;
                    GO TO LOOP;
                END;
            END INDEX;

            ! PUT SOMETHING IN ;
            PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
            BEGIN
                INTEGER I;
                IF V == NONE THEN
                    ERROR("HASHMAP.PUT: NONE IS NOT A VALID VALUE");
                I := INDEX(K);
                IF KEYTABLE(I) == NONE THEN BEGIN
                    IF SIZE = N THEN
                        ERROR("HASHMAP.PUT: TABLE FILLED COMPLETELY");
                    KEYTABLE(I) :- K;
                    VALTABLE(I) :- V;
                    SIZE := SIZE+1;
                END ELSE
                    VALTABLE(I) :- V;
            END PUT;

            ! GET SOMETHING OUT ;
            REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
            BEGIN
                INTEGER I;
                IF K == NONE THEN
                    ERROR("HASHMAP.GET: NONE IS NOT A VALID KEY");
                I := INDEX(K);
                IF KEYTABLE(I) == NONE THEN
                    GET :- NONE ! ERROR("HASHMAP.GET: KEY NOT FOUND");
                ELSE
                    GET :- VALTABLE(I);
            END GET;

            PROCEDURE CLEAR;
            BEGIN
                INTEGER I;
                FOR I := 0 STEP 1 UNTIL N-1 DO BEGIN
                    KEYTABLE(I) :- NONE;
                    VALTABLE(I) :- NONE;
                END;
                SIZE := 0;
            END CLEAR;

            ! DATA MEMBERS OF CLASS HASHMAP ;
            REF(HASHKEY) ARRAY KEYTABLE(0:N-1);
            REF(HASHVAL) ARRAY VALTABLE(0:N-1);
            INTEGER SIZE;

        END INNERHASHMAP;

        PROCEDURE PUT(K,V); REF(HASHKEY) K; REF(HASHVAL) V;
        BEGIN
            IF IMAP.SIZE >= 0.75 * IMAP.N THEN
            BEGIN
                COMMENT RESIZE HASHMAP ;
                REF(INNERHASHMAP) NEWIMAP;
                REF(ITERATOR) IT;
                NEWIMAP :- NEW INNERHASHMAP(2 * IMAP.N);
                IT :- NEW ITERATOR(THIS HASHMAP);
                WHILE IT.MORE DO
                BEGIN
                    REF(HASHKEY) KEY;
                    KEY :- IT.NEXT;
                    NEWIMAP.PUT(KEY, IMAP.GET(KEY));
                END;
                IMAP.CLEAR;
                IMAP :- NEWIMAP;
            END;
            IMAP.PUT(K, V);
        END;

        REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K;
            GET :- IMAP.GET(K);

        PROCEDURE CLEAR;
            IMAP.CLEAR;

        INTEGER PROCEDURE SIZE;
            SIZE := IMAP.SIZE;

        REF(INNERHASHMAP) IMAP;

        IMAP :- NEW INNERHASHMAP(16);
    END HASHMAP;

    CLASS ITERATOR(H); REF(HASHMAP) H;
    BEGIN
        INTEGER POS,KEYCOUNT;

        BOOLEAN PROCEDURE MORE;
            MORE := KEYCOUNT < H.SIZE;

        REF(HASHKEY) PROCEDURE NEXT;
        BEGIN
            INSPECT H DO
            INSPECT IMAP DO
            BEGIN
                WHILE KEYTABLE(POS) == NONE DO
                    POS := POS+1;
                NEXT :- KEYTABLE(POS);
                KEYCOUNT := KEYCOUNT+1;
                POS := POS+1;
            END;
        END NEXT;

    END ITERATOR;

    COMMENT ----- PROBLEM SPECIFIC CLASSES ;

    HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
    BEGIN
        INTEGER PROCEDURE HASH;
        BEGIN
            INTEGER I;
            T.SETPOS(1);
            WHILE T.MORE DO
                I := 31*I+RANK(T.GETCHAR);
            HASH := I;
        END HASH;
        BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;
            EQUALTO := T = K QUA TEXTHASHKEY.T;
    END TEXTHASHKEY;

    HASHVAL CLASS COUNTER;
    BEGIN
        INTEGER COUNT;
    END COUNTER;

    REF(INFILE) INF;
    REF(HASHMAP) MAP;
    REF(TEXTHASHKEY) KEY;
    REF(COUNTER) VAL;
    REF(ITERATOR) IT;
    TEXT LINE, WORD;
    INTEGER I, J, MAXCOUNT, LINENO;
    INTEGER ARRAY MAXCOUNTS(1:10);
    REF(TEXTHASHKEY) ARRAY MAXWORDS(1:10);

    WORD :- BLANKS(1000);
    MAP :- NEW HASHMAP;

    COMMENT MAP WORDS TO COUNTERS ;

    INF :- NEW INFILE("135-0.txt");
    INF.OPEN(BLANKS(4096));
    WHILE NOT INF.LASTITEM DO
    BEGIN
        BOOLEAN INWORD;

        PROCEDURE SAVE;
        BEGIN
            IF WORD.POS > 1 THEN
            BEGIN
                KEY :- NEW TEXTHASHKEY(WORD.SUB(1, WORD.POS - 1));
                VAL :- MAP.GET(KEY);
                IF VAL == NONE THEN
                BEGIN
                    VAL :- NEW COUNTER;
                    MAP.PUT(KEY, VAL);
                END;
                VAL.COUNT := VAL.COUNT + 1;
                WORD := " ";
                WORD.SETPOS(1);
            END;
        END SAVE;

        LINENO := LINENO + 1;
        LINE :- COPY(INF.IMAGE).STRIP; INF.INIMAGE;

        COMMENT SEARCH WORDS IN LINE ;
        COMMENT A WORD IS ANY SEQUENCE OF LETTERS ;

        INWORD := FALSE;
        LINE.SETPOS(1);
        WHILE LINE.MORE DO
        BEGIN
            CHARACTER CH;
            CH := LINE.GETCHAR;
            IF CH >= 'a' AND CH <= 'z' THEN
                CH := CHAR(RANK(CH) - RANK('a') + RANK('A'));
            IF CH >= 'A' AND CH <= 'Z' THEN
            BEGIN
                IF NOT INWORD THEN
                BEGIN
                    SAVE;
                    INWORD := TRUE;
                END;
                WORD.PUTCHAR(CH);
            END ELSE
            BEGIN
                IF INWORD THEN
                BEGIN
                    SAVE;
                    INWORD := FALSE;
                END;
            END;
        END;
        SAVE; COMMENT LAST WORD ;
    END;
    INF.CLOSE;

    COMMENT FIND 10 MOST COMMON WORDS ;

    IT :- NEW ITERATOR(MAP);
    WHILE IT.MORE DO
    BEGIN
        KEY :- IT.NEXT;
        VAL :- MAP.GET(KEY);
        FOR I := 1 STEP 1 UNTIL 10 DO
        BEGIN
            IF VAL.COUNT >= MAXCOUNTS(I) THEN
            BEGIN
                FOR J := 10 STEP -1 UNTIL I + 1 DO
                BEGIN
                    MAXCOUNTS(J) := MAXCOUNTS(J - 1);
                    MAXWORDS(J) :- MAXWORDS(J - 1);
                END;
                MAXCOUNTS(I) := VAL.COUNT;
                MAXWORDS(I) :- KEY;
                GO TO BREAK;
            END;
        END;
    BREAK:
    END;

    COMMENT OUTPUT 10 MOST COMMON WORDS ;

    FOR I := 1 STEP 1 UNTIL 10 DO
    BEGIN
        IF MAXWORDS(I) =/= NONE THEN
        BEGIN
            OUTINT(MAXCOUNTS(I), 10);
            OUTTEXT(" ");
            OUTTEXT(MAXWORDS(I) QUA TEXTHASHKEY.T);
            OUTIMAGE;
        END;
    END;

END


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

namespace WieferichPrimes {
    class Program {
        static long ModPow(long @base, long exp, long mod) {
            if (mod == 1) {
                return 0;
            }

            long result = 1;
            @base %= mod;
            for (; exp > 0; exp >>= 1) {
                if ((exp & 1) == 1) {
                    result = (result * @base) % mod;
                }
                @base = (@base * @base) % mod;
            }
            return result;
        }

        static bool[] PrimeSieve(int limit) {
            bool[] sieve = Enumerable.Repeat(true, limit).ToArray();

            if (limit > 0) {
                sieve[0] = false;
            }
            if (limit > 1) {
                sieve[1] = false;
            }

            for (int i = 4; i < limit; i += 2) {
                sieve[i] = false;
            }

            for (int p = 3; ; p += 2) {
                int q = p * p;
                if (q >= limit) {
                    break;
                }
                if (sieve[p]) {
                    int inc = 2 * p;
                    for (; q < limit; q += inc) {
                        sieve[q] = false;
                    }
                }
            }

            return sieve;
        }

        static List<int> WiefreichPrimes(int limit) {
            bool[] sieve = PrimeSieve(limit);
            List<int> result = new List<int>();
            for (int p = 2; p < limit; p++) {
                if (sieve[p] && ModPow(2, p - 1, p * p) == 1) {
                    result.Add(p);
                }
            }
            return result;
        }

        static void Main() {
            const int limit = 5000;
            Console.WriteLine("Wieferich primes less that {0}:", limit);
            foreach (int p in WiefreichPrimes(limit)) {
                Console.WriteLine(p);
            }
        }
    }
}


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Wireworld is
   type Cell is (' ', 'H', 't', '.');
   type Board is array (Positive range <>, Positive range <>) of Cell;
      -- Perform one transition of the cellular automation
   procedure Wireworld (State : in out Board) is
      function "abs" (Left : Cell) return Natural is
      begin
         if Left = 'H' then
            return 1;
         else
            return 0;
         end if;
      end "abs";
      Above   : array (State'Range (2)) of Cell := (others => ' ');
      Left    : Cell := ' ';
      Current : Cell;
   begin
      for I in State'First (1) + 1..State'Last (1) - 1 loop
         for J in State'First (2) + 1..State'Last (2) - 1 loop
            Current := State (I, J);
            case Current is
               when ' ' =>
                  null;
               when 'H' =>
                  State (I, J) := 't';
               when 't' =>
                  State (I, J) := '.';
               when '.' =>
                  if abs Above (       J - 1) + abs Above (       J) + abs Above (       J + 1) +
                     abs Left                                        + abs State (I,     J + 1) +
                     abs State (I + 1, J - 1) + abs State (I + 1, J) + abs State (I + 1, J + 1)
                  in 1..2 then
                     State (I, J) := 'H';
                  else
                     State (I, J) := '.';
                  end if;
            end case;
            Above (J - 1) := Left;
            Left := Current;
         end loop;
      end loop;
   end Wireworld;
      -- Print state of the automation
   procedure Put (State : Board) is
   begin
      for I in State'First (1) + 1..State'Last (1) - 1 loop
         for J in State'First (2) + 1..State'Last (2) - 1 loop
            case State (I, J) is
               when ' ' => Put (' ');
               when 'H' => Put ('H');
               when 't' => Put ('t');
               when '.' => Put ('.');
            end case;
         end loop;
         New_Line;
      end loop;
   end Put;
   Oscillator : Board := ("         ", "  tH     ", " .  .... ", "  ..     ", "         ");
begin
   for Step in 0..9 loop
      Put_Line ("Step" & Integer'Image (Step) & " ---------"); Put (Oscillator);
      Wireworld (Oscillator);
   end loop;
end Test_Wireworld;


    Dim newForm as new Form
    newForm.Text = "It's a new window"

        newForm.Show()


import "dome" for Window

class EmptyWindow {
    construct new(width, height) {
        Window.title = "Empty window"
        Window.resize(width, height)
    }

    init() {}

    update() {}

    draw(alpha) {}
}

var Game = EmptyWindow.new(600, 600)


;GTK imports and defines etc.
%define GTK_WINDOW_TOPLEVEL 0

extern gtk_init
extern gtk_window_new
extern gtk_widget_show
extern gtk_signal_connect
extern gtk_main
extern g_print
extern gtk_main_quit

bits 32

section .text
	global _main

        ;exit signal
	sig_main_exit:
		push exit_sig_msg
		call g_print
		add esp, 4
		call gtk_main_quit
		ret

	_main:
		mov ebp, esp
		sub esp, 8
		push argv
		push argc
		call gtk_init
		add esp, 8				;stack alignment.
		push GTK_WINDOW_TOPLEVEL
		call gtk_window_new
		add esp, 4
		mov [ebp-4], eax		;ebp-4 now holds our GTKWindow pointer.
		push 0
		push sig_main_exit
		push gtk_delete_event
		push dword [ebp-4]
		call gtk_signal_connect
		add esp, 16
		push dword [ebp-4]
		call gtk_widget_show
		add esp, 4
		call gtk_main

section .data
;sudo argv
argc                dd 1
argv                dd args
args                dd title
						  dd 0

title               db "GTK Window",0
gtk_delete_event   db 'delete_event',0
exit_sig_msg      db "-> Rage quitting..",10,0


open window 400,200  //minimum line required to accomplish the indicated task
clear screen
text 200,100,"I am a window - close me!","cc"
end


import Foundation

func printTopWords(path: String, count: Int) throws {
    // load file contents into a string
    let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
    var dict = Dictionary<String, Int>()
    // split text into words, convert to lowercase and store word counts in dict
    let regex = try NSRegularExpression(pattern: "\\w+")
    regex.enumerateMatches(in: text, range: NSRange(text.startIndex..., in: text)) {
        (match, _, _) in
        guard let match = match else { return }
        let word = String(text[Range(match.range, in: text)!]).lowercased()
        dict[word, default: 0] += 1
    }
    // sort words by number of occurrences
    let wordCounts = dict.sorted(by: {$0.1 > $1.1})
    // print the top count words
    print("Rank\tWord\tCount")
    for (i, (word, n)) in wordCounts.prefix(count).enumerated() {
        print("\(i + 1)\t\(word)\t\(n)")
    }
}

do {
    try printTopWords(path: "135-0.txt", count: 10)
} catch {
    print(error.localizedDescription)
}


lassign $argv head
while { [gets stdin line] >= 0 } {
    foreach word [regexp -all -inline {[A-Za-z]+} $line] {
        dict incr wordcount [string tolower $word]
    }
}

set sorted [lsort -stride 2 -index 1 -int -decr $wordcount]
foreach {word count} [lrange $sorted 0 [expr {$head * 2 - 1}]] {
    puts "$count\t$word"
}


/* Input format: N text                                         */
/* Only lowercase letters can constitute a word in text.        */
/* (c) 2020, Andrii Makukha, 2-clause BSD licence.              */

progrm: readn/error
        table(freq) table(chain) [firstword = ~0]
loop:   not(!<<>>) output
    |   [j=777] batch/loop loop;                   /* Main loop */

/* To use less stack, divide input into batches.                */
/* (Avoid interpreting entire input as a single "sentence".)    */
batch:  [j<=0?] succ
     |  word/skip [j--] skip batch;
skip:   string(other);
not:    params(1) (any($1) fail | ());
readn:  string(!<<0123456789>>) readint(n) skip;
error:  diag(( ={ <ERROR: input must start with a number> * } ));

/* Process a word */
word:   smark any(letter) string(letter) scopy
        locate/new
        [freq[k]++] newmax;
locate: find(freq, k);
new:    enter(freq, k)
        [freq[k] = 1] newmax
        [firstword = firstword==~0 ? k : firstword]
        enter(chain, i) [chain[i]=prevword] [prevword=k];
newmax: [max = max<freq[k] ? freq[k] : max];

/* Output logic */
output: [next=max]
outmax: [max=next] [next=0] [max>0?] [j = prevword] cycle/outmax;
cycle:  [i = j] [k = freq[i]] [n>0?]
        ( [max==freq[i]?] parse(wn)
        | [(freq[i]<max) & (next<freq[i])?] [next = freq[i]]
        | ())
        [i != firstword?] [j = chain[i]] cycle;
wn:     getnam(freq, i) [k = freq[i]] decimal(k) [n--]
        = { 2 < > 1 * };

/* Reads decimal integer */
readint:  proc(n;i) ignore(<<>>) [n=0] inta
int1:     [n = n*12+i] inta\int1;
inta:     char(i) [i<72?] [(i =- 60)>=0?];

/* Variables */
prevword:   0;  /* Head of the linked list */
firstword:  0;  /* First word's index to know where to stop output */
k: 0;
i: 0;
j: 0;
n: 0;           /* Number of most frequent words to display */
max:  0;        /* Current highest number of occurrences */
next: 0;        /* Next highest number of occurrences */

/* Tables */
freq:   0;
chain:  0;

/* Character classes */
letter:   <<abcdefghijklmnopqrstuvwxyz>>;
other:   !<<abcdefghijklmnopqrstuvwxyz>>;


// Weiferich primes: Nigel Galloway. June 2nd., 2021
primes32()|>Seq.takeWhile((>)5000)|>Seq.filter(fun n->(2I**(n-1)-1I)%(bigint(n*n))=0I)|>Seq.iter(printfn "%d")


USING: io kernel math math.functions math.primes prettyprint
sequences ;

"Wieferich primes less than 5000:" print
5000 primes-upto [ [ 1 - 2^ 1 - ] [ sq divisor? ] bi ] filter .


Func Iswief(p)=Isprime(p)*Divides(p^2, 2^(p-1)-1).
for i=2 to 5000 do if Iswief(i) then !!i fi od


: prime? ( n -- ? ) here + [email protected] 0= ;
: notprime! ( n -- ) here + 1 swap c! ;

: prime_sieve { n -- }
  here n erase
  0 notprime!
  1 notprime!
  n 4 > if
    n 4 do i notprime! 2 +loop
  then
  3
  begin
    dup dup * n <
  while
    dup prime? if
      n over dup * do
        i notprime!
      dup 2* +loop
    then
    2 +
  repeat
  drop ;

: modpow { c b a -- a^b mod c }
  c 1 = if 0 exit then
  1
  a c mod to a
  begin
    b 0>
  while
    b 1 and 1 = if
      a * c mod
    then
    a a * c mod to a
    b 2/ to b
  repeat ;

: wieferich_prime? { p -- ? }
  p prime? if
    p p * p 1- 2 modpow 1 =
  else
    false
  then ;

: wieferich_primes { n -- }
  ." Wieferich primes less than " n 1 .r ." :" cr
  n prime_sieve
  n 0 do
    i wieferich_prime? if
      i 1 .r cr
    then
  loop ;

5000 wieferich_primes
bye


#include "isprime.bas"

function iswief( byval p as uinteger ) as boolean
    if not isprime(p) then return 0
    dim as integer q = 1, p2 = p^2
    while p>1
        q=(2*q) mod p2
        p = p - 1
    wend
    if q=1 then return 1 else return 0
end function

for i as uinteger = 1 to 5000
    if iswief(i) then print i
next i


package main

import (
    "fmt"
    "math/big"
    "rcu"
)

func main() {
    primes := rcu.Primes(5000)
    zero := new(big.Int)
    one := big.NewInt(1)
    num := new(big.Int)
    fmt.Println("Wieferich primes < 5,000:")
    for _, p := range primes {
        num.Set(one)
        num.Lsh(num, uint(p-1))
        num.Sub(num, one)
        den := big.NewInt(int64(p * p))
        if num.Rem(num, den).Cmp(zero) == 0 {
            fmt.Println(rcu.Commatize(p))
        }
    }
}


CO
Wireworld implementation.
CO

PROC exception = ([]STRING args)VOID:(
  putf(stand error, ($"Exception"$, $", "g$, args, $l$));
  stop
);

PROC assertion error = (STRING message)VOID:exception(("assertion error", message));

MODE CELL = CHAR;
MODE WORLD = FLEX[0, 0]CELL;
CELL head="H", tail="t", conductor=".", empty = " ";
STRING all states := empty;

BOOL wrap = FALSE; # is the world round? #

STRING nl := REPR 10;

STRING in string :=
  "tH........."+nl+
  ".   ."+nl+
  "   ..."+nl+
  ".   ."+nl+
  "Ht.. ......"+nl
;

OP +:= = (REF FLEX[]FLEX[]CELL lines, FLEX[]CELL line)VOID:(
      [UPB lines + 1]FLEX[0]CELL new lines;
      new lines[:UPB lines]:=lines;
      lines := new lines;
      lines[UPB lines]:=line
);

PROC read file = (REF FILE in file)WORLD: (
    # file > initial world configuration" #
    FLEX[0]CELL line;
    FLEX[0]FLEX[0]CELL lines;
    INT upb x:=0, upb y := 0;
    BEGIN
      # on physical file end(in file, exit read line); #
      make term(in file, nl);
      FOR x TO 5 DO
        get(in file, (line, new line));
        upb x := x;
        IF UPB line > upb y THEN upb y := UPB line FI;
        lines +:= line
      OD;
    exit read line: SKIP
    END;
    [upb x, upb y]CELL out;
    FOR x TO UPB out DO
      out[x,]:=lines[x]+" "*(upb y-UPB lines[x])
    OD;
    out
);

PROC new cell = (WORLD current world, INT x, y)CELL: (
    CELL istate := current world[x, y];
    IF INT pos; char in string (istate, pos, all states); pos IS REF INT(NIL) THEN
        assertion error("Wireworld cell set to unknown value "+istate) FI;
    IF istate = head THEN
        tail
    ELIF istate = tail THEN
        conductor
    ELIF istate = empty THEN
        empty
    ELSE # istate = conductor #
        [][]INT dxy list = ( (-1,-1), (-1,+0), (-1,+1),
                             (+0,-1),          (+0,+1),
                             (+1,-1), (+1,+0), (+1,+1) );
        INT n := 0;
        FOR enum dxy TO UPB dxy list DO
          []INT dxy = dxy list[enum dxy];
          IF wrap THEN
            INT px = ( x + dxy[1] - 1 ) MOD 1 UPB current world + 1;
            INT py = ( y + dxy[2] - 1 ) MOD 2 UPB current world + 1;
            n +:= ABS (current world[px, py] = head)
          ELSE
            INT px = x + dxy[1];
            INT py = y + dxy[2];
            IF px >= 1 LWB current world AND px <= 1 UPB current world AND
               py >= 2 LWB current world AND py <= 2 UPB current world THEN
                 n +:= ABS (current world[px, py] = head)
            FI
          FI
        OD;
        IF 1 <= n AND n <= 2 THEN head ELSE conductor FI
    FI
);

PROC next gen = (WORLD world)WORLD:(
    # compute next generation of wireworld #
    WORLD new world := world;
    FOR x TO 1 UPB world DO
        FOR y TO 2 UPB world DO
            new world[x,y] := new cell(world, x, y)
        OD
    OD;
    new world
);

PROC world2string = (WORLD world) STRING:(
    STRING out:="";
    FOR x TO UPB world DO
      out +:= world[x,]+nl
    OD;
    out
);

FILE in file;
associate(in file, in string);

WORLD ww := read file(in file);
close(in file);

FOR gen TO 10 DO
    printf ( ($lg(-3)" "$, gen-1,  $g$,"="* (2 UPB ww-4), $l$));
    print ( world2string(ww) );
    ww := next gen(ww)
OD


#!/bin/sh
<"$1" tr -cs A-Za-z '\n' | tr A-Z a-z | LC_ALL=C sort | uniq -c | sort -rn | head -n "$2"