March 2014 update

This commit is contained in:
Ingy döt Net 2014-04-02 16:56:35 +00:00
parent 09687c4926
commit a25938f123
1846 changed files with 21876 additions and 5203 deletions

View file

@ -0,0 +1,48 @@
; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html
; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.
; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC
;
; Notes:
; Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will
; be directly shown as pixels in the display.
; $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops.
; Y register holds Stride
; X register holds Index
; Zero Page address $01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction.
; First, zero door array
LDA #00
LDX #100
Z_LOOP:
STA 200,X
DEX
BNE Z_LOOP
STA 200,X
; Now do doors repeated open/close
LDY #01 ; Initial value of Stride
S_LOOP:
CPY #101
BCS S_DONE
TYA ; Initial value of Index
I_LOOP:
CMP #101
BCS I_DONE
TAX ; Use as Door array index
INC $200,X ; Toggle bit 0 to reverse state of door
STY 01 ; Add stride (Y) to index (X, via A)
ADC 01
BCC I_LOOP
I_DONE:
INY
BNE S_LOOP
S_DONE:
; Finally, format array values for output: 0 for closed, 1 for open
LDX #100
C_LOOP:
LDA $200,X
AND #$01
STA $200,X
DEX
BNE C_LOOP

View file

@ -0,0 +1,17 @@
;assumes memory at $02xx is initially set to 0 and stack pointer is initialized
;the 1 to 100 door byte array will be at $0200-$0263 (decimal 512 to 611)
;Zero-page location $01 will hold delta
;At end, closed doors = $00, open doors = $01
start: ldx #0 ;initialize index - first door will be at $200 + $0
stx $1
inc $1 ;start out with a delta of 1 (0+1=1)
openloop: inc $200,X ;open X'th door
inc $1 ;add 2 to delta
inc $1
txa ;add delta to X by transferring X to A, adding delta to A, then transferring back to X
clc ; clear carry before adding (6502 has no add-without-carry instruction)
adc $1
tax
cpx #$64 ;check to see if we're at or past the 100th door (at $200 + $63)
bmi openloop ;jump back to openloop if less than 100

View file

@ -1,10 +0,0 @@
;assume all memory is initially set to 0
inc $1 ;start out with a delta of 1
openloop: inc $200,X ;open a door at X
inc $1 ;add 2 to delta
inc $1
txa ;add delta to X
adc $1
tax
cpx #$65 ;check to see if we're at the 100th door
bmi openloop ;jump back to openloop if less than 100

View file

@ -1,16 +1,22 @@
DIM doors(0 TO 99)
FOR pass = 0 TO 99
FOR door = pass TO 99 STEP pass + 1
PRINT doors(door)
PRINT NOT doors(door)
doors(door) = NOT doors(door)
NEXT door
NEXT pass
FOR i = 0 TO 99
PRINT "Door #"; i + 1; " is ";
IF NOT doors(i) THEN
PRINT "closed"
ELSE
PRINT "open"
END IF
NEXT i
REM "100 Doors" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler.
REM Author: G. A. Tippery
REM Date: 12-Feb-2014
REM
REM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors
DEFINT A-Z
CONST N = 100
DIM door(N)
FOR stride = 1 TO N
FOR index = stride TO N STEP stride
LET door(index) = NOT (door(index))
NEXT index
NEXT stride
PRINT "Open doors:"
FOR index = 1 TO N
IF door(index) THEN PRINT index
NEXT index
END

View file

@ -1,7 +1,11 @@
DIM doors(0 TO 99)
FOR door = 0 TO 99
IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1
NEXT door
FOR pass = 0 TO 99
FOR door = pass TO 99 STEP pass + 1
PRINT doors(door)
PRINT NOT doors(door)
doors(door) = NOT doors(door)
NEXT door
NEXT pass
FOR i = 0 TO 99
PRINT "Door #"; i + 1; " is ";
IF NOT doors(i) THEN

View file

@ -1,10 +1,12 @@
'lrcvs 04.11.12
cls
x = 1 : y = 3 : z = 0
print x + " Open"
do
z = x + y
print z + " Open"
x = z : y = y + 2
until z >= 100
end
DIM doors(0 TO 99)
FOR door = 0 TO 99
IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1
NEXT door
FOR i = 0 TO 99
PRINT "Door #"; i + 1; " is ";
IF NOT doors(i) THEN
PRINT "closed"
ELSE
PRINT "open"
END IF
NEXT i

View file

@ -0,0 +1,10 @@
'lrcvs 04.11.12
cls
x = 1 : y = 3 : z = 0
print x + " Open"
do
z = x + y
print z + " Open"
x = z : y = y + 2
until z >= 100
end

View file

@ -0,0 +1,26 @@
Require Import List.
Fixpoint rep {A} (a : A) n :=
match n with
| O => nil
| S n' => a::(rep a n')
end.
Fixpoint flip (l : list bool) (n k : nat) : list bool :=
match l with
| nil => nil
| cons h t => match k with
| O => (negb h) :: (flip t n n)
| S k' => h :: (flip t n k')
end
end.
Definition flipeach l n := flip l n n.
Fixpoint flipwhile l n :=
match n with
| O => flipeach l 0
| S n' => flipwhile (flipeach l (S n')) n'
end.
Definition prison cells := flipwhile (rep false (S cells)) cells.

View file

@ -0,0 +1,13 @@
Require Import List.
Fixpoint prisoo' nd n k accu :=
match nd with
| O => rev accu
| S nd' => let ra := match k with
| O => (true, S n, (n + n))
| S k' => (false, n, k')
end in
prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu)
end.
Definition prisoo n := prisoo' (S n) 1 0 nil.

View file

@ -0,0 +1 @@
Goal prison 100 = prisoo 100. compute. reflexivity. Qed.

View file

@ -0,0 +1 @@
Goal forall n, prison n = prisoo n. Abort.

View file

@ -0,0 +1,9 @@
doors = new array[[101], false]
for pass=1 to 100
for door=pass to 100 step pass
doors@door = ! doors@door
print["Open doors: "]
for door=1 to 100
if doors@door
print["$door "]

View file

@ -1,11 +1,6 @@
(function(){var doors = [], n = 100, i, j;
for (i = 1; i <= n; i++) {
for (j = i; j <= n; j += i) {
doors[j] = !doors[j];
}
for (var door = 1; door <= 100; i++) {
var sqrt = Math.sqrt(door);
if (sqrt === (sqrt | 0)) {
console.log("Door %d is open", door);
}
}
for (i = 1 ; i <= n ; i++) {
if (doors[i]) console.log("Door " + i + " is open");
}}())

View file

@ -1,19 +1,9 @@
var
n = 100,
doors = [n],
step,
idx;
// now, start opening and closing
for (step = 1; step <= n; step += 1)
for (idx = step; idx <= n; idx += step)
// toggle state of door
doors[idx] = !doors[idx];
Array.apply(null, { length: 100 })
.map(function(v, i) { return i + 1; })
.forEach(function(door) {
var sqrt = Math.sqrt(door);
// find out which doors are open
var open = doors.reduce(function(open, val, idx) {
if (val) {
open.push(idx);
}
return open;
}, []);
document.write("These doors are open: " + open.join(', '));
if (sqrt === (sqrt | 0)) {
console.log("Door %d is open", door);
}
});

View file

@ -0,0 +1,9 @@
Array.apply(null, { length: 100 })
.map((v, i) => i + 1)
.forEach(door => {
var sqrt = Math.sqrt(door);
if (sqrt === (sqrt | 0)) {
console.log("Door %d is open", door);
}
});

View file

@ -0,0 +1,9 @@
// Array comprehension style
[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => {
var door = i + 1
var sqrt = Math.sqrt(door);
if (sqrt === (sqrt | 0)) {
console.log("Door %d is open", door);
}
});

View file

@ -0,0 +1,11 @@
fun oneHundredDoors(): List<Int> {
val doors = Array<Boolean>(100, { false })
for (i in 0..99)
for (j in i..99 step (i + 1))
doors[j] = !doors[j]
return IndexIterator(doors.iterator()).filter { it.second }
.map { it.first + 1 }
.toList()
}

View file

@ -0,0 +1,5 @@
doors(n) := block([v], local(v),
v: makelist(true, n),
for i: 2 thru n do
for j: i step i thru n do v[j]: not v[j],
sublist_indices(v, 'identity));

View file

@ -0,0 +1,2 @@
doors(100);
/* [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] */

View file

@ -1,10 +0,0 @@
doors(n) := block([v: makelist(i, i, 1, n)],
for i from 2 thru n do
for j from i step i while j <= n do v[j]: -v[j],
sublist(v, ?plusp))$
doors(100);
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
/* Note: ?plusp is a Lisp function. Maxima has nonnegintegerp, which is equivalent,
but it needs load(linearalgebra)$ first. */

View file

@ -0,0 +1,16 @@
from strutils import format
proc check_doors() =
const n = 100
var is_open : array[1..n, bool] # auto-initialized to false
# pass over the doors n times
for pass in 1..n:
var i = pass
while i <= n:
is_open[i] = not is_open[i]
i += pass
# print the result
for door in 1..n:
echo format("door $1 is $2.", door, (if is_open[door]: "open" else: "closed"))
check_doors()

View file

@ -1,4 +1,6 @@
for i in list(range(1, 101)):
if i**0.5 % 1: state='open'
else: state='close'
print ("Door {}:{}".format(i, state))
for i in range(1, 101):
if i**0.5 % 1:
state='open'
else:
state='close'
print("Door {}:{}".format(i, state))

View file

@ -1,9 +1,9 @@
@(do (defun 100-doors ()
@(do (defun hyaku-mai-to ()
(let ((doors (vector 100)))
(each ((i (range 0 99)))
(for ((j i)) ((< j 100)) ((inc j (+ i 1)))
(each ((j (range i 99 (+ i 1))))
(flip [doors j])))
doors))
(each ((counter (range 1))
(door (list-vector (100-doors))))
(door (list-vector (hyaku-mai-to))))
(format t "door ~a is ~a\n" counter (if door "open" "closed"))))

View file

@ -1,45 +1,27 @@
(ns rosettacode.24game)
(defn gen-new-game-nums [amount] (repeatedly amount #(inc ( rand-int 9))))
(def ^:dynamic *luser*
"You guessed wrong, or your input was not in prefix notation.")
(defn orderless-seq-eq? [seq1 seq2] (apply = (map frequencies (list seq1 seq2))))
(def ^:private start #(println
"Your numbers are: " %1 ". Your goal is " %2 ".\n"
"Use the ops [+ - * /] in prefix notation to reach" %2 ".\n"
"q[enter] to quit."))
(defn valid-input?
"checks whether the expression is somewhat valid prefix notation
(+ 1 2 3 4) (+ 3 (+ 4 5) 6)
this is done by making sure the only contents of the list are numbers operators and brackets
flatten gets rid of the brackets, so we just need to test for operators and integers after that"
[user-input]
(if (re-find #"^\(([\d-+/*] )+\d?\)$" (pr-str (flatten user-input)))
true
false))
(defn play
([] (play 24))
([goal] (play goal (repeatedly 4 #(inc (rand-int 9)))))
([goal gns]
(start gns goal)
(let [input (read-string (read-line))
flat (flatten input)]
(println
(if (and (re-find #"^\([\d\s+*/-]+\d?\)$" (pr-str flat))
(= (set gns) (set (filter integer? flat)))
(= goal (eval input)))
"You won the game!"
*luser*))
(when (not= input 'q) (recur goal gns)))))
(defn game-numbers-and-user-input-same?
"input form: (+ 1 2 (+ 3 4))
tests to see if the numbers the user entered are the same as the ones given to them by the game"
[game-nums user-input]
(orderless-seq-eq? game-nums (filter integer? (flatten user-input))))
(defn win [] (println "you won the game!\n"))
(defn lose [] (println "you guessed wrong, or your input was not in prefix notation. eg: '(+ 1 2 3 4)'\n"))
(defn game-start [goal game-numbers] (do
(println "Your numbers are " game-numbers)
(println "Your goal is " goal)
(println "Use the numbers and +*-/ to reach your goal\n")
(println "'q' to Quit\n")))
(defn play-game
"typing in 'q' quits.
to play use (play-game) (play-game 24) or (play-game 24 '(1 2 3 4)"
([] (play-game 24))
([goal] (play-game goal (gen-new-game-nums 4)))
([goal game-numbers]
(game-start goal game-numbers)
(let [input (read-line)
input-as-code (read-string input)]
(if (and (valid-input? input-as-code)
(game-numbers-and-user-input-same? game-numbers input-as-code)
(try (= goal (eval input-as-code)) (catch Exception e (do (lose) (play-game goal game-numbers)))))
(win)
(when (not (= input "q"))
(do (lose) (recur goal game-numbers)))))))
; * checks prefix form, then checks to see that the numbers used
; and the numbers generated by the game are the same.

View file

@ -0,0 +1,14 @@
repeat with beerCount from 99 to 1 by -1
set bottles to "bottles"
if beerCount < 99 then
if beerCount = 1 then
set bottles to "bottle"
end
log "" & beerCount & " " & bottles & " of beer on the wall"
log ""
end
log "" & beerCount & " " & bottles & " of beer on the wall"
log "" & beerCount & " " & bottles & " of beer"
log "Take one down, pass it around"
end
log "No more bottles of beer on the wall!"

View file

@ -0,0 +1,12 @@
public static void BottlesSong(int numberOfBottles)
{
if (numberOfBottles > 0)
{
Console.WriteLine("{0} bottles of beer on the wall", numberOfBottles);
Console.WriteLine("{0} bottles of beer ", numberOfBottles);
Console.WriteLine("Take one down, pass it around");
Console.WriteLine("{0} bottles of beer ", numberOfBottles - 1);
Console.WriteLine();
BottlesSong(--numberOfBottles);
}
}

View file

@ -1,5 +1,17 @@
#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");}
int main(int argc, char *argv[])
{
if(argc == 99)
return 99;
if(argv[0] != NULL){
argv[0] = NULL;
argc = 0;
}
argc = main(argc + 1, argv);
printf("%d bottle%c of beer on the wall\n", argc, argc == 1?'\0': 's');
printf("%d bottle%c of beer\n", argc, argc == 1?'\0': 's');
printf("Take one down, pass it around\n");
printf("%d bottle%c of beer on the wall\n\n", argc - 1, (argc - 1) == 1?'\0': 's');
return argc - 1;
}

View file

@ -1,30 +1,5 @@
#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;
}
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

@ -1,35 +1,30 @@
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);}
#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,28 @@
program bottlesMPI
implicit none
integer :: ierr,rank,nproc
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)"
call mpi_init(ierr)
call mpi_comm_size(MPI_COMM_WORLD,nproc, ierr)
call mpi_comm_rank(MPI_COMM_WORLD,rank,ierr)
if ( rank /= 1 ) then
write (*,form) rank, bottles // bwall
if ( rank > 0 ) write (*,form) rank, bottles
else
write (*,form) rank, bottle // bwall
write (*,form) rank, bottle
end if
if ( rank > 0 ) write (*,*) take
call mpi_finalize(ierr)
end program bottlesMPI

View file

@ -1,10 +1,13 @@
// 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--;
while (beer > 0) {
var verse = [
beer + " bottles of beer on the wall,",
beer + " bottles of beer!",
"Take one down, pass it around",
(beer - 1) + " bottles of beer on the wall!"
].join("\n");
console.log(verse);
beer--;
}

View file

@ -1,2 +1,10 @@
// 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>" );
let beer = 99;
while (beer > 0) {
let verse = `${beer} bottles of beer on the wall,
${beer} bottles of beer!
Take one down, pass it around
${beer-1} bottles of beer on the wall`;
console.log(verse);
beer--;
}

View file

@ -1,21 +1,2 @@
// 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();
})();
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

@ -1,18 +1,25 @@
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);
function Bottles(count) {
this.count = count || 99;
}
window.onload = bottleSong;
Bottles.prototype.take = function() {
var verse = [
this.count + " bottles of beer on the wall,",
this.count + " bottles of beer!",
"Take one down, pass it around",
(this.count - 1) + " bottles of beer on the wall!"
].join("\n");
console.log(verse);
this.count--;
};
Bottles.prototype.sing = function() {
while (this.count) {
this.take();
}
};
var bar = new Bottles(99);
bar.sing();

View file

@ -1,12 +1,18 @@
(function(){var beer = 99,string='';
while (beer > 0)
{
string+=beer+"bottles of beer on the wall\n"+ //inline line appending shouldn't be as expensive.
beer +
"bottles of beer\nTake one down, pass it around\n"+
(--beer)+
" bottles of beer on the wall\n" ;
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);
}
console.log(string);
})()
window.onload = bottleSong;

View file

@ -0,0 +1,12 @@
bottles(n) = n==0 ? "No more bottles" :
n==1 ? "1 bottle" :
"$n bottles"
for n = 99:-1:1
println("""
$(bottles(n)) of beer on the wall
$(bottles(n)) of beer
Take one down, pass it around
$(bottles(n-1)) of beer on the wall
""")
end

View file

@ -0,0 +1 @@
bottles(n) = "$(n==0 ? "No more" : n) bottle$(n==1 ? "" : "s")"

View file

@ -1,13 +1,26 @@
bottle(n) := if n = 1 then "bottle" else "bottles"$
bottles(n) := for i from n thru 1 step -1 do (
printf(true, "~d bottle~p of beer on the wall~%", i, i),
printf(true, "~d bottle~p of beer~%", i, i),
printf(true, "Take one down, pass it around~%"),
printf(true, "~d bottle~p of beer on the wall~%", i - 1, i - 1),
disp(""))$
bottles(n) := block(
for i from n thru 1 step -1 do (
printf(true, "~d ~a of beer on the wall~%", i, bottle(i)),
printf(true, "~d ~a of beer~%", i, bottle(i)),
printf(true, "Take one down, pass it around~%"),
printf(true, "~d ~a of beer on the wall~%", i - 1, bottle(i - 1)),
disp("")
)
)$
bottles(3);
/*
bottles(99);
3 bottles of beer on the wall
3 bottles of beer
Take one down, pass it around
2 bottles of beer on the wall
2 bottles of beer on the wall
2 bottles of beer
Take one down, pass it around
1 bottle of beer on the wall
1 bottle of beer on the wall
1 bottle of beer
Take one down, pass it around
0 bottles of beer on the wall
*/

View file

@ -2,16 +2,16 @@
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int bottles = 99;
do
{
NSLog(@"%i bottles of beer on the wall\n", bottles);
NSLog(@"%i bottles of beer\n", bottles);
NSLog(@"Take one down, pass it around\n");
NSLog(@"%i bottles of beer on the wall\n\n", --bottles);
} while (bottles > 0);
@autoreleasepool {
int bottles = 99;
do
{
NSLog(@"%i bottles of beer on the wall\n", bottles);
NSLog(@"%i bottles of beer\n", bottles);
NSLog(@"Take one down, pass it around\n");
NSLog(@"%i bottles of beer on the wall\n\n", --bottles);
} while (bottles > 0);
[pool drain];
}
return 0;
}

View file

@ -1,5 +1,3 @@
// rust is changing fast, so this will probably not work in later versions
use std::iter::range_step_inclusive;
fn main() {
@ -18,10 +16,9 @@ fn sing_bottles_line(num_bottles: int, on_the_wall: bool) {
// check out the docs for std::fmt
print!("{0, plural, =0{No bottles} =1{One bottle} other{# bottles}} of beer", num_bottles as uint);
// this is to demonstrate the select "method"
// it's probably not the best way to do it
// it needs a &str so I had to use that tmp variable to trick it
// hopefully someone else can fix it for me
let tmp: &str = on_the_wall.to_str();
println!("{0, select, true{ on the wall} other{}}!", tmp);
if on_the_wall {
println(" on the wall!");
} else {
println("");
}
}

View file

@ -1,27 +1,27 @@
import 'dart:io';
import 'dart:convert';
// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));
void main() {
stdin.transform(new AsciiDecoder())
.transform(new LineSplitter())
.listen((String str) {
var strings = str.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
if(!strings.every(isAnInteger)) {
print("not an integer!");
} else if(strings.length > 2) {
print("too many numbers!");
} else if(strings.length < 2) {
print('not enough numbers!');
while(true) {
String input = stdin.readLineSync();
var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
if(!chunks.every(isAnInteger)) {
print("not an integer!");
} else if(chunks.length > 2) {
print("too many numbers!");
} else if(chunks.length < 2) {
print('not enough numbers!');
} else {
// parse the strings into integers
var nums = chunks.map((String s) => int.parse(s));
if(nums.any((num) => num < -1000 || num > 1000)) {
print("between -1000 and 1000 please!");
} else {
// parse the strings into integers
var nums = strings.map((String s) => int.parse(s));
if(nums.any((num) => num < -1000 || num > 1000)) {
print("between -1000 and 1000 please!");
} else {
print(nums[0]+ nums[1]);
}
print(nums.reduce((a, b) => a + b));
}
});
}
}
}

1
Task/A+B/Frink/a+b.frink Normal file
View file

@ -0,0 +1 @@
sum[eval[split[%r/\s+/, input[""]]]]

View file

@ -3,7 +3,7 @@ process.openStdin().on (
function (line) {
var xs = String(line).match(/^\s*(\d+)\s+(\d+)\s*/)
console.log (
xs ? Number(xs[1]) + Number(xs[2]) : 'usage: <integer> <integer>'
xs ? Number(xs[1]) + Number(xs[2]) : 'usage: <number> <number>'
)
process.exit()
}

View file

@ -0,0 +1,5 @@
process.stdin.on("data", buffer => {
console.log(
(buffer + "").trim().split(" ").map(Number).reduce((a, v) => a + v, 0)
);
});

15
Task/A+B/Rust/a+b.rust Normal file
View file

@ -0,0 +1,15 @@
// -*- rust v0.9 -*-
use std::os;
fn main() {
let args : ~[~str] = os::args();
let mut values = 0;
for i in args.iter(){
match from_str::<int>(i.to_str()) {
Some(valid_int) => values += valid_int,
None => ()
}
}
println(values.to_str());
}

View file

@ -1,5 +1,5 @@
interface {
Method1(value float64) int
Name() string
SetName(name string)
GetName() string
Method1(value float64) int
}

View file

@ -1,9 +1,9 @@
function accumulator(sum) {
return function(n) {
return sum += n;
}
return function(n) {
return sum += n;
}
}
var x = accumulator(1);
x(5);
document.write(accumulator(3).toString() + '<br>');
document.write(x(2.3));
console.log(accumulator(3).toString() + '<br>');
console.log(x(2.3));

View file

@ -1,5 +1,5 @@
function accumulator(sum) function(n) sum += n;
var x = accumulator(1);
x(5);
console.log(accumulator(3).toSource());
let accumulator = sum => (n => sum += n);
let x = accumulator(1);
console.log(x(5));
accumulator(3);
console.log(x(2.3));

View file

@ -0,0 +1,5 @@
function accumulator(sum) function(n) sum += n;
var x = accumulator(1);
x(5);
console.log(accumulator(3).toSource());
console.log(x(2.3));

View file

@ -7,17 +7,17 @@ Accumulator accumulator_factory(double initial) {
Accumulator acc = ^(double n){
return sum += n;
};
return [[acc copy] autorelease];
return acc;
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
Accumulator x = accumulator_factory(1);
x(5);
accumulator_factory(3);
NSLog(@"%f", x(2.3));
Accumulator x = accumulator_factory(1);
x(5);
accumulator_factory(3);
NSLog(@"%f", x(2.3));
[pool drain];
}
return 0;
}

View file

@ -3,8 +3,7 @@ import std.stdio, std.bigint, std.conv;
BigInt ipow(BigInt base, BigInt exp) pure /*nothrow*/ {
auto result = 1.BigInt;
while (exp) {
//if (exp & 1)
if (exp % 2)
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;

View file

@ -1,7 +1,5 @@
sub A(Int $m, Int $n) {
$m == 0 ?? $n + 1 !!
$n == 0 ?? A($m - 1, 1 ) !!
A($m - 1, A($m, $n - 1));
if $m == 0 { $n + 1 }
elsif $n == 0 { A($m - 1, 1) }
else { A($m - 1, A($m, $n - 1)) }
}

View file

@ -0,0 +1,15 @@
// works for Rust 0.9
fn main() {
let a: int = ack(3, 4); // 125
println!("{}", a.to_str());
}
fn ack(m: int, n: int) -> int {
if m == 0 {
n + 1
} else if n == 0 {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}

View file

@ -0,0 +1,23 @@
@(do
(defmacro defmemofun (name (. args) . body)
(let ((hash (gensym "hash-"))
(argl (gensym "args-"))
(hent (gensym "hent-"))
(uniq (copy-str "uniq")))
^(let ((,hash (hash :equal-based)))
(defun ,name (,*args)
(let* ((,argl (list ,*args))
(,hent (inhash ,hash ,argl ,uniq)))
(if (eq (cdr ,hent) ,uniq)
(set (cdr ,hent) (block ,name (progn ,*body)))
(cdr ,hent)))))))
(defmemofun ack (m n)
(cond
((= m 0) (+ n 1))
((= n 0) (ack (- m 1) 1))
(t (ack (- m 1) (ack m (- n 1))))))
(each ((i (range 0 3)))
(each ((j (range 0 4)))
(format t "ack(~a, ~a) = ~a\n" i j (ack i j)))))

View file

@ -1,21 +1,20 @@
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
char fooKey;
static char fooKey;
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
id e = [[NSObject alloc] init];
id e = [[NSObject alloc] init];
// set
objc_setAssociatedObject(e, &fooKey, [NSNumber numberWithInt:1], OBJC_ASSOCIATION_RETAIN);
// set
objc_setAssociatedObject(e, &fooKey, @1, OBJC_ASSOCIATION_RETAIN);
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey);
NSLog(@"associatedObject: %@", associatedObject);
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey);
NSLog(@"associatedObject: %@", associatedObject);
[e release];
[pool drain];
}
return 0;
}

View file

@ -2,18 +2,17 @@
#import <objc/runtime.h>
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
id e = [[NSObject alloc] init];
id e = [[NSObject alloc] init];
// set
objc_setAssociatedObject(e, @selector(foo), [NSNumber numberWithInt:1], OBJC_ASSOCIATION_RETAIN);
// set
objc_setAssociatedObject(e, @selector(foo), @1, OBJC_ASSOCIATION_RETAIN);
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo));
NSLog(@"associatedObject: %@", associatedObject);
// get
NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo));
NSLog(@"associatedObject: %@", associatedObject);
[e release];
[pool drain];
}
return 0;
}

View file

@ -0,0 +1,10 @@
yes_no = "Yes"
def yes_no.not
replace( self=="Yes" ? "No": "Yes")
end
#Demo:
p yes_no.not # => "No"
p yes_no.not # => "Yes"
p "aaa".not # => undefined method `not' for "aaa":String (NoMethodError)

View file

@ -0,0 +1,13 @@
let address_of (x:'a) : nativeint =
if Obj.is_block (Obj.repr x) then
Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *)
else
invalid_arg "Can only find address of boxed values.";;
let () =
let a = 3.14 in
Printf.printf "%nx\n" (address_of a);;
let b = ref 42 in
Printf.printf "%nx\n" (address_of b);;
let c = 17 in
Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)

View file

@ -2,7 +2,7 @@ BEGIN {
FS="$"
lcounter = 1
maxfield = 0
# justistification; pick up one
# justification; pick one
#justify = "left"
justify = "center"
#justify = "right"

View file

@ -8,11 +8,11 @@ that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."
.splitLines.map!q{ a.chomp("$").split("$") };
.split.map!(r => r.chomp("$").split("$"));
int[int] maxWidths;
foreach (const line; data)
foreach (i, word; line)
foreach (immutable i, const word; line)
maxWidths[i] = max(maxWidths.get(i, 0), word.length);
foreach (const just; TypeTuple!(leftJustify, center, rightJustify))

View file

@ -5,15 +5,12 @@
@; pi = padded items (data with row lengths equalized with empty strings)
@; cw = vector of max column widths
@; ce = center padding
@(bind nc @(apply (fun max) (mapcar (fun length) item)))
@(bind pi @(mapcar (lambda (row)
(append row (repeat '("") (- nc (length row)))))
item))
@(bind nc @[apply max [mapcar length item]])
@(bind pi @(mapcar (op append @1 (repeat '("") (- nc (length @1)))) item))
@(bind cw @(vector-list
(mapcar (lambda (column)
(apply (fun max) (mapcar (fun length) column)))
(mapcar (op apply max [mapcar length @1])
;; matrix transpose trick cols become rows:
(apply (fun mapcar) (cons (fun list) pi)))))
[apply mapcar [cons list pi]])))
@(bind ns "")
@(output)
@ (repeat)

View file

@ -0,0 +1,56 @@
Time := A_TickCount
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetBatchLines -1
Loop, Read, unixdict.txt
StrOut .= StrLen(A_LoopReadLine) - 2 . "," . A_LoopReadLine . "`n"
Sort StrOut, N R
Loop, Parse, StrOut, `n, `r
{
StringSplit, No_Let, A_Loopfield, `,
if ( old1 = no_let1 )
string .= old2 "`n"
if ( old1 != no_let1 )
{
string := trim(string old2)
if ( old2 != "" )
Loop, Parse, string, `n, `r ; Specifying `n prior to `r allows both Windows and Unix files to be Parsed.
line_number := A_Index
if ( line_number > 1 )
{
Loop, Parse, string, `n, `r
{
StringSplit, newstr, A_Loopfield, `, ; break the string based on Comma
Loop, Parse, newstr2
k .= A_LoopField " "
Sort k, D%A_Space%
k := RegExReplace( k, "\s", "" )
file .= "`r`n" k . "," . newstr1 . "," . newstr2
k =
}
Sort File
Loop, Parse, File, `n, `r
{
if ( A_Loopfield != "" )
{
StringSplit, T_C, A_Loopfield, `,
if ( old = T_C1 )
{
Loop, 1
{
Loop % T_C2
if (SubStr(T_C3, A_Index, 1) = SubStr(old3, A_Index, 1))
break 2
Time := (A_tickcount - Time)/1000
MsgBox % T_C3 " " old3 " in " Time . " seconds."
ExitApp
}
}
old := T_C1, old3 := T_C3
}
}
file =
}
string =
}
old1 := no_let1, old2 := A_Loopfield
}

View file

@ -1,19 +1,15 @@
void main() {
import std.stdio, std.file, std.algorithm, std.string, std.range,
std.functional, std.exception;
import std.stdio, std.file, std.algorithm, std.string, std.array;
string[][const ubyte[]] anags;
string[][dstring] anags;
foreach (const w; "unixdict.txt".readText.split)
anags[w.dup.representation.sort().release.assumeUnique] ~= w;
anags[w.array.sort().release.idup] ~= w;
anags
.byValue
.map!(words => cartesianProduct(words, words)
.filter!(ww => ww[].equal!q{ a != b })
.array)
.filter!(not!empty)
.array
.schwartzSort!q{ a[0][0].length }
.back[0]
.map!(words => words.cartesianProduct(words)
.filter!q{ a[].equal!q{ a != b }})
.join
.minPos!q{ a[0].length > b[0].length }[0]
.writeln;
}

View file

@ -1,27 +1,3 @@
import std.stdio, std.file, std.algorithm, std.string, std.array,
std.functional, std.exception;
string[2][] findDeranged(in string[] words) pure nothrow {
// return words.pairwise.filter!(ww => ww[].equal!q{ a != b });
typeof(return) result;
foreach (immutable i, w1; words)
foreach (w2; words[i + 1 .. $])
if (w1.representation.equal!q{ a != b }(w2.representation))
result ~= [w1, w2];
return result;
}
void main() {
Appender!(string[])[30] wClasses;
foreach (const w; "unixdict.txt".readText.splitter)
wClasses[$ - w.length] ~= w;
foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) {
string[][const ubyte[]] anags; // Assume ASCII input.
foreach (immutable w; ws)
anags[w.dup.representation.sort().release.assumeUnique]~= w;
auto pairs = anags.byValue.map!findDeranged.joiner;
if (!pairs.empty)
return writefln("Longest deranged: %-(%s %)", pairs.front);
}
}
string[][ubyte[]] anags;
foreach (const w; "unixdict.txt".readText.split)
anags[w.dup.representation.sort().release.assumeUnique] ~= w;

View file

@ -0,0 +1,27 @@
import std.stdio, std.file, std.algorithm, std.string, std.array,
std.functional, std.exception;
string[2][] findDeranged(in string[] words) pure nothrow {
// return words.pairwise.filter!(ww => ww[].equal!q{ a != b });
typeof(return) result;
foreach (immutable i, w1; words)
foreach (w2; words[i + 1 .. $])
if (w1.representation.equal!q{ a != b }(w2.representation))
result ~= [w1, w2];
return result;
}
void main() {
Appender!(string[])[30] wClasses;
foreach (const w; "unixdict.txt".readText.splitter)
wClasses[$ - w.length] ~= w;
foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) {
string[][const ubyte[]] anags; // Assume ASCII input.
foreach (immutable w; ws)
anags[w.dup.representation.sort().release.assumeUnique]~= w;
auto pairs = anags.byValue.map!findDeranged.joiner;
if (!pairs.empty)
return writefln("Longest deranged: %-(%s %)", pairs.front);
}
}

View file

@ -0,0 +1,5 @@
with(StringTools):
dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]):
L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]:
len:=length(ListTools:-FindMaximalElement(L,(a,b)->length(a)<length(b))):
select(w->length(w)=len,L)[];

View file

@ -1,17 +1,31 @@
MsgBox % anagrams("able")
anagrams(word) {
Static dict
IfEqual dict,, FileRead dict, unixdict.txt ; file in the script directory
w := sort(word)
Loop Parse, dict, `n, `r
If (w = sort(A_LoopField))
t .= A_LoopField "`n"
Return t
}
sort(word) {
a := RegExReplace(word,".","$0`n")
Sort a
Return a
FileRead, Contents, unixdict.txt
Loop, Parse, Contents, % "`n", % "`r"
{ ; parsing each line of the file we just read
Loop, Parse, A_LoopField ; parsing each letter/character of the current word
Dummy .= "," A_LoopField
Sort, Dummy, % "D," ; sorting those letters before removing the delimiters (comma)
StringReplace, Dummy, Dummy, % ",", % "", All
List .= "`n" Dummy " " A_LoopField , Dummy := ""
} ; at this point, we have a list where each line looks like <LETTERS><SPACE><WORD>
Count := 0, Contents := "", List := SubStr(List,2)
Sort, List
Loop, Parse, List, % "`n", % "`r"
{ ; now the list is sorted, parse it counting the consecutive lines with the same set of <LETTERS>
Max := (Count > Max) ? Count : Max
StringSplit, LinePart, A_LoopField, % " " ; (LinePart1 are the letters, LinePart2 is the word)
If ( PreviousLinePart1 = LinePart1 )
Count++ , WordList .= "," LinePart2
Else
var_Result .= ( Count <> Max ) ? "" ; don't append if the number of common words is too low
: "`n" Count "`t" PreviousLinePart1 "`t" SubStr(WordList,2)
, WordList := "" , Count := 0
PreviousLinePart1 := LinePart1
}
List := "", var_Result := SubStr(var_Result,2)
Sort, var_Result, R N ; make the higher scores appear first
Loop, Parse, var_Result, % "`n", % "`r"
If ( 1 == InStr(A_LoopField,Max) )
var_Output .= "`n" A_LoopField
Else ; output only those sets of letters that scored the maximum amount of common words
Break
MsgBox, % ClipBoard := SubStr(var_Output,2) ; the result is also copied to the clipboard

View file

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

View file

@ -19,6 +19,16 @@ Procedure.s sortWord(word$)
ProcedureReturn word$
EndProcedure
;for a faster and more advanced alternative replace the previous procedure with this code
; Procedure.s sortWord(word$) ;returns a string with the letters of the word sorted
; Protected wordLength = Len(word$)
; Protected Dim letters.c(wordLength)
;
; PokeS(@letters(), word$) ;overwrite the array with the strings contents
; SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
; ProcedureReturn PeekS(@letters(), wordLength) ;return the arrays contents
; EndProcedure
tmpdir$ = GetTemporaryDirectory()
filename$ = tmpdir$ + "unixdict.txt"
@ -43,15 +53,20 @@ If ReceiveHTTPFile("http://www.puzzlers.org/pub/wordlists/unixdict.txt", filenam
Else
; if no
anaMap(key$)\anas = word$ ; applying a new record
anaMap()\isana + 1
anaMap()\isana = 1
EndIf
If anaMap()\isana > maxAnagrams ;make note of maximum anagram count
maxAnagrams = anaMap()\isana
EndIf
Until Eof(1)
CloseFile(1)
DeleteFile(filename$)
;----- output -----
ForEach anaMap()
If anaMap()\isana >= 4 ; only emit what had 4 or more hits.
If anaMap()\isana = maxAnagrams ; only emit elements that have the most hits
PrintN(anaMap()\anas)
EndIf
Next

View file

@ -0,0 +1,39 @@
extern crate collections;
use std::str;
use collections::HashMap;
use std::io::File;
use std::io::BufferedReader;
use std::cmp;
fn sort_string(string: &str) -> ~str {
let mut chars = string.chars().to_owned_vec();
chars.sort();
str::from_chars(chars)
}
fn main () {
let path = Path::new("unixdict.txt");
let mut file = BufferedReader::new(File::open(&path));
let mut map: HashMap<~str, ~[~str]> = HashMap::new();
for line in file.lines() {
let s = line.trim().to_owned();
map.mangle(sort_string(s.clone()), s,
|_k, v| ~[v],
|_k, v, string| v.push(string)
);
}
let max_length = map.iter().fold(0, |s, (_k, v)| cmp::max(s, v.len()));
for (_k, v) in map.iter() {
if v.len() == max_length {
for s in v.iter() {
print!("{} ", *s)
}
println!("")
}
}
}

View file

@ -0,0 +1,39 @@
SetBatchlines,-1
;settings
SizeGUI:={w:650,h:400} ;Guisize
pendulum:={length:300,maxangle:90,speed:2,size:30,center:{x:Sizegui.w//2,y:10}} ;pendulum length, size, center, speed and maxangle
pendulum.maxangle:=pendulum.maxangle*0.01745329252
p_Token:=Gdip_Startup()
Gui,+LastFound
Gui,show,% "w" SizeGUI.w " h" SizeGUI.h
hwnd:=WinActive()
hdc:=GetDC(hwnd)
start:=A_TickCount/1000
G:=Gdip_GraphicsFromHDC(hdc)
pBitmap:=Gdip_CreateBitmap(650, 450)
G2:=Gdip_GraphicsFromImage(pBitmap)
Gdip_SetSmoothingMode(G2, 4)
pBrush := Gdip_BrushCreateSolid(0xff0000FF)
pBrush2 := Gdip_BrushCreateSolid(0xFF777700)
pPen:=Gdip_CreatePenFromBrush(pBrush2, 10)
SetTimer,Update,10
Update:
Gdip_GraphicsClear(G2,0xFFFFFFFF)
time:=start-(A_TickCount/1000*pendulum.speed)
angle:=sin(time)*pendulum.maxangle
x2:=sin(angle)*pendulum.length+pendulum.center.x
y2:=cos(angle)*pendulum.length+pendulum.center.y
Gdip_DrawLine(G2,pPen,pendulum.center.x,pendulum.center.y,x2,y2)
GDIP_DrawCircle(G2,pBrush,pendulum.center.x,pendulum.center.y,15)
GDIP_DrawCircle(G2,pBrush2,x2,y2,pendulum.size)
Gdip_DrawImage(G, pBitmap)
return
GDIP_DrawCircle(g,b,x,y,r){
Gdip_FillEllipse(g, b, x-r//2,y-r//2 , r, r)
}
GuiClose:
ExitApp

View file

@ -0,0 +1,23 @@
Fib(n) {
nold1 := 1
nold2 := 0
If n < 0
{
MsgBox, Positive argument required!
Return
}
Else If n = 0
Return nold2
Else If n = 1
Return nold1
Fib_Label:
t := nold2+nold1
If n > 2
{
n--
nold2:=nold1
nold1:=t
GoSub Fib_Label
}
Return t
}

View file

@ -1,10 +1,7 @@
)abbrev package TESTP TestPackage
Z ==> Integer
TestPackage : with
fib : Z -> Z
== add
fib x ==
x <= 0 => error "argument outside of range"
f : Reference((Z,Z,Z) -> Z) := ref((n, v1, v2) +-> 0)
f() := (n, v1, v2) +-> if n<2 then v2 else f()(n-1,v2,v1+v2)
f()(x,1,1)
#include "axiom"
Z ==> Integer;
fib(x:Z):Z == {
x <= 0 => error "argument outside of range";
f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2);
f(x,1,1);
}

View file

@ -1,10 +1,10 @@
#include "aldor";
#include "aldorio";
import from Integer;
Z ==> Integer;
fib(x:Z):Z == {
x <= 0 => throw SyntaxException;
f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2);
f(x,1,1);
}
stdout << fib(10000);
)abbrev package TESTP TestPackage
Z ==> Integer
TestPackage : with
fib : Z -> Z
== add
fib x ==
x <= 0 => error "argument outside of range"
f : Reference((Z,Z,Z) -> Z) := ref((n, v1, v2) +-> 0)
f() := (n, v1, v2) +-> if n<2 then v2 else f()(n-1,v2,v1+v2)
f()(x,1,1)

View file

@ -15,19 +15,18 @@
if (i < 2)
result = 1;
else
result = [[self performSelector:_cmd withObject:[NSNumber numberWithInt:i-1]] intValue]
+ [[self performSelector:_cmd withObject:[NSNumber numberWithInt:i-2]] intValue];
return [NSNumber numberWithInt:result];
result = [[self performSelector:_cmd withObject:@(i-1)] intValue]
+ [[self performSelector:_cmd withObject:@(i-2)] intValue];
return @(result);
}
@end
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
AnonymousRecursion *dummy = [[AnonymousRecursion alloc] init];
NSLog(@"%@", [dummy fibonacci:[NSNumber numberWithInt:8]]);
[dummy release];
AnonymousRecursion *dummy = [[AnonymousRecursion alloc] init];
NSLog(@"%@", [dummy fibonacci:@8]);
[pool release];
}
return 0;
}

View file

@ -5,21 +5,22 @@ int fib(int n) {
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:@"fib: no negative numbers"
userInfo:nil];
__block int (^f)(int);
f = ^(int n) {
int (^f)(int);
__block __weak int (^weak_f)(int); // block cannot capture strong reference to itself
weak_f = f = ^(int n) {
if (n < 2)
return 1;
else
return f(n-1) + f(n-2);
return weak_f(n-1) + weak_f(n-2);
};
return f(n);
}
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@autoreleasepool {
NSLog(@"%d", fib(8));
NSLog(@"%d", fib(8));
[pool release];
}
return 0;
}

View file

@ -0,0 +1,25 @@
#import <Foundation/Foundation.h>
int fib(int n) {
if (n < 0)
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:@"fib: no negative numbers"
userInfo:nil];
__block int (^f)(int);
f = ^(int n) {
if (n < 2)
return 1;
else
return f(n-1) + f(n-2);
};
return f(n);
}
int main (int argc, const char *argv[]) {
@autoreleasepool {
NSLog(@"%d", fib(8));
}
return 0;
}

View file

@ -0,0 +1,9 @@
>>> from inspect import currentframe
>>> from types import FunctionType
>>> def myself (*args, **kw):
... caller_frame = currentframe(1)
... code = caller_frame.f_code
... return FunctionType(code, caller_frame.f_globals)(*args, **kw)
...
>>> print "factorial(5) =",
>>> print (lambda n:1 if n<=1 else n*myself(n-1)) ( 5 )

View file

@ -0,0 +1,3 @@
f = {|x| x^2} // Anonymous function to square input
a = [1,2,3,5,7]
println[map[f, a]]

View file

@ -1,7 +1,9 @@
function map(a, func) {
for (var i in a)
a[i] = func(a[i]);
var ret = [];
for (var i = 0; i < a.length; i++) {
ret[i] = func(a[i]);
}
return ret;
}
var a = [1, 2, 3, 4, 5];
map(a, function(v) { return v * v; });
map([1, 2, 3, 4, 5], function(v) { return v * v; });

View file

@ -1 +1 @@
var a = (1).to(10).collect(Math.pow.curry(undefined,2));
[1, 2, 3, 4, 5].map(function(v) { return v * v; });

View file

@ -1,15 +1 @@
function cube(num) {
return Math.pow(num, 3);
}
var numbers = [1, 2, 3, 4, 5];
// get results of calling cube on every element
var cubes1 = numbers.map(cube);
// display each result in a separate dialog
cubes1.forEach(alert);
// array comprehension
var cubes2 = [cube(n) for each (n in numbers)];
var cubes3 = [n * n * n for each (n in numbers)];
[1, 2, 3, 4, 5].map(v => v * v);

View file

@ -1,7 +1,11 @@
@(do
(defun mapvec (vec fun)
(each ((i (range 0 (- (length vec) 1))))
[fun [vec i]]))
(mapvec #(1 2 3 4 5 6 7 8 9 10)
(lambda (x) (format t "~a\n" x))))
$ txr -e '[mapcar prinl #(1 2 3 4 5 6 7 8 9 10)]'
1
2
3
4
5
6
7
8
9
10

View file

@ -9,3 +9,6 @@ C.F. [[Long multiplication]]
<small>Note: <ul><li>Do not submit an ''implementation'' of [[wp:arbitrary precision arithmetic|arbitrary precision arithmetic]]. The intention is to show the capabilities of the language as supplied. If a language has a [[Talk:Arbitrary-precision integers (included)#Use of external libraries|single, overwhelming, library]] of varied modules that is endorsed by its home site such as [[CPAN]] for Perl or [[Boost]] for C++ then that ''may'' be used instead.
</li><li>Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the '''only''' recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.</li></ul></small>
;See also:
* [[Exponentiation order]]

View file

@ -0,0 +1,14 @@
$SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class.

View file

@ -0,0 +1,13 @@
add[x,y] := x + y
multiply[x,y] := x * y
negate[x] := -x
invert[x] := 1/x // Could also use inv[x] or recip[x]
conjugate[x] := Re[x] - Im[x] i
a = 3 + 2.5i
b = 7.3 - 10i
println["$a + $b = " + add[a,b]]
println["$a * $b = " + multiply[a,b]]
println["-$a = " + negate[a]]
println["1/$a = " + invert[a]]
println["conjugate[$a] = " + conjugate[a]]

View file

@ -0,0 +1,16 @@
extern crate num;
use num::complex::Cmplx;
fn main() {
let a = Cmplx::new(-4.0, 5.0);
let b = Cmplx::new(1.0, 1.0);
println!("a = {}", a);
println!("b = {}", b);
println!("a + b = {}", a + b);
println!("a * b = {}", a * b);
println!("1 / a = {}", Cmplx::new(1.0, 0.0) / a);
println!("-a = {}", -a);
println!("conj a = {}", a.conj());
}

View file

@ -9,7 +9,7 @@ T lcm(T)(in T a, in T b) pure /*nothrow*/ {
return a / gcd(a, b) * b;
}
struct RationalT(T) {
struct RationalT(T) if (!isUnsigned!T) {
private T num, den; // Numerator & denominator.
private enum Type { NegINF = -2,
@ -54,7 +54,7 @@ struct RationalT(T) {
return result;
}
T nomerator() const pure nothrow @property {
T numerator() const pure nothrow @property {
return num;
}
@ -73,9 +73,9 @@ struct RationalT(T) {
real toReal() pure const /*nothrow*/ {
static if (is(T == BigInt))
return num.toLong / cast(real)den.toLong;
return num.toLong / real(den.toLong);
else
return num / cast(real)den;
return num / real(den);
}
RationalT opBinary(string op)(in RationalT r)
@ -126,14 +126,14 @@ struct RationalT(T) {
return num != 0;
}
int opEquals(U)(in U r) const pure nothrow {
bool opEquals(U)(in U r) const pure nothrow {
RationalT rhs = RationalT(r);
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
return false;
return num == rhs.num && den == rhs.den;
}
int opCmp(U)(in U r) const pure nothrow {
int opCmp(U)(in U r) const pure {
auto rhs = RationalT(r);
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
throw new Exception("Compare involve a NaRAT.");
@ -154,6 +154,15 @@ struct RationalT(T) {
}
}
RationalT!U rational(U)(in U n) pure /*nothrow*/ {
return typeof(return)(n);
}
RationalT!(CommonType!(U1, U2))
rational(U1, U2)(in U1 n, in U2 d) pure /*nothrow*/ {
return typeof(return)(n, d);
}
alias Rational = RationalT!BigInt;
version (arithmetic_rational_main) { // Test.
@ -163,7 +172,7 @@ version (arithmetic_rational_main) { // Test.
foreach (immutable p; 2 .. 2 ^^ 19) {
auto sum = RatL(1, p);
immutable limit = 1 + cast(uint)sqrt(cast(real)p);
immutable limit = 1 + cast(uint)real(p).sqrt;
foreach (immutable factor; 2 .. limit)
if (p % factor == 0)
sum += RatL(1, factor) + RatL(factor, p);

View file

@ -8,9 +8,9 @@ def agm(a0, g0, tolerance=1e-10):
value of the arithmetic-geometric mean
(default value = 1e-10)
"""
[an, gn] = [(a0 + g0) / 2.0, sqrt(a0 * g0)]
an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)
while abs(an - gn) > tolerance:
[an, gn] = [(an + gn) / 2.0, sqrt(an * gn)]
an, gn = (an + gn) / 2.0, sqrt(an * gn)
return an
print agm(1, 1 / sqrt(2))

View file

@ -2,7 +2,7 @@ from decimal import Decimal, getcontext
def agm(a, g, tolerance=Decimal("1e-65")):
while True:
a, g = ((a + g) / 2, (a * g).sqrt())
a, g = (a + g) / 2, (a * g).sqrt()
if abs(a - g) < tolerance:
return a

View file

@ -0,0 +1,3 @@
a = [1,2]
b = [3,4]
a.pushAll[b]

View file

@ -0,0 +1,3 @@
val a : Array<T> = // initialise a
val b : Array<T> = // initialise b
val c = (a.toList() + b.toList()).copyToArray()

View file

@ -0,0 +1,2 @@
fun arrayConcat(a : Array<Any>, b : Array<Any>)
= Array<Any>(a.size + b.size, {if (it in a.indices) a[it] else b[it - a.size]})

View file

@ -0,0 +1,3 @@
val a : Collection<T> // initialise a
val b : Collection<T> = // initialise b
val c : Collection = a + b

View file

@ -1,7 +1,3 @@
NSArray *arr1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3], nil];
NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:4],
[NSNumber numberWithInt:5],
[NSNumber numberWithInt:6], nil];
NSArray *arr1 = @[@1, @2, @3];
NSArray *arr2 = @[@4, @5, @6];
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];

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