First commit of partial RosettaCode contents.

Pushing this for testing purposes. Lots of work still needed.
This commit is contained in:
Ingy döt Net 2013-04-08 13:02:41 -07:00
commit 1e05ecd7ee
781 changed files with 9080 additions and 0 deletions

View file

@ -0,0 +1,13 @@
In this puzzle, write code to print out the entire "99 bottles of beer on the wall" song. For those who do not know the song, the lyrics follow this form:
X bottles of beer on the wall
X bottles of beer
Take one down, pass it around
X-1 bottles of beer on the wall
X-1 bottles of beer on the wall
...
Take one down, pass it around
0 bottles of beer on the wall
Where X and X-1 are replaced by numbers of course. Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too).
See also: http://99-bottles-of-beer.net/

View file

@ -0,0 +1,7 @@
{ i = 99
while (i > 0)
{print i, " bottles of beer on the wall,"
print i, " bottles of beer."
print "Take one down, pass it around,"
i--
print i, " bottles of beer on the wall\n"}}

View file

@ -0,0 +1,7 @@
FOR x = 99 TO 1 STEP -1
PRINT x; "bottles of beer on the wall"
PRINT x; "bottles of beer"
PRINT "Take one down, pass it around"
PRINT x-1; "bottles of beer on the wall"
PRINT
NEXT x

View file

@ -0,0 +1,12 @@
PLAY "<"
FOR x = 99 TO 0 STEP -1
PRINT x; "bottles of beer on the wall"
PRINT x; "bottles of beer"
PRINT "Take one down, pass it around"
PRINT x-1; "bottles of beer on the wall"
PRINT
PLAY "e-8e-8e-8<b-8b-8b-8>e-8e-8e-8e-4"'X bottles of beer on the wall
PLAY "f8f8f8c8c8c8f4"'X bottles of beer
PLAY "d4d8d8 N0 d8d8d8d4"'take one down, pass it around
PLAY "<a+8a+8a+8>c8c8d8d+8d+8d+8d+4"'X-1 bottles of beer on the wall
NEXT x

View file

@ -0,0 +1,11 @@
<v <.g10" bottles of beer on the wall"+*4310 <
c>:,|
<v <.g10" bottles of beer"+*4310
>:,|
<v <"take one down, pass it around"+*4310
>:,|
>01g1-:01p v
v <.g10" bottles of beer on the wall"+*4310<
>:,|
>134*+0` |
@

View file

@ -0,0 +1,5 @@
#include <stdio.h>
main(){_=100;while(--_)printf("%i bottle%s of beer in the wall,\n%i bottle%"
"s of beer.\nTake one down, pass it round,\n%s%s\n\n",_,_-1?"s":"",_,_-1?"s"
:"",_-1?(char[]){(_-1)/10?(_-1)/10+48:(_-1)%10+48,(_-1)/10?(_-1)%10+48:2+30,
(_-1)/10?32:0,0}:"",_-1?"bottles of beer in the wall":"No more beers");}

View file

@ -0,0 +1,30 @@
#include <stdlib.h>
#include <stdio.h>
#define BOTTLE(nstr) nstr " bottles of beer"
#define WALL(nstr) BOTTLE(nstr) " on the wall"
#define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \
"\nTake one down, pass it around\n"
#define PART2(nstr) WALL(nstr) "\n\n"
#define MIDDLE(nstr) PART2(nstr) PART1(nstr)
#define SONG PART1("100") CD2 PART2("0")
#define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \
CD3("4") CD3("3") CD3("2") CD3("1") CD4("")
#define CD3(pre) CD4(pre) MIDDLE(pre "0")
#define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \
MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \
MIDDLE(pre "2") MIDDLE(pre "1")
int main(void)
{
(void) printf(SONG);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,35 @@
int b =99,u =1;
#include<stdio.h>
char *d[16],y[]
= "#:ottle/ of"
":eer_ a_Go<o5"
"st>y\x20some6"
"_Take8;down4p"
"a=1rou7_17 _<"
"h;_ m?_nd_ on"
"_085wal" "l_ "
"b_e _ t_ss it"
"_?4bu_ore_9, "
"\060.""@, 9$";
# define x c ^=
#include <string.h>
#define or(t,z) else\
if(c==t && !(c = 0) &&\
(c =! z)); int p(char *t)
{ char *s = t; int c; for (
d[c = 0] = y; !t && (d[c +1
]= strchr(s = d[c], '_'));*
(d[++c]++) = 0); for(t = s?
s:t;(c= *s++); c && putchar
(c)) { if (!((( x 48)& ~0xf
) && ( x 48)) ) p(d[c]), c=
0 ; or('$', p(b - 99?".\n":
"." ) && p(b - 99? t : ""))
or ('\x40', c && p( d[!!b--
+ 2])) or('/', c && p( b^1?
"s": "")) or ('\043', b++ ?
p("So6" + --b):!printf("%d"
, b ? --b : (b += 99))) or(
'S',!(++u % 3) * 32+ 78) or
('.', puts("."))}return c;}
int main() {return p(0);}

View file

@ -0,0 +1,15 @@
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
unsigned int bottles = 99;
do
{
printf("%u bottles of beer on the wall\n", bottles);
printf("%u bottles of beer\n", bottles);
printf("Take one down, pass it around\n");
printf("%u bottles of beer on the wall\n\n", --bottles);
} while(bottles > 0);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,14 @@
(defn verse
[n]
(printf "%d bottles of beer on the wall,
%d bottles of beer,
Take one down, pass it around,
%d bottles of beer on the wall.\n\n"
n
n
(dec n)))
(defn sing
[start]
(doseq [n (range start 0 -1)]
(verse n)))

View file

@ -0,0 +1,4 @@
for j in [99..1]
x=''
x += [j,j-1,'\nTake one down, pass it around\n'," bottles of beer",' on the wall\n'][i] for i in [0,3,4,0,3,2,1,3,4]
console.log x.replace /(1.+)s/g, '$1'

View file

@ -0,0 +1 @@
console.log( if (j+2)%4 then (x=Math.round j/4)+" bottle#{if x-1 then 's' else ''} of beer#{if (j+1)%4 then ' on the wall' else ''}" else "Take one down, pass it around" ) for j in [396..1]

View file

@ -0,0 +1 @@
((console.log if i is 2 then "Take one down, pass it around" else "#{b-!(i-1%4)} bottle#{if 4*b+i<10 and b-i then '' else 's'} of beer#{if i%3 then ' on the wall' else ''}") for i in [4..1]) for b in [99..1]

View file

@ -0,0 +1,9 @@
bottlesOfBeer = (n) ->
"#{n} bottle#{if n is 1 then '' else 's'} of beer"
console.log """
#{bottlesOfBeer n} on the wall
#{bottlesOfBeer n}
Take one down, pass it around
#{bottlesOfBeer n - 1} on the wall
\n""" for n in [99..1]

View file

@ -0,0 +1,39 @@
-module(beersong).
-export([sing/0]).
-define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99
bottles of beer on the wall.~n").
-define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s of
beer on the wall.~n~n").
create_verse(0) -> {0, io_lib:format(?TEMPLATE_0, phrase(0))};
create_verse(Bottle) -> {Bottle, io_lib:format(?TEMPLATE_N, phrase(Bottle))}.
phrase(0) -> ["No more bottles", "no more bottles"];
phrase(1) -> ["1 bottle", "1 bottle", "no more bottles"];
phrase(2) -> ["2 bottles", "2 bottles", "1 bottle"];
phrase(Bottle) -> lists:duplicate(2, integer_to_list(Bottle) ++ " bottles") ++
[integer_to_list(Bottle-1) ++ " bottles"].
bottles() -> lists:reverse(lists:seq(0,99)).
sing() ->
lists:foreach(fun spawn_singer/1, bottles()),
sing_verse(99).
spawn_singer(Bottle) ->
Pid = self(),
spawn(fun() -> Pid ! create_verse(Bottle) end).
sing_verse(Bottle) ->
receive
{_, Verse} when Bottle == 0 ->
io:format(Verse);
{N, Verse} when Bottle == N ->
io:format(Verse),
sing_verse(Bottle-1)
after
3000 ->
io:format("Verse not received - re-starting singer~n"),
spawn_singer(Bottle),
sing_verse(Bottle)
end.

View file

@ -0,0 +1,14 @@
:noname dup . ." bottles" ;
:noname ." 1 bottle" ;
:noname ." no more bottles" ;
create bottles , , ,
: .bottles dup 2 min cells bottles + @ execute ;
: .beer .bottles ." of beer" ;
: .wall .beer ." on the wall" ;
: .take ." Take one down, pass it around" ;
: .verse .wall cr .beer cr
1- .take cr .wall cr ;
: verses begin cr .verse ?dup 0= until ;
99 verses

View file

@ -0,0 +1,24 @@
program bottlestest
implicit none
integer :: i
character(len=*), parameter :: bwall = " on the wall", &
bottles = "bottles of beer", &
bottle = "bottle of beer", &
take = "Take one down, pass it around", &
form = "(I0, ' ', A)"
do i = 99,0,-1
if ( i /= 1 ) then
write (*,form) i, bottles // bwall
if ( i > 0 ) write (*,form) i, bottles
else
write (*,form) i, bottle // bwall
write (*,form) i, bottle
end if
if ( i > 0 ) write (*,*) take
end do
end program bottlestest

View file

@ -0,0 +1,18 @@
package main
import "fmt"
func main() {
cardinality := func (i int) string {
if i!=1 {
return "s"
}
return ""
}
for i := 99; i > 0; i-- {
fmt.Printf("%d bottle%s of beer on the wall\n", i, cardinality(i))
fmt.Printf("%d bottle%s of beer\n", i, cardinality(i))
fmt.Printf("Take one down, pass it around\n")
fmt.Printf("%d bottle%s of beer on the wall\n", i-1, cardinality(i-1))
}
}

View file

@ -0,0 +1,16 @@
import qualified Char
main = putStr $ concat
[up (bob n) ++ wall ++ ", " ++ bob n ++ ".\n" ++
pass n ++ bob (n - 1) ++ wall ++ ".\n\n" |
n <- [99, 98 .. 0]]
where bob n = (num n) ++ " bottle" ++ (s n) ++ " of beer"
wall = " on the wall"
pass 0 = "Go to the store and buy some more, "
pass _ = "Take one down and pass it around, "
up (x : xs) = Char.toUpper x : xs
num (-1) = "99"
num 0 = "no more"
num n = show n
s 1 = ""
s _ = "s"

View file

@ -0,0 +1,28 @@
{-# LANGUAGE TemplateHaskell #-}
-- build with "ghc --make beer.hs"
module Main where
import Language.Haskell.TH
import Control.Monad.Writer
-- This is calculated at compile time, and is equivalent to
-- songString = "99 bottles of beer on the wall\n99 bottles..."
songString =
$(let
sing = tell -- we can't sing very well...
someBottles 1 = "1 bottle of beer "
someBottles n = show n ++ " bottles of beer "
bottlesOfBeer n = (someBottles n ++)
verse n = do
sing $ n `bottlesOfBeer` "on the wall\n"
sing $ n `bottlesOfBeer` "\n"
sing $ "Take one down, pass it around\n"
sing $ (n - 1) `bottlesOfBeer` "on the wall\n\n"
song = execWriter $ mapM_ verse [99,98..1]
in return $ LitE $ StringL $ song)
main = putStr songString

View file

@ -0,0 +1,7 @@
main = mapM_ (putStrLn . beer) [99, 98 .. 0]
beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around"
beer 0 = "better go to the store and buy some more."
beer v = show v ++ " bottles of beer on the wall\n"
++ show v
++" bottles of beer\nTake one down, pass it around\n"
++ head (lines $ beer $ v-1) ++ "\n"

View file

@ -0,0 +1,16 @@
public class Beer
{
public static void main(final String[] args)
{
int beer = 99;
StringBuilder sb = new StringBuilder();
String data[] = new String[] { " bottles of beer on the wall\n",
" bottles of beer.\nTake one down, pass it around,\n",
"Better go to the store and buy some more." };
while (beer > 0)
sb.append(beer).append(data[0]).append(beer).append(data[1]).append(--beer).append(data[0]).append("\n");
System.out.println(sb.append(data[2]).toString());
}
}

View file

@ -0,0 +1,40 @@
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Beer extends JFrame implements ActionListener{
private int x;
private JButton take;
private JTextArea text;
public static void main(String[] args){
new Beer();//build and show the GUI
}
public Beer(){
x= 99;
take= new JButton("Take one down, pass it around");
text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");
text.setEditable(false);//so they can't change the text after it's displayed
take.addActionListener(this);//listen to the button
setLayout(new BorderLayout());//handle placement of components
add(text, BorderLayout.CENTER);//put the text area in the largest section
add(take, BorderLayout.SOUTH);//put the button underneath it
pack();//auto-size the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...)
setVisible(true);//show it
}
public void actionPerformed(ActionEvent arg0){
if(arg0.getSource() == take){//if they clicked the button
JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text
}
if(x == 0){//if it's the end
dispose();//end
}
}
}

View file

@ -0,0 +1,20 @@
import java.text.MessageFormat;
public class Beer
{
static String bottles(final int n)
{
return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n);
}
public static void main(final String[] args)
{
String byob = bottles(99);
for (int x = 99; x > 0;)
{
System.out.println(byob + " on the wall");
System.out.println(byob);
System.out.println("Take one down, pass it around");
byob = bottles(--x);
System.out.println(byob + " on the wall\n");
}
}
}

View file

@ -0,0 +1,2 @@
// Line breaks are in HTML
var beer; while ((beer = typeof beer === "undefined" ? 99 : beer) > 0) document.write( beer + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall<br>" + beer + " bottle" + (beer != 1 ? "s" : "") + " of beer<br>Take one down, pass it around<br>" + (--beer) + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall<br>" );

View file

@ -0,0 +1,21 @@
// Line breaks are in HTML
function Bottles(count){
this.count = (!!count)?count:99;
this.knock = function(){
var c = document.createElement('div');
c.id="bottle-"+this.count;
c.innerHTML = "<p>"+this.count+" bottles of beer on the wall</p>"
+"<p>"+this.count+" bottles of beer!</p>"
+"<p>Take one down,<br>Pass it around</p>"
+"<p>"+(--this.count)+" bottles of beer on the wall</p><p><br></p>";
document.body.appendChild(c);
}
this.sing = function(){
while (this.count>0) { this.knock(); }
}
}
(function(){
var bar = new Bottles(99);
bar.sing();
})();

View file

@ -0,0 +1,18 @@
function bottleSong(n) {
if (!isFinite(Number(n)) || n == 0) n = 100;
var a = '%% bottles of beer',
b = ' on the wall',
c = 'Take one down, pass it around',
r = '<br>'
p = document.createElement('p'),
s = [],
re = /%%/g;
while(n) {
s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n));
}
p.innerHTML = s.join(r+r);
document.body.appendChild(p);
}
window.onload = bottleSong;

View file

@ -0,0 +1,10 @@
// Line breaks are in HTML
var beer = 99;
while (beer > 0)
{
document.write( beer + " bottles of beer on the wall<br>" );
document.write( beer + " bottles of beer<br>" );
document.write( "Take one down, pass it around<br>" );
document.write( (beer - 1) + " bottles of beer on the wall<br>" );
beer--;
}

View file

@ -0,0 +1,23 @@
\documentclass{article}
\newcounter{beer}
\newcounter{showC}
\newcommand{\verses}[1]{
\setcounter{beer}{#1}
\loop
\par\noindent
\Roman{beer} bottles of beer on the wall,\\
\Roman{beer} bottles of beer!\\
Take one down, pass it around---\\
\addtocounter{beer}{-1}
% Romans didn't know how to write zero ;-)
\ifnum\value{beer}=0 ZERO \else\Roman{beer} \fi
bottles of beer on the wall!\\
\ifnum\value{beer}>0
\repeat
}
\begin{document}
\verses{99}
\end{document}

View file

@ -0,0 +1,20 @@
\documentclass{article}
\newcounter{beer}
\newcommand{\verses}[1]{
\setcounter{beer}{#1}
\par\noindent
\arabic{beer} bottles of beer on the wall,\\
\arabic{beer} bottles of beer!\\
Take one down, pass it around---\\
\addtocounter{beer}{-1}
\arabic{beer} bottles of beer on the wall!\\
\ifnum#1>0
\verses{\value{beer}}
\fi
}
\begin{document}
\verses{99}
\end{document}

View file

@ -0,0 +1,11 @@
local bottles = 99
local function plural (bottles) if bottles == 1 then return '' end return 's' end
while bottles > 0 do
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print (bottles..' bottle'..plural(bottles)..' of beer')
print ('Take one down, pass it around')
bottles = bottles - 1
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print ()
end

View file

@ -0,0 +1,13 @@
<?php
foreach(range(99,1) as $i) {
$p = ($i>1)?"s":"";
echo <<< EOV
$i bottle$p of beer on the wall
$i bottle$p of beer
Take one down, pass it around
EOV;
}
echo "No more Bottles of beer on the wall";
?>

View file

@ -0,0 +1,18 @@
<?php
$verse = <<<VERSE
100 bottles of beer on the wall,
100 bottles of beer!
Take one down, pass it around!
99 bottles of beer on the wall!
VERSE;
foreach (range(1,99) as $i) { // loop 99 times
$verse = preg_replace('/\d+/e', '$0 - 1', $verse);
$verse = preg_replace('/\b1 bottles/', '1 bottle', $verse);
$verse = preg_replace('/\b0 bottle/', 'No bottles', $verse);
echo $verse;
}
?>

View file

@ -0,0 +1,7 @@
<?php
for($i=100;$i>0;$i--){
$p2=$i." bottle".(($i>1)?"s":"")." of beer";
$p1=$p2." on the wall\n";
$p3="Take one down, pass it around\n";
echo (($i<100)?$p1."\n":"").$p1.$p2."\n".$p3.(($i<2)?($i-1).substr($p1,1,28):"");
}

View file

@ -0,0 +1,15 @@
<?php
$plural = 's';
foreach (range(99, 1) as $i) {
echo "$i bottle$plural of beer on the wall,\n";
echo "$i bottle$plural of beer!\n";
echo "Take one down, pass it around!\n";
if ($i - 1 == 1)
$plural = '';
if ($i > 1)
echo ($i - 1) . " bottle$plural of beer on the wall!\n\n";
else
echo "No more bottles of beer on the wall!\n";
}
?>

View file

@ -0,0 +1,31 @@
.sub sounding_smart_is_hard_after_drinking_this_many
.param int b
if b == 1 goto ONE
.return(" bottles ")
ONE:
.return(" bottle ")
end
.end
.sub main :main
.local int bottles
.local string b
bottles = 99
LUSH:
if bottles == 0 goto DRUNK
b = sounding_smart_is_hard_after_drinking_this_many( bottles )
print bottles
print b
print "of beer on the wall\n"
print bottles
print b
print "of beer\nTake one down, pass it around\n"
dec bottles
b = sounding_smart_is_hard_after_drinking_this_many( bottles )
print bottles
print b
print "of beer on the wall\n\n"
goto LUSH
DRUNK:
end
.end

View file

@ -0,0 +1,6 @@
for $n (reverse(0..99))
{
$bottles = sprintf("%s bottle%s of beer on the wall\n",(($n==0)?"No":$n), (($n==1)?"":"s"));
print( (($n==99)?"":"$bottles\n") .
(($n==0)?"":(substr(${bottles}x2,0,-12) . "\nTake one down, pass it around\n")) );
}

View file

@ -0,0 +1,14 @@
use 5.10.0;
$num = 99;
while ($num > 0) {
my $s = "s" unless ($num == 1);
say "$num bottle$s of beer on the wall, $num bottle$s of beer";
$num--;
my $s = "s" unless ($num == 1);
$num = "No more" if ($num == 0);
say "Take one down, pass it around, $num bottle$s of beer on the wall\n"
}
say "No more bottles of beer on the wall, no more bottles of beer.";
say "Go to the store and buy some more, 99 bottles of beer on the wall.";

View file

@ -0,0 +1,16 @@
#!/usr/bin/env perl
use strict;
use warnings;
sub bottles() { sprintf qq{%s bottle%s of beer}
, $_ || 'No'
, $_==1 ? '' : 's';
}
sub store() { $_=99; qq{Go to the store, buy some more...\n}; }
sub wall() { qq{ on the wall\n} }
sub take() { $_-- ? qq{Take one down, pass it around\n} : store }
do { print bottles, wall
, bottles, qq{\n}
, take
, bottles, qq{\n\n}
} for reverse 0..99;

View file

@ -0,0 +1,18 @@
#!/usr/bin/perl -w
my $verse = <<"VERSE";
100 bottles of beer on the wall,
100 bottles of beer!
Take one down, pass it around!
99 bottles of beer on the wall!
VERSE
{
$verse =~ s/(\d+)/$1-1/ge;
$verse =~ s/\b1 bottles/1 bottle/g;
my $done = $verse =~ s/\b0 bottle/No bottles/g; # if we make this replacement, we're also done.
print $verse;
redo unless $done;
}

View file

@ -0,0 +1,12 @@
(de bottles (N)
(case N
(0 "No more beer")
(1 "One bottle of beer")
(T (cons N " bottles of beer")) ) )
(for (N 99 (gt0 N))
(prinl (bottles N) " on the wall,")
(prinl (bottles N) ".")
(prinl "Take one down, pass it around,")
(prinl (bottles (dec 'N)) " on the wall.")
(prinl) )

View file

@ -0,0 +1,9 @@
verse = '''\
%i bottles of beer on the wall
%i bottles of beer
Take one down, pass it around
%i bottles of beer on the wall
'''
for bottles in range(99,0,-1):
print verse % (bottles, bottles, bottles-1)

View file

@ -0,0 +1,9 @@
verse = '''\
{some} bottles of beer on the wall
{some} bottles of beer
Take one down, pass it around
{less} bottles of beer on the wall
'''
for bottles in range(99,0,-1):
print verse.format(some=bottles, less=bottles-1)

View file

@ -0,0 +1,2 @@
a, b, c, s = " bottles of beer", " on the wall\n", "Take one down, pass it around\n", str
print "\n".join(s(x)+a+b+s(x)+a+"\n"+c+s(x-1)+a+b for x in xrange(99, 0, -1))

View file

@ -0,0 +1,2 @@
a = lambda n: "%u bottle%s of beer on the wall\n" % (n, "s"[n==1:])
print "\n".join(a(x)+a(x)[:-13]+"\nTake one down, pass it around\n"+a(x-1) for x in xrange(99, 0, -1))

View file

@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""\
{0} {2} of beer on the wall
{0} {2} of beer
Take one down, pass it around
{1} {3} of beer on the wall
"""
print("\n".join(
__doc__.format(
i, i - 1,
"bottle" if i == 1 else "bottles",
"bottle" if i - 1 == 1 else "bottles"
) for i in range(99, 0, -1)
), end="")

View file

@ -0,0 +1,39 @@
ones = (
'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'
)
prefixes = ('thir', 'four', 'fif', 'six', 'seven', 'eigh', 'nine')
tens = ['', '', 'twenty' ]
teens = ['ten', 'eleven', 'twelve']
for prefix in prefixes:
tens.append(prefix + 'ty')
teens.append(prefix +'teen')
tens[4] = 'forty'
def number(num):
"get the wordy version of a number"
ten, one = divmod(num, 10)
if ten == 0 and one == 0:
return 'no'
elif ten == 0:
return ones[one]
elif ten == 1:
return teens[one]
elif one == 0:
return tens[ten]
else:
return "%s-%s" % (tens[ten], ones[one])
def bottles(beer):
"our rephrase"
return "%s bottle%s of beer" % (
number(beer).capitalize(), 's' if beer > 1 else ''
)
onthewall = 'on the wall'
takeonedown = 'Take one down, pass it around'
for beer in range(99, 0, -1):
print bottles(beer), onthewall
print bottles(beer)
print takeonedown
print bottles(beer-1), onthewall
print

View file

@ -0,0 +1,7 @@
for n in xrange(99, 0, -1):
## The formatting performs a conditional check on the variable.
## If it formats the first open for False, and the second for True
print n, 'bottle%s of beer on the the wall.' % ('s', '')[n == 1]
print n, 'bottle%s of beer.' % ('s', '')[n == 1]
print 'Take one down, pass it around.'
print n - 1, 'bottle%s of beer on the wall.\n' % ('s', '')[n - 1 == 1]

View file

@ -0,0 +1,14 @@
def plural(word, amount): # Correctly pluralize a word.
if amount == 1:
return word
else:
return word + 's'
def sing(b, end): # Sing a phrase of the song, for b bottles, ending in end
print b or 'No more', plural('bottle', b), end
for i in range(99, 0, -1):
sing(i, 'of beer on the wall,')
sing(i, 'of beer,')
print 'Take one down, pass it around,'
sing(i-1, 'of beer on the wall.\n')

View file

@ -0,0 +1,19 @@
/*REXX pgm displays words to the song "99 Bottles of Beer on the Wall". */
do j=99 by -1 to 1 /*start countdown | singdown*/
say j 'bottle's(j) "of beer on the wall," /*sing the #bottles of beer.*/
say j 'bottle's(j) "of beer." /* ... and the refrain. */
say 'Take one down, pass it around,' /*get a bottle and share it.*/
n=j-1 /*N is #bottles we have now.*/
if n==0 then n='no' /*use "no" instead of 0. */
say n 'bottle's(n) "of beer on the wall." /*sing beer bottle inventory*/
say /*blank line between verses.*/
end /*j*/
say 'No more bottles of beer on the wall,' /*Finally! The last verse.*/
say 'no more bottles of beer.' /*so sad ... */
say 'Go to the store and buy some more,' /*replenishment of the beer.*/
say '99 bottles of beer on the wall.' /*All is well in the tavern.*/
exit /*we're done & also sloshed.*/
/*───────────────────────────────────S subroutine───────────────────────*/
s: if arg(1)=1 then return ''; return 's' /*a simple pluralizer funct.*/

View file

@ -0,0 +1,12 @@
trace_var :$bottle_num do |val|
$bottles = %Q{#{val == 0 ? 'No more' : val.to_s} bottle#{val == 1 ? '' : 's'}}
end
($bottle_num = 99).times do
puts "#{$bottles} of beer on the wall"
puts "#{$bottles} of beer"
puts "Take one down, pass it around"
$bottle_num -= 1
puts "#{$bottles} of beer on the wall"
puts ""
end

View file

@ -0,0 +1,15 @@
def bottles(of_beer, ending)
puts "#{of_beer} bottle#{ending} of beer on the wall,"
puts "#{of_beer} bottle#{ending} of beer"
puts "Take one down, pass it around!"
end
99.downto(0) do |left|
if left > 1
bottles(left, "s")
elsif left == 1
bottles(left, "")
else
puts "No more bottles of beer on the wall!"
end
end

View file

@ -0,0 +1,14 @@
def bottles(beer, wall = false)
"#{beer>0 ? beer : "no more"} bottle#{"s" if beer!=1} of beer#{" on the wall" if wall}"
end
99.downto(0) do |remaining|
puts "#{bottles(remaining,true).capitalize}, #{bottles(remaining)}."
if remaining==0
print "Go to the store and buy some more"
remaining=100
else
print "Take one down, pass it around"
end
puts ", #{bottles(remaining-1,true)}.\n\n"
end

View file

@ -0,0 +1,13 @@
plural = 's'
99.downto(1) do |i|
puts "#{i} bottle#{plural} of beer on the wall,"
puts "#{i} bottle#{plural} of beer"
puts "Take one down, pass it around!"
plural = '' if i - 1 == 1
if i > 1
puts "#{i-1} bottle#{plural} of beer on the wall!"
puts
else
puts "No more bottles of beer on the wall!"
end
end

View file

@ -0,0 +1,19 @@
/=!/===========!/==+++++++++# +9
| | /=!/=====@/==@@@+@+++++# +48 (itoa)
| | | | /==!/==@@@@=++++# +32 (space)
| | | | | \==@@++\!+++++++++++++\!+++++\
9 9 '9 9' space 'b' 'o' 't'
$@/>@/>@/>@/>@/>========@/>============@/>====@/>++++++++++ \n setup
/====================================loop=====>\!=>\!<<<<<<<< /
\@\@\>cr.@\< ?\<->+++++++++>->+++++++++\ | |
! | | \===-========>=>-==BCD==!\< @\< ?/< ?/# no more beer!
/=|=====|================================/
| | \<++t.<<----a.>----k.<++++e.<_.>>++++o.-n.< e.<_.>-d.>+o.>+++w.<-n.<<_.\
| | / /
| | \>---a.>n.<+++d.<_.>>++p.<---a.>>----s.s.<<<_.>>-------i.>+t.<<<_.\
| | / /
| | \>a.>>--r.<++++++o.>+++u.<-n.<+++d.>>>cr.<-T<+O<--B<<<#
| !
\@\<<<_.>>o.-n.<<_.>>>++t.<<+++h.---e.<_.>>>+++w.<<----a.>--l.l.>>CR.<---T<+++O<+B<<<#
|
\9.>9.>_.>B.>O.>T.t.<---l.<+++e.>>-s.<<<_.>>+++O.<+f.<_.>----b.+++e.E.>>-R.#

View file

@ -0,0 +1,28 @@
proc 0-19 {n} {
lindex {"no more" one two three four five six seven eight nine ten eleven
twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen} $n
}
proc TENS {n} {
lindex {twenty thirty fourty fifty sixty seventy eighty ninety} [expr {$n - 2}]
}
proc num2words {n} {
if {$n < 20} {return [0-19 $n]}
set tens [expr {$n / 10}]
set ones [expr {$n % 10}]
if {$ones == 0} {return [TENS $tens]}
return "[TENS $tens]-[0-19 $ones]"
}
proc get_words {n} {
return "[num2words $n] bottle[expr {$n != 1 ? "s" : ""}] of beer"
}
for {set i 99} {$i > 0} {incr i -1} {
puts [string totitle "[get_words $i] on the wall, [get_words $i]."]
puts "Take one down and pass it around, [get_words [expr {$i - 1}]] on the wall.\n"
}
puts "No more bottles of beer on the wall, no more bottles of beer."
puts "Go to the store and buy some more, 99 bottles of beer on the wall."

View file

@ -0,0 +1,10 @@
set s "s"; set ob "of beer"; set otw "on the wall"; set more "Take one down and pass it around"
for {set n 100} {$n ne "No more"} {} {
switch -- [incr n -1] {
1 {set s ""}
0 {set s "s"; set n "No more"; set more "Go to the store and buy some more"}
}
lappend verse ". $n bottle$s $ob $otw.\n"
lappend verse "\n$n bottle$s $ob $otw, [string tolower $n] bottle$s $ob.\n$more"
}
puts -nonewline [join [lreplace $verse 0 0] ""][lindex $verse 0]

View file

@ -0,0 +1 @@
Two or more words can be composed of the same characters, but in a different order. Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them.

2
Task/Anagrams/1META.yaml Normal file
View file

@ -0,0 +1,2 @@
---
note: Text processing

View file

@ -0,0 +1,26 @@
# JUMBLEA.AWK - words with the most duplicate spellings
# syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT
{ for (i=1; i<=NF; i++) {
w = sortstr(toupper($i))
arr[w] = arr[w] $i " "
n = gsub(/ /,"&",arr[w])
if (max_n < n) { max_n = n }
}
}
END {
for (w in arr) {
if (gsub(/ /,"&",arr[w]) == max_n) {
printf("%s\t%s\n",w,arr[w])
}
}
exit(0)
}
function sortstr(str, i,j,leng) {
leng = length(str)
for (i=2; i<=leng; i++) {
for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) {
str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1)
}
}
return(str)
}

View file

@ -0,0 +1,101 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
typedef struct { const char *key, *word; int cnt; } kw_t;
int lst_cmp(const void *a, const void *b)
{
return strcmp(((const kw_t*)a)->key, ((const kw_t*)b)->key);
}
/* Bubble sort. Faster than stock qsort(), believe it or not */
void sort_letters(char *s)
{
int i, j;
char t;
for (i = 0; s[i] != '\0'; i++) {
for (j = i + 1; s[j] != '\0'; j++)
if (s[j] < s[i]) {
t = s[j]; s[j] = s[i]; s[i] = t;
}
}
}
int main()
{
struct stat s;
char *words, *keys;
size_t i, j, k, longest, offset;
int n_word = 0;
kw_t *list;
int fd = open("unixdict.txt", O_RDONLY);
if (fd == -1) return 1;
fstat(fd, &s);
words = malloc(s.st_size * 2);
keys = words + s.st_size;
read(fd, words, s.st_size);
memcpy(keys, words, s.st_size);
/* change newline to null for easy use; sort letters in keys */
for (i = j = 0; i < s.st_size; i++) {
if (words[i] == '\n') {
words[i] = keys[i] = '\0';
sort_letters(keys + j);
j = i + 1;
n_word ++;
}
}
list = calloc(n_word, sizeof(kw_t));
/* make key/word pointer pairs for sorting */
for (i = j = k = 0; i < s.st_size; i++) {
if (words[i] == '\0') {
list[j].key = keys + k;
list[j].word = words + k;
k = i + 1;
j++;
}
}
qsort(list, n_word, sizeof(kw_t), lst_cmp);
/* count each key's repetition */
for (i = j = k = offset = longest = 0; i < n_word; i++) {
if (!strcmp(list[i].key, list[j].key)) {
++k;
continue;
}
/* move current longest to begining of array */
if (k < longest) {
k = 0;
j = i;
continue;
}
if (k > longest) offset = 0;
while (j < i) list[offset++] = list[j++];
longest = k;
k = 0;
}
/* show the longest */
for (i = 0; i < offset; i++) {
printf("%s ", list[i].word);
if (i < n_word - 1 && strcmp(list[i].key, list[i+1].key))
printf("\n");
}
/* free(list); free(words); */
close(fd);
return 0;
}

160
Task/Anagrams/C/anagrams.c Normal file
View file

@ -0,0 +1,160 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
char *sortedWord(const char *word, char *wbuf)
{
char *p1, *p2, *endwrd;
char t;
int swaps;
strcpy(wbuf, word);
endwrd = wbuf+strlen(wbuf);
do {
swaps = 0;
p1 = wbuf; p2 = endwrd-1;
while (p1<p2) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2--;
}
p1 = wbuf; p2 = p1+1;
while(p2 < endwrd) {
if (*p2 > *p1) {
t = *p2; *p2 = *p1; *p1 = t;
swaps = 1;
}
p1++; p2++;
}
} while (swaps);
return wbuf;
}
static
short cxmap[] = {
0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,
0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,
0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,
0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,
0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,
0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,
0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,
0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,
};
#define CXMAP_SIZE (sizeof(cxmap)/sizeof(short))
int Str_Hash( const char *key, int ix_max )
{
const char *cp;
short mash;
int hash = 33501551;
for (cp = key; *cp; cp++) {
mash = cxmap[*cp % CXMAP_SIZE];
hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));
hash &= 0x3FFFFFFF;
}
return hash % ix_max;
}
typedef struct sDictWord *DictWord;
struct sDictWord {
const char *word;
DictWord next;
};
typedef struct sHashEntry *HashEntry;
struct sHashEntry {
const char *key;
HashEntry next;
DictWord words;
HashEntry link;
short wordCount;
};
#define HT_SIZE 8192
HashEntry hashTable[HT_SIZE];
HashEntry mostPerms = NULL;
int buildAnagrams( FILE *fin )
{
char buffer[40];
char bufr2[40];
char *hkey;
int hix;
HashEntry he, *hep;
DictWord we;
int maxPC = 2;
int numWords = 0;
while ( fgets(buffer, 40, fin)) {
for(hkey = buffer; *hkey && (*hkey!='\n'); hkey++);
*hkey = 0;
hkey = sortedWord(buffer, bufr2);
hix = Str_Hash(hkey, HT_SIZE);
he = hashTable[hix]; hep = &hashTable[hix];
while( he && strcmp(he->key , hkey) ) {
hep = &he->next;
he = he->next;
}
if ( ! he ) {
he = malloc(sizeof(struct sHashEntry));
he->next = NULL;
he->key = strdup(hkey);
he->wordCount = 0;
he->words = NULL;
he->link = NULL;
*hep = he;
}
we = malloc(sizeof(struct sDictWord));
we->word = strdup(buffer);
we->next = he->words;
he->words = we;
he->wordCount++;
if ( maxPC < he->wordCount) {
maxPC = he->wordCount;
mostPerms = he;
he->link = NULL;
}
else if (maxPC == he->wordCount) {
he->link = mostPerms;
mostPerms = he;
}
numWords++;
}
printf("%d words in dictionary max ana=%d\n", numWords, maxPC);
return maxPC;
}
int main( )
{
HashEntry he;
DictWord we;
FILE *f1;
f1 = fopen("unixdict.txt","r");
buildAnagrams(f1);
fclose(f1);
f1 = fopen("anaout.txt","w");
// f1 = stdout;
for (he = mostPerms; he; he = he->link) {
fprintf(f1,"%d:", he->wordCount);
for(we = he->words; we; we = we->next) {
fprintf(f1,"%s, ", we->word);
}
fprintf(f1, "\n");
}
fclose(f1);
return 0;
}

View file

@ -0,0 +1,10 @@
(require '[clojure.java.io :as io])
(def groups
(with-open [r (io/reader wordfile)]
(group-by sort (line-seq r)))
(let [wordlists (sort-by (comp - count) (vals groups)
maxlength (count (first wordlists))]
(doseq [wordlist (take-while #(= (count %) maxlength) wordlists)]
(println wordlist))

View file

@ -0,0 +1,7 @@
> coffee anagrams.coffee
[ 'abel', 'able', 'bale', 'bela', 'elba' ]
[ 'alger', 'glare', 'lager', 'large', 'regal' ]
[ 'angel', 'angle', 'galen', 'glean', 'lange' ]
[ 'caret', 'carte', 'cater', 'crate', 'trace' ]
[ 'elan', 'lane', 'lean', 'lena', 'neal' ]
[ 'evil', 'levi', 'live', 'veil', 'vile' ]

View file

@ -0,0 +1,31 @@
http = require 'http'
show_large_anagram_sets = (word_lst) ->
anagrams = {}
max_size = 0
for word in word_lst
key = word.split('').sort().join('')
anagrams[key] ?= []
anagrams[key].push word
size = anagrams[key].length
max_size = size if size > max_size
for key, variations of anagrams
if variations.length == max_size
console.log variations.join ' '
get_word_list = (process) ->
options =
host: "www.puzzlers.org"
path: "/pub/wordlists/unixdict.txt"
req = http.request options, (res) ->
s = ''
res.on 'data', (chunk) ->
s += chunk
res.on 'end', ->
process s.split '\n'
req.end()
get_word_list show_large_anagram_sets

View file

@ -0,0 +1,29 @@
-module(anagrams).
-compile(export_all).
play() ->
{ok, P} = file:read_file('unixdict.txt'),
D = dict:new(),
E=fetch(string:tokens(binary_to_list(P), "\n"), D),
get_value(dict:fetch_keys(E), E).
fetch([H|T], D) ->
fetch(T, dict:append(lists:sort(H), H, D));
fetch([], D) ->
D.
get_value(L, D) -> get_value(L,D,1,[]).
get_value([H|T], D, N, L) ->
Var = dict:fetch(H,D),
Len = length(Var),
if
Len > N ->
get_value(T, D, Len, [Var]);
Len == N ->
get_value(T, D, Len, [Var | L]);
Len < N ->
get_value(T, D, N, L)
end;
get_value([], _, _, L) ->
L.

View file

@ -0,0 +1,5 @@
def words = new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').text.readLines()
def groups = words.groupBy{ it.toList().sort() }
def bigGroupSize = groups.collect{ it.value.size() }.max()
def isBigAnagram = { it.value.size() == bigGroupSize }
println groups.findAll(isBigAnagram).collect{ it.value }.collect{ it.join(' ') }.join('\n')

View file

@ -0,0 +1,10 @@
import Data.List
groupon f x y = f x == f y
main = do
f <- readFile "./../Puzzels/Rosetta/unixdict.txt"
let words = lines f
wix = groupBy (groupon fst) . sort $ zip (map sort words) words
mxl = maximum $ map length wix
mapM_ (print . map snd) . filter ((==mxl).length) $ wix

View file

@ -0,0 +1,7 @@
*Main> main
["abel","able","bale","bela","elba"]
["caret","carte","cater","crate","trace"]
["angel","angle","galen","glean","lange"]
["alger","glare","lager","large","regal"]
["elan","lane","lean","lena","neal"]
["evil","levi","live","veil","vile"]

View file

@ -0,0 +1,39 @@
package main
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
fmt.Println(err)
return
}
var ma int
m := make(map[string][]string)
for _, word := range strings.Split(string(b), "\n") {
bs := byteSlice(word)
sort.Sort(bs)
k := string(bs)
a := append(m[k], word)
if len(a) > ma {
ma = len(a)
}
m[k] = a
}
for _, a := range m {
if len(a) == ma {
fmt.Println(a)
}
}
}
type byteSlice []byte
func (b byteSlice) Len() int { return len(b) }
func (b byteSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byteSlice) Less(i, j int) bool { return b[i] < b[j] }

View file

@ -0,0 +1,30 @@
import java.net.*;
import java.io.*;
import java.util.*;
public class WordsOfEqChars {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt");
InputStreamReader isr = new InputStreamReader(url.openStream());
BufferedReader reader = new BufferedReader(isr);
Map<String, Collection<String>> anagrams = new HashMap<String, Collection<String>>();
String word;
int count = 0;
while ((word = reader.readLine()) != null) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (!anagrams.containsKey(key))
anagrams.put(key, new ArrayList<String>());
anagrams.get(key).add(word);
count = Math.max(count, anagrams.get(key).size());
}
reader.close();
for (Collection<String> ana : anagrams.values())
if (ana.size() >= count)
System.out.println(ana);
}
}

View file

@ -0,0 +1,20 @@
#!/usr/bin/env js
var anas = {};
var words = read('unixdict.txt').split(/\n/g);
for (var w in words) {
var key = words[w].split("").sort().join('');
if (!(key in anas)) {
anas[key] = [];
}
anas[key].push(words[w]);
}
for (var a in anas) {
if (anas[a].length >= 2) {
print(anas[a]);
}
}
quit();

View file

@ -0,0 +1,73 @@
-- Build the word set
local set = {}
local file = io.open("unixdict.txt")
local str = file:read()
while str do
table.insert(set,str)
str = file:read()
end
-- Build the anagram tree
local tree = {}
for i,word in next,set do
-- Sort a string from lowest char to highest
local function sortString(str)
if #str <= 1 then
return str
end
local less = ''
local greater = ''
local pivot = str:byte(1)
for i = 2, #str do
if str:byte(i) <= pivot then
less = less..(str:sub(i,i))
else
greater = greater..(str:sub(i,i))
end
end
return sortString(less)..str:sub(1,1)..sortString(greater)
end
local sortchar = sortString(word)
if not tree[#word] then tree[#word] = {} end
local node = tree[#word]
for i = 1,#word do
if not node[sortchar:byte(i)] then
node[sortchar:byte(i)] = {}
end
node = node[sortchar:byte(i)]
end
table.insert(node,word)
end
-- Gather largest groups by gathering all groups of current max size and droping gathered groups and increasing max when a new largest group is found
local max = 0
local set = {}
local function recurse (tree)
local num = 0
for i,node in next,tree do
if type(node) == 'string' then
num = num + 1
end
end
if num > max then
set = {}
max = num
end
if num == max then
local newset = {}
for i,node in next,tree do
if type(node) == 'string' then
table.insert(newset,node)
end
end
table.insert(set,newset)
end
for i,node in next,tree do
if type(node) == 'table' then
recurse(node)
end
end
end
recurse (tree)
for i,v in next,set do io.write (i..':\t')for j,u in next,v do io.write (u..' ') end print() end

View file

@ -0,0 +1,13 @@
<?php
$words = explode("\n", file_get_contents('http://www.puzzlers.org/pub/wordlists/unixdict.txt'));
foreach ($words as $word) {
$chars = str_split($word);
sort($chars);
$anagram[implode($chars)][] = $word;
}
$best = max(array_map('count', $anagram));
foreach ($anagram as $ana)
if (count($ana) == $best)
print_r($ana);
?>

View file

@ -0,0 +1,7 @@
use LWP::Simple;
for (split ' ' => get 'http://www.puzzlers.org/pub/wordlists/unixdict.txt')
{push @{$anagram{ join '' => sort split // }}, $_}
$max > @$_ or $max = @$_ for values %anagram;
@$_ >= $max and print "@$_\n" for values %anagram;

View file

@ -0,0 +1,15 @@
use LWP::Simple;
use List::Util qw(max);
my @words = split(' ', get('http://www.puzzlers.org/pub/wordlists/unixdict.txt'));
my %anagram;
foreach my $word (@words) {
push @{ $anagram{join('', sort(split(//, $word)))} }, $word;
}
my $count = max(map {scalar @$_} values %anagram);
foreach my $ana (values %anagram) {
if (@$ana >= $count) {
print "@$ana\n";
}
}

View file

@ -0,0 +1,8 @@
(let Words NIL
(in "unixdict.txt"
(while (line)
(let (Word (pack @) Key (pack (sort @)))
(if (idx 'Words Key T)
(push (car @) Word)
(set Key (list Word)) ) ) ) )
(flip (by length sort (mapcar val (idx 'Words)))) )

View file

@ -0,0 +1,4 @@
(flip
(by length sort
(by '((L) (sort (copy L))) group
(in "unixdict.txt" (make (while (line) (link @)))) ) ) )

View file

@ -0,0 +1,14 @@
import urllib.request, itertools
import time
words = urllib.request.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
print('Words ready')
t0 = time.clock()
anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)]
anagrams.sort(key=len, reverse=True)
count = len(anagrams[0])
for ana in anagrams:
if len(ana) < count:
break
print(ana)
t0 -= time.clock()
print('Finished in %f s' % -t0)

View file

@ -0,0 +1,25 @@
>>> import urllib
>>> from collections import defaultdict
>>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> len(words)
25104
>>> anagram = defaultdict(list) # map sorted chars to anagrams
>>> for word in words:
anagram[tuple(sorted(word))].append( word )
>>> count = max(len(ana) for ana in anagram.itervalues())
>>> for ana in anagram.itervalues():
if len(ana) >= count:
print ana
['angel', 'angle', 'galen', 'glean', 'lange']
['alger', 'glare', 'lager', 'large', 'regal']
['caret', 'carte', 'cater', 'crate', 'trace']
['evil', 'levi', 'live', 'veil', 'vile']
['elan', 'lane', 'lean', 'lena', 'neal']
['abel', 'able', 'bale', 'bela', 'elba']
>>> count
5
>>>

View file

@ -0,0 +1,22 @@
>>> import urllib, itertools
>>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> len(words)
25104
>>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)]
>>> count = max(len(ana) for ana in anagrams)
>>> for ana in anagrams:
if len(ana) >= count:
print ana
['abel', 'able', 'bale', 'bela', 'elba']
['caret', 'carte', 'cater', 'crate', 'trace']
['angel', 'angle', 'galen', 'glean', 'lange']
['alger', 'glare', 'lager', 'large', 'regal']
['elan', 'lane', 'lean', 'lena', 'neal']
['evil', 'levi', 'live', 'veil', 'vile']
>>> count
5
>>>

View file

@ -0,0 +1,12 @@
>>> import urllib.request
>>> from collections import defaultdict
>>> words = urllib.request.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
>>> anagram = defaultdict(list) # map sorted chars to anagrams
>>> for word in words:
anagram[tuple(sorted(word))].append( word )
>>> count = max(len(ana) for ana in anagram.values())
>>> for ana in anagram.values():
if len(ana) >= count:
print ([x.decode() for x in ana])

View file

@ -0,0 +1,33 @@
/*REXX program finds words with the largest set of anagrams (same size).*/
ifid='unixdict.txt'; words=0 /*input file identifier, # words.*/
wL.=0 /*number of words of length L. */
do j=1 while lines(ifid)\==0 /*read each word in file (word=X)*/
x=space(linein(ifid),0) /*pick off a word from the input.*/
L=length(x); if L<3 then iterate /*onesies and twosies can't win. */
words=words+1 /*count of (useable) words. */
@.words=x /*save the word in an array. */
wL.L=wL.L+1; _=wL.L /*counter of words of length L. */
@@.L._=x /*array of words of length L. */
/*sort the letters*/ do ja=1 for L; !.ja=substr(x,ja,1); end
!.0=L; call esort;z=; do jb=1 for L; z=z || !.jb; end
@@s.L._=z /*store the sorted word (letters)*/
@s.words=@@s.L._ /*and also, sorted length L vers.*/
end /*j*/
a.= /*all the anagrams for word X. */
say copies('─',30) words 'words in the dictionary file: ' ifid
n.=0 /*number of anagrams for word X. */
do j=1 for words /*process the usable words found.*/
x=@.j; Lx=length(x); xs=@s.j /*get some vital statistics for X*/
do k=1 for wL.Lx /*process all the words of len L.*/
if xs\==@@s.Lx.k then iterate /*is this a true anagram of X ? */
if x==@@.Lx.k then iterate /*skip doing anagram on itself. */
n.j=n.j+1; a.j=a.j @@.Lx.k /*bump counter, add ──► anagrams.*/
end /*k*/
end /*j*/
m=n.1 /*assume first (len=1) is largest*/
do j=2 to words; m=max(m,n.j); end /*find the maximum anagram count.*/
do k=1 for words; if n.k==m then if word(a.k,1)>@.k then say @.k a.k; end
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────ESORT───────────────────────────────*/
esort:procedure expose !.;h=!.0;do while h>1;h=h%2;do i=1 for !.0-h;j=i;k=h+i
do while !.k<!.j;t=!.j;!.j=!.k;!.k=t;if h>=j then leave;j=j-h;k=k-h;end;end;end;return

View file

@ -0,0 +1,14 @@
require 'open-uri'
anagram = nil
open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
anagram = f.read.split.group_by {|s| s.each_char.sort}
end
count = anagram.each_value.map {|ana| ana.length}.max
anagram.each_value do |ana|
if ana.length >= count
p ana
end
end

View file

@ -0,0 +1,17 @@
require 'open-uri'
anagram = Hash.new {|hash, key| hash[key] = []} # map sorted chars to anagrams
open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
words = f.read.split
for word in words
anagram[word.split('').sort] << word
end
end
count = anagram.values.map {|ana| ana.length}.max
anagram.each_value do |ana|
if ana.length >= count
p ana
end
end

View file

@ -0,0 +1,6 @@
Source
.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toList
.groupBy(_.sorted).values
.groupBy(_.size).maxBy(_._1)._2
.map(_.mkString("\t"))
.foreach(println)

View file

@ -0,0 +1,4 @@
val src = io.Source fromURL "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
val vls = src.getLines.toList.groupBy(_.sorted).values
val max = vls.map(_.size).max
vls filter (_.size == max) map (_ mkString " ") mkString "\n"

View file

@ -0,0 +1,24 @@
package require Tcl 8.5
package require http
set url http://www.puzzlers.org/pub/wordlists/unixdict.txt
set response [http::geturl $url]
set data [http::data $response]
http::cleanup $response
set max 0
array set anagrams {}
foreach line [split $data \n] {
foreach word [split $line] {
set anagram [join [lsort [split $word ""]] ""]
lappend anagrams($anagram) $word
set max [::tcl::mathfunc::max $max [llength $anagrams($anagram)]]
}
}
foreach key [array names anagrams] {
if {[llength $anagrams($key)] == $max} {
puts $anagrams($key)
}
}

View file

@ -0,0 +1,14 @@
[[wp:Bulls and Cows|This]] is an old game played with pencil and paper that was later implemented on computer.
The task is for the program to create a four digit random number from the digits 1 to 9, without duplication.
The program should ask for guesses to this number, reject guesses that are malformed, then print the score for the guess.
The score is computed as:
# The player wins if the guess is the same as the randomly chosen number, and the program ends.
# A score of one '''bull''' is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
# A score of one '''cow''' is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
;Cf,
* [[Bulls and cows/Player]]
* [[Guess the number]]
* [[Guess the number/With Feedback]]

View file

@ -0,0 +1,2 @@
---
note: Games

View file

@ -0,0 +1,41 @@
DEFINT A-Z
DIM secret AS STRING
DIM guess AS STRING
DIM c AS STRING
DIM bulls, cows, guesses, i
RANDOMIZE TIMER
DO WHILE LEN(secret) < 4
c = CHR$(INT(RND * 10) + 48)
IF INSTR(secret, c) = 0 THEN secret = secret + c
LOOP
guesses = 0
DO
INPUT "Guess a 4-digit number with no duplicate digits: "; guess
guess = LTRIM$(RTRIM$(guess))
IF LEN(guess) = 0 THEN EXIT DO
IF LEN(guess) <> 4 OR VAL(guess) = 0 THEN
PRINT "** You should enter 4 numeric digits!"
GOTO looper
END IF
bulls = 0: cows = 0: guesses = guesses + 1
FOR i = 1 TO 4
c = MID$(secret, i, 1)
IF MID$(guess, i, 1) = c THEN
bulls = bulls + 1
ELSEIF INSTR(guess, c) THEN
cows = cows + 1
END IF
NEXT i
PRINT bulls; " bulls, "; cows; " cows"
IF guess = secret THEN
PRINT "You won after "; guesses; " guesses!"
EXIT DO
END IF
looper:
LOOP

View file

@ -0,0 +1,85 @@
bool take_it_or_not()
{
int i;
int cows=0, bulls=0;
for(i=0; i < 4; i++) {
if ( number[i] == guess[i] ) {
bulls++;
} else if ( strchr(number, guess[i]) != NULL ) {
cows++;
}
}
move(yp, xp);
addstr(guess); addch(' ');
if ( bulls == 4 ) { yp++; return true; }
if ( (cows==0) && (bulls==0) ) addch('-');
while( cows-- > 0 ) addstr("O");
while( bulls-- > 0 ) addstr("X");
yp++;
if ( yp > LAST_LINE ) {
yp = LINE_BEGIN;
xp += 10;
}
return false;
}
bool ask_play_again()
{
int i;
while(yp-- >= LINE_BEGIN) {
move(yp, 0); clrtoeol();
}
yp = LINE_BEGIN; xp = 0;
move(21,0); clrtoeol();
addstr("Do you want to play again? [y/n]");
while(true) {
int a = getch();
switch(a) {
case 'y':
case 'Y':
return true;
case 'n':
case 'N':
return false;
}
}
}
int main()
{
bool bingo, again;
int tries = 0;
initscr(); cbreak(); noecho();
clear();
number[4] = guess[4] = 0;
mvaddstr(0,0, "I choose a number made of 4 digits (from 1 to 9) without repetitions\n"
"You enter a number of 4 digits, and I say you how many of them are\n"
"in my secret number but in wrong position (cows or O), and how many\n"
"are in the right position (bulls or X)");
do {
move(20,0); clrtoeol(); move(21, 0); clrtoeol();
srand(time(NULL));
choose_the_number();
do {
ask_for_a_number();
bingo = take_it_or_not();
tries++;
} while(!bingo && (tries < MAX_NUM_TRIES));
if ( bingo )
mvaddstrf(20, 0, "You guessed %s correctly in %d attempts!", number, tries);
else
mvaddstrf(20,0, "Sorry, you had only %d tries...; the number was %s",
MAX_NUM_TRIES, number);
again = ask_play_again();
tries = 0;
} while(again);
nocbreak(); echo(); endwin();
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,60 @@
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>
#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18
int yp=LINE_BEGIN, xp=0;
char number[5];
char guess[5];
#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
va_list args;
char buf[MAX_STR];
va_start(args, fmt);
vsprintf(buf, fmt, args);
move(y, x);
clrtoeol();
addstr(buf);
va_end(args);
}
void ask_for_a_number()
{
int i=0;
char symbols[] = "123456789";
move(5,0); clrtoeol();
addstr("Enter four digits: ");
while(i<4) {
int c = getch();
if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
addch(c);
symbols[c-'1'] = 0;
guess[i++] = c;
}
}
}
void choose_the_number()
{
int i=0, j;
char symbols[] = "123456789";
while(i<4) {
j = rand() % 9;
if ( symbols[j] != 0 ) {
number[i++] = symbols[j];
symbols[j] = 0;
}
}
}

View file

@ -0,0 +1,38 @@
(ns bulls-and-cows)
(defn bulls [guess solution]
(count (filter true? (map = guess solution))))
(defn cows [guess solution]
(-
(count (filter (set solution) guess))
(bulls guess solution)))
(defn valid-input?
"checks whether the string is a 4 digit number with unique digits"
[user-input]
(if (re-seq #"^(?!.*(\d).*\1)\d{4}$" user-input)
true
false))
(defn enter-guess []
"Let the user enter a guess. Verify the input. Repeat until valid.
returns a list of digits enters by the user (# # # #)"
(println "Enter your guess: ")
(let [guess (read-line)]
(if (valid-input? guess)
(map #(Character/digit % 10) guess)
(recur))))
(defn bulls-and-cows []
"generate a random 4 digit number from the list of (1 ... 9): no repeating digits
player tries to guess the number with bull and cows rules gameplay"
(let [solution ( take 4 (shuffle (range 1 10)))]
(println "lets play some bulls and cows!")
(loop [guess (enter-guess)]
(println (bulls guess solution) " bulls and " (cows guess solution) " cows.")
(if (not= guess solution)
(recur (enter-guess))
(println "You have won!")))))
(bulls-and-cows)

View file

@ -0,0 +1,3 @@
#!/usr/bin/escript
% Play Bulls and Cows
main(_) -> random:seed(now()), bulls_and_cows:play().

View file

@ -0,0 +1,45 @@
-module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).
% generate the secret code
generate_secret() -> generate_secret([], 4, lists:seq(1,9)).
generate_secret(Secret, 0, _) -> Secret;
generate_secret(Secret, N, Digits) ->
Next = lists:nth(random:uniform(length(Digits)), Digits),
generate_secret(Secret ++ [Next], N - 1, Digits -- [Next]).
% evaluate a guess
score_guess(Secret, Guess)
when length(Secret) =/= length(Guess) -> throw(badguess);
score_guess(Secret, Guess) ->
Bulls = count_bulls(Secret,Guess),
Cows = count_cows(Secret, Guess, Bulls),
[Bulls, Cows].
% count bulls (exact matches)
count_bulls(Secret, Guess) ->
length(lists:filter(fun(I) -> lists:nth(I,Secret) == lists:nth(I,Guess) end,
lists:seq(1, length(Secret)))).
% count cows (digits present but out of place)
count_cows(Secret, Guess, Bulls) ->
length(lists:filter(fun(I) -> lists:member(I, Guess) end, Secret)) - Bulls.
% play a game
play() -> play_round(generate_secret()).
play_round(Secret) -> play_round(Secret, read_guess()).
play_round(Secret, Guess) ->
play_round(Secret, Guess, score_guess(Secret,Guess)).
play_round(_, _, [4,0]) ->
io:put_chars("Correct!\n");
play_round(Secret, _, Score) ->
io:put_chars("\tbulls:"), io:write(hd(Score)), io:put_chars(", cows:"),
io:write(hd(tl(Score))), io:put_chars("\n"), play_round(Secret).
read_guess() ->
lists:map(fun(D)->D-48 end,
lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).

View file

@ -0,0 +1,37 @@
include random.fs
create hidden 4 allot
: ok? ( str -- ? )
dup 4 <> if 2drop false exit then
1 9 lshift 1- -rot
bounds do
i c@ '1 -
dup 0 9 within 0= if 2drop false leave then
1 swap lshift over and
dup 0= if nip leave then
xor
loop 0<> ;
: init
begin
hidden 4 bounds do 9 random '1 + i c! loop
hidden 4 ok?
until ;
: check? ( addr -- solved? )
0
4 0 do
over i + c@
4 0 do
dup hidden i + c@ = if swap
i j = if 8 else 1 then + swap
then
loop drop
loop nip
8 /mod tuck . ." bulls, " . ." cows"
4 = ;
: guess: ( "1234" -- )
bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
drop check? if cr ." You guessed it!" then ;

View file

@ -0,0 +1,84 @@
module bac
implicit none
contains
subroutine Gennum(n)
integer, intent(out) :: n(4)
integer :: i, j
real :: r
call random_number(r)
n(1) = int(r * 9.0) + 1
i = 2
outer: do while (i <= 4)
call random_number(r)
n(i) = int(r * 9.0) + 1
inner: do j = i-1 , 1, -1
if (n(j) == n(i)) cycle outer
end do inner
i = i + 1
end do outer
end subroutine Gennum
subroutine Score(n, guess, b, c)
character(*), intent(in) :: guess
integer, intent(in) :: n(0:3)
integer, intent(out) :: b, c
integer :: digit, i, j, ind
b = 0; c = 0
do i = 1, 4
read(guess(i:i), "(i1)") digit
if (digit == n(i-1)) then
b = b + 1
else
do j = i, i+2
ind = mod(j, 4)
if (digit == n(ind)) then
c = c + 1
exit
end if
end do
end if
end do
end subroutine Score
end module bac
program Bulls_and_Cows
use bac
implicit none
integer :: n(4)
integer :: bulls=0, cows=0, tries=0
character(4) :: guess
call random_seed
call Gennum(n)
write(*,*) "I have selected a number made up of 4 digits (1-9) without repetitions."
write(*,*) "You attempt to guess this number."
write(*,*) "Every digit in your guess that is in the correct position scores 1 Bull"
write(*,*) "Every digit in your guess that is in an incorrect position scores 1 Cow"
write(*,*)
do while (bulls /= 4)
write(*,*) "Enter a 4 digit number"
read*, guess
if (verify(guess, "123456789") /= 0) then
write(*,*) "That is an invalid entry. Please try again."
cycle
end if
tries = tries + 1
call Score (n, guess, bulls, cows)
write(*, "(a, i1, a, i1, a)") "You scored ", bulls, " bulls and ", cows, " cows"
write(*,*)
end do
write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"
end program Bulls_and_Cows

View file

@ -0,0 +1,117 @@
package main
import (
. "fmt"
"rand"
"time"
"os"
"bufio"
"strconv"
"strings"
)
func generateTarget() int {
rand.Seed(time.Nanoseconds())
// loop until we find a number that doesn't have dupes
for {
target := rand.Intn(9000) + 1000
if !hasDupes(target) {
return target
}
}
panic("Crap.")
}
func hasDupes(num int) bool {
digs := make([]bool, 10)
for num > 0 {
if digs[num%10] {
return true
}
digs[num%10] = true
num /= 10
}
return false
}
func askForNumber() (int, os.Error) {
in := bufio.NewReader(os.Stdin)
for {
Print("Give me a number: ")
line, err := in.ReadString('\n')
if err != nil {
return -1, err
}
// Strip off the \n
line = line[0 : len(line)-1]
number, err := strconv.Atoi(line)
switch {
case err != nil:
Println("Give me a number fule!")
case number < 1000:
Println("Number not long enough")
case number > 9999:
Println("Number is to big")
case hasDupes(number):
Println("I said no dupes!")
default:
return number, nil
}
// Keep Asking
}
panic("Crap.")
}
func bullsAndCows(number int, guess int) (bulls int, cows int) {
bulls, cows = 0, 0
numberstr := strconv.Itoa(number)
guessstr := strconv.Itoa(guess)
for i := range guessstr {
s := string(guessstr[i])
switch {
case guessstr[i] == numberstr[i]:
bulls++
case strings.Index(numberstr, s) >= 0:
cows++
}
}
return;
}
func main() {
attempts := 0
Print("I choose a number made of 4 digits (from 1 to 9) without repetitions\n"
"You enter a number of 4 digits, and I say you how many of them are\n"
"in my secret number but in wrong position (cows or O), and how many\n"
"are in the right position (bulls or X)\n\n")
target := generateTarget()
for {
guess, err := askForNumber()
attempts++
// Handle err
if err != nil && err != os.EOF {
Print(err)
} else if err == os.EOF {
return
}
// Check if target matches guess
if guess == target {
Printf("Congratulations you guessed correctly in %d attempts\n", attempts)
return
}
bulls, cows := bullsAndCows(target, guess)
Printf("%d Bulls, %d Cows\n", bulls, cows)
}
}

View file

@ -0,0 +1,68 @@
package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
// generate pattern
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
// accept and score guesses
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
// malformed: not four characters
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
// malformed: repeated digit
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
// malformed: not a digit
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default: // I just think cows should go first
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
}

Some files were not shown because too many files have changed in this diff Show more