This commit is contained in:
Ingy döt Net 2013-06-05 21:47:54 +00:00
parent 1f1ad49427
commit 6f050a029e
2496 changed files with 37609 additions and 3031 deletions

View file

@ -1,36 +1,31 @@
import std.stdio;
import std.stdio, std.algorithm, std.range;
enum DoorState { Closed, Open }
alias DoorState[] Doors;
enum DoorState : bool { closed, open }
alias Doors = DoorState[];
Doors flipUnoptimized(Doors doors) {
doors[] = DoorState.Closed;
foreach (i; 0 .. doors.length)
for (int j = i; j < doors.length; j += i+1)
if (doors[j] == DoorState.Open)
doors[j] = DoorState.Closed;
Doors flipUnoptimized(Doors doors) pure nothrow {
doors[] = DoorState.closed;
foreach (immutable i; 0 .. doors.length)
for (int j = i; j < doors.length; j += i + 1)
if (doors[j] == DoorState.open)
doors[j] = DoorState.closed;
else
doors[j] = DoorState.Open;
doors[j] = DoorState.open;
return doors;
}
Doors flipOptimized(Doors doors) {
doors[] = DoorState.Closed;
for (int i = 1; i*i <= doors.length; i++)
doors[i*i - 1] = DoorState.Open;
Doors flipOptimized(Doors doors) pure nothrow {
doors[] = DoorState.closed;
for (int i = 1; i ^^ 2 <= doors.length; i++)
doors[i ^^ 2 - 1] = DoorState.open;
return doors;
}
// test program
void main() {
auto doors = new Doors(100);
foreach (i, door; flipUnoptimized(doors))
if (door == DoorState.Open)
write(i+1, " ");
writeln();
foreach (i, door; flipOptimized(doors))
if (door == DoorState.Open)
write(i+1, " ");
writeln();
foreach (const open; [doors.dup.flipUnoptimized,
doors.dup.flipOptimized])
iota(1, open.length + 1).filter!(i => open[i - 1]).writeln;
}

View file

@ -0,0 +1,15 @@
#AppType Console
Dim doors[], n As Integer = 100
For Dim i = 1 To n
For Dim j = i To n Step i
doors[j] = Not doors[j]
Next
Next
For i = 1 To n
If doors[i] Then Print "Door ", i, " is open"
Next
Pause

View file

@ -0,0 +1,12 @@
#APPTYPE CONSOLE
DIM i = 0, j = 0, door = 1
WHILE INCR(i) < 101
IF i = door THEN
PRINT "Door ", door, " open"
INCR(door, INCR((INCR(j) << 1)))
END IF
WEND
PAUSE

View file

@ -0,0 +1,23 @@
USING: bit-arrays formatting fry kernel math math.ranges
sequences ;
IN: rosetta.doors
CONSTANT: number-of-doors 100
: multiples ( n -- range )
0 number-of-doors rot <range> ;
: toggle-multiples ( n doors -- )
[ multiples ] dip '[ _ [ not ] change-nth ] each ;
: toggle-all-multiples ( doors -- )
[ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ;
: print-doors ( doors -- )
[
swap "open" "closed" ? "Door %d is %s\n" printf
] each-index ;
: main ( -- )
number-of-doors 1 + <bit-array>
[ toggle-all-multiples ] [ print-doors ] bi ;

View file

@ -0,0 +1,8 @@
USING:
formatting
math math.primes.factors math.ranges
sequences ;
IN: rosetta-doors2
: main ( -- )
100 [1,b] [ divisors length odd? ] filter "Open %[%d, %]\n" printf ;

View file

@ -1,13 +1,11 @@
public class Doors
{
public static void main(final String[] args)
{
boolean[] doors = new boolean[100];
for (int pass = 0; pass < 10; pass++)
doors[(pass + 1) * (pass + 1) - 1] = true;
for(int i = 0; i < 100; i++)
System.out.println("Door #" + (i + 1) + " is " + (doors[i] ? "open." : "closed."));
}
public static void main(String[] args)
{
boolean[] doors=new boolean[100];
for(int i=0;i<10;i++)
doors[i*(i+2)]=true;
for(int i=0;i<100;i++)
System.out.println("Door #"+(i+1)+" is"+(doors[i]?"open.":" closed."));
}
}

View file

@ -1,12 +1,8 @@
public class Doors
{
public static void main(final String[] args)
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++)
sb.append("Door #").append(i*i).append(" is open\n");
System.out.println(sb.toString());
}
public static void main(String[] args)
{
for(int i=0;i<10;i++)
System.out.println("Door #"+(i*(i+2)+1)+" is open.");
}
}

View file

@ -1,13 +1,13 @@
public class Doors{
public static void main(String[] args){
int i;
for(i = 1; i < 101; i++){
double sqrt = Math.sqrt(i);
if(sqrt != (int)sqrt){
System.out.println("Door " + i + " is closed");
}else{
System.out.println("Door " + i + " is open");
}
}
}
public class Doors
{
public static void main(final String[] args)
{
boolean[] doors = new boolean[100];
for (int pass = 0; pass < 10; pass++)
doors[(pass + 1) * (pass + 1) - 1] = true;
for(int i = 0; i < 100; i++)
System.out.println("Door #" + (i + 1) + " is " + (doors[i] ? "open." : "closed."));
}
}

View file

@ -0,0 +1,12 @@
public class Doors
{
public static void main(final String[] args)
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++)
sb.append("Door #").append(i*i).append(" is open\n");
System.out.println(sb.toString());
}
}

View file

@ -0,0 +1,13 @@
public class Doors{
public static void main(String[] args){
int i;
for(i = 1; i < 101; i++){
double sqrt = Math.sqrt(i);
if(sqrt != (int)sqrt){
System.out.println("Door " + i + " is closed");
}else{
System.out.println("Door " + i + " is open");
}
}
}
}

View file

@ -0,0 +1,31 @@
DECLARE
TYPE doorsarray IS VARRAY(100) OF BOOLEAN;
doors doorsarray := doorsarray();
BEGIN
doors.EXTEND(100); --ACCOMMODATE 100 DOORS
FOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE
LOOP
doors(i) := FALSE;
END LOOP;
FOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE
LOOP
FOR k IN 1 .. 100
LOOP
IF MOD(k,j)=0 THEN
doors(k) := NOT doors(k);
END IF;
END LOOP;
END LOOP;
FOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION
LOOP
DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE'
THEN 'OPEN'
ELSE 'CLOSED'
END);
END LOOP;
END;

View file

@ -0,0 +1,3 @@
1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""}
filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_}
invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host"

View file

@ -1,28 +1,17 @@
#lang racket
;; Like "map", but the proc must take an index as well as the element.
(define (map-index proc seq)
(for/list ([(elt i) (in-indexed seq)])
(proc elt i)))
;; Applies PROC to every STEPth element of SEQ, leaving the others
;; unchanged.
(define (map-step proc step seq)
(map-index
(lambda (elt i)
((if (zero? (remainder i step) )
proc
values) elt))
seq))
;; Applies fun to every step-th element of seq, leaving the others unchanged.
(define (map-step fun step seq)
(for/list ([elt seq] [i (in-naturals)])
((if (zero? (modulo i step)) fun values) elt)))
(define (toggle-nth n seq)
(map-step not n seq))
(define (solve seq)
(for/fold ([result seq])
([(_ pass) (in-indexed seq)])
(toggle-nth (add1 pass) result)))
(for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)])
(toggle-nth pass result)))
(for ([(door index) (in-indexed (solve (make-vector 100 #f)))])
(when door
(printf "~a is open~%" index)))
(for ([door (solve (make-vector 101 #f))] [index (in-naturals)]
#:when (and door (> index 0)))
(printf "~a is open~%" index))

View file

@ -1,6 +1,3 @@
#lang racket
(for-each (lambda (x) (printf "~a is open\n" x))
(filter (lambda (x)
(exact-integer? (sqrt x)))
(sequence->list (in-range 1 101))))
(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x)))
(printf "~a is open\n" x))

View file

@ -1,20 +1,16 @@
#lang slideshow
(define-syntax-rule (vector-neg-set! vec pos)
(define-syntax-rule (vector-neg! vec pos)
(vector-set! vec pos (not (vector-ref vec pos))))
(define (make-doors)
(define doors (make-vector 100 #f))
(for ([i (in-range 100)])
(for ([j (in-range i 100 (add1 i))])
(vector-neg-set! doors j)))
(for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j))
doors)
(displayln (list->string (for/list ([d (make-doors)])
(if d #\o #\-))))
(displayln (list->string (for/list ([d (make-doors)]) (if d #\o #\-))))
(define (closed-door) (inset (filled-rectangle 4 20) 2))
(define (open-door) (inset (rectangle 4 20) 2))
(define closed-door (inset (filled-rectangle 4 20) 2))
(define open-door (inset (rectangle 4 20) 2))
(for/fold ([doors (rectangle 0 0)])
([open? (make-doors)])
(hc-append doors (if open? (open-door) (closed-door))))
(for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)])
(hc-append doors (if open? open-door closed-door)))

View file

@ -1,31 +1,31 @@
class Door
attr_reader :state
def initialize
@state=:closed
end
def close; @state=:closed; end
def open; @state=:open; end
def closed?; @state==:closed; end
def open?; @state==:open; end
def toggle
if closed?
open
else
close
end
end
def to_s; @state.to_s; end
attr_reader :state
def initialize
@state=:closed
end
def close; @state=:closed; end
def open; @state=:open; end
def closed?; @state==:closed; end
def open?; @state==:open; end
def toggle
if closed?
open
else
close
end
end
def to_s; @state.to_s; end
end
doors=Array.new(100){Door.new}
1.upto(100) do |multiplier|
doors.each_with_index do |door, i|
door.toggle if (i+1)%multiplier==0
end
doors.each_with_index do |door, i|
door.toggle if (i+1)%multiplier==0
end
end
doors.each_with_index{|door, i| puts "Door #{i+1} is #{door}."}

View file

@ -1,19 +1,18 @@
n = 100
Open = "open"
Closed = "closed"
def Open.f
Closed
def Open.toggle
Closed
end
def Closed.f
Open
def Closed.toggle
Open
end
doors = [Closed] * (n+1)
for mul in 1..n
for x in 1..n
doors[mul*x] = (doors[mul*x] || break).f
end
for x in 1..n/mul
doors[mul*x] = doors[mul*x].toggle
end
end
doors.each_with_index {
|b, i|
puts "Door #{i} is #{b}" if i>0
doors.each_with_index { |b, i|
puts "Door #{i} is #{b}" if i>0
}

View file

@ -1,4 +1,4 @@
n = 100
(1..n).each do |i|
puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}"
puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}"
end

View file

@ -1,7 +1,7 @@
doors = [false] * 100
100.times do |i|
(i .. doors.length).step(i+1) do |j|
(i ... doors.length).step(i+1) do |j|
doors[j] = !doors[j]
end
end
puts doors.inspect
puts doors.map.with_index{|d,i| "Door #{i+1} is #{d ? 'open' : 'closed'}."}

View file

@ -0,0 +1,15 @@
fn main() {
let mut door_open = [false, ..100];
for uint::range(1, 101) |pass| {
for uint::range(1, 101) |door| {
if door % pass == 0 {
door_open[door - 1] = !door_open[door - 1]
}
};
}
for door_open.eachi |i, state| {
io::println(fmt!("Door %u is %s.", i + 1,
if *state { "open" } else { "closed" }));
}
}

View file

@ -0,0 +1,7 @@
fn main() {
for int::range(1,101) |i| {
let x = float::pow(i as f64, 0.5);
let state = if x == float::round(x) {"open"} else {"closed"};
io::println(fmt!("Door %i is %s", i, state));
}
}

View file

@ -1,54 +1,47 @@
("100doors")
100doors
(100doors)
comment
(always)
(message) (first) 100 (100passes) (doors)
(pr) (first) 100 (passes) 1 (doors)
(doors)
an infinite list of closed doors
comment
(always)
(c) "'closed" (doors)
(100passes) doors
[open closed closed closed ...]
(always)
(100passes1) 1 doors
(100passes1) count doors
101 [open closed closed open ...]
(passes) count doors
comment
(>) count 100
doors
(100passes1) count doors
3 [open closed open closed ...]
(passes) count doors
comment
(always)
(100passes1) (add1) count
(flip-and-count) count doors
(passes) (add1) count
(pass) count doors
(flip-and-count) frequency doors
3 [open closed open closed ...]
(pass) n doors
comment
(always)
(flip-and-count1) frequency frequency doors
(pass1) n n doors
(flip-and-count1) frequency count doors
3 1 [open closed open closed ...]
(=) count 1
(c) (flip-door-state) (1) doors
(flip-and-count) frequency (!) doors
(pass1) n m doors
comment
(=) m 1
(c) (toggle) (1) doors
(pass) n (!) doors
(flip-and-count1) frequency count doors
3 3 [open closed open closed ...]
(always)
(pass1) n m doors
comment
(>) m 1
(c) (1) doors
(flip-and-count1) frequency
(sub1) count
(!) doors
(pass1) n (sub1) m (!) doors
(flip-door-state) state
'closed
(=) state "'closed"
(toggle) door
comment
(=) door "'closed"
"'open"
(flip-door-state) state
'open
(=) state "'open"
(toggle) door
comment
(=) door "'open"
"'closed"

View file

@ -0,0 +1,19 @@
function solve24(nums)
length(nums) != 4 && error("Input must be a 4-element Array")
syms = [+,-,*,/]
for x in syms, y in syms, z in syms
for i = 1:24
a,b,c,d = nthperm(nums,i)
if round(x(y(a,b),z(c,d)),5) == 24
return "($a$y$b)$x($c$z$d)"
elseif round(x(a,y(b,z(c,d))),5) == 24
return "$a$x($b$y($c$z$d))"
elseif round(x(y(z(c,d),b),a),5) == 24
return "(($c$z$d)$y$b)$x$a"
elseif round(x(y(b,z(c,d)),a),5) == 24
return "($b$y($c$z$d))$x$a"
end
end
end
return "0"
end

View file

@ -0,0 +1,16 @@
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
[o2n (object-name o2)]
[o3n (object-name o3)])
(with-handlers ((exn:fail:contract:divide-by-zero? (λ (_) empty-sequence)))
(in-parallel
(list (o1 (o2 (o3 n1 n2) n3) n4)
(o1 (o2 n1 (o3 n2 n3)) n4)
(o1 (o2 n1 n2) (o3 n3 n4))
(o1 n1 (o2 (o3 n2 n3) n4))
(o1 n1 (o2 n2 (o3 n3 n4))))
(list `(((,n1 ,o3n ,n2) ,o2n ,n3) ,o1n ,n4)
`((,n1 ,o2n (,n2 ,o3n ,n3)) ,o1n ,n4)
`((,n1 ,o2n ,n2) ,o1n (,n3 ,o3n ,n4))
`(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4))
`(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4))))))))

View file

@ -0,0 +1,15 @@
(define (find-solutions numbers (goal 24))
(define in-operations (list + - * /))
(remove-duplicates
(for*/list ([n1 numbers]
[n2 (remove-from numbers n1)]
[n3 (remove-from numbers n1 n2)]
[n4 (remove-from numbers n1 n2 n3)]
[o1 in-operations]
[o2 in-operations]
[o3 in-operations]
[(res expr) (in-variants n1 o1 n2 o2 n3 o3 n4)]
#:when (= res goal))
expr)))
(define (remove-from numbers . n) (foldr remq numbers n))

View file

@ -0,0 +1,42 @@
USING:
combinators.short-circuit
continuations
eval
formatting
fry
kernel
io
math math.ranges
prettyprint
random
sequences
sets ;
IN: 24game
: choose4 ( -- seq )
4 [ 9 [1,b] random ] replicate ;
: step ( numbers -- ? )
readln
[
parse-string
{
! Is only allowed tokens used?
[ swap { + - / * } append subset? ]
! Digit count in expression should be equal to the given numbers.
[ [ number? ] count swap length = ]
! Of course it must evaluate to 24
[ nip call( -- x ) 24 = ]
} 2&&
[ f "You got it!" ]
[ t "Expression isnt valid, or doesnt evaluate to 24." ]
if
]
[ 3drop f "Could not parse that." ]
recover print flush ;
: main ( -- )
choose4
[ "Your numbers are %[%s, %], make an expression\n" printf flush ]
[ '[ _ step ] loop ]
bi ;

View file

@ -0,0 +1,4 @@
IN: scratchpad main
Your numbers are { 4, 1, 8, 2 }, make an expression
8 4 + 2 * 1 /
You got it!

View file

@ -0,0 +1,56 @@
function twentyfour()
function check(input)
d = ref(Int)
for i in input.args
if typeof(i) == Expr
c = check(i)
typeof(c) == String || append!(d,c)
elseif contains([:*,:/,:-,:+],i)
continue
elseif contains([1:9],i)
push!(d,i)
continue
elseif i > 9 || i < 1
d = "Sorry, $i is not allowed, please use only numbers between 1 and 9"
else
d = "Sorry, $i isn't allowed"
end
end
return d
end
new_digits() = [rand(1:9),rand(1:9),rand(1:9),rand(1:9)]
answer = new_digits()
print("The 24 Game\nYou will be given any four digits in the range 1 to 9, which may have repetitions.\n
Using just the +, -, *, and / operators show how to make an answer of 24.\n
Use parentheses, (), to ensure proper order of evaulation.\n
Enter 'n' for a new set of digits, and 'q' to quit. Good luck!\n
Here's your first 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n
>")
while true
input = chomp(readline(STDIN))
input == "q" && break
if input == "n"
answer = new_digits()
print("\nLet's try again, go ahead and guess\n Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n>")
continue
end
input = try
parse(input)
catch
print("I couldn't calculate your answer, please try again\n>");
continue
end
c = check(input)
cc = all([sum(i .== answer) == sum(i .== c) for i in answer])
!cc && (print("Sorry, valid digits are \n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n are allowed and all four must be used. Please try again\n>"); continue)
if eval(input) == 24
answer = new_digits()
print("\nYou did it!\nLet's do another round, or enter 'q' to quit\n
Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n
>")
continue
else
print("\nSorry your answer calculates to $(eval(input))\nTry again\n>")
end
end
end

View file

@ -0,0 +1,35 @@
#lang racket
(define (interprete expr numbers)
;; the cashe for used numbers
(define cashe numbers)
;; updating the cashe and handling invalid cases
(define (update-cashe! x)
(unless (member x numbers) (error "Number is not in the given set:" x))
(unless (member x cashe) (error "Number is used more times then it was given:" x))
(set! cashe (remq x cashe)))
;; the parser
(define parse
(match-lambda
;; parsing arythmetics
[`(,x ... + ,y ...) (+ (parse x) (parse y))]
[`(,x ... - ,y ...) (- (parse x) (parse y))]
[`(,x ... * ,y ...) (* (parse x) (parse y))]
[`(,x ... / ,y ...) (/ (parse x) (parse y))]
[`(,x ,op ,y ...) (error "Unknown operator: " op)]
;; opening redundant brackets
[`(,expr) (parse expr)]
;; parsing numbers
[(? number? x) (update-cashe! x) x]
;; unknown token
[x (error "Not a number: " x)]))
;; parse the expresion
(define result (parse expr))
;; return the result if cashe is empty
(if (empty? cashe)
result
(error "You didn`t use all numbers!")))

View file

@ -0,0 +1,36 @@
;; starting the program
(define (start)
(displayln "Combine given four numbers using operations + - * / to get 24.")
(displayln "Input 'q' to quit or your answer like '1 - 3 * (2 + 3)'")
(new-game))
;; starting a new game
(define (new-game)
;; create a new number set
(define numbers (build-list 4 (λ (_) (+ 1 (random 9)))))
(apply printf "Your numbers: ~a ~a ~a ~a\n" numbers)
(new-input numbers))
;; processing a new user input
(define (new-input numbers)
;; if an exception is raized while processing, show the exeption message
;; and prompt for another input, but do not stop the program.
(with-handlers ([exn? (λ (exn)
(displayln (exn-message exn))
(new-input numbers))])
;; get the answer
(define user-expr (read-the-answer))
;; interprete it
(case user-expr
[(q) (display "Good buy!")]
[(n) (new-game)]
[else (define ans (interprete user-expr numbers))
(case ans
[(24) (printf "Indeed! ~a = 24\n" user-expr)
(new-game)]
[else (error "Wrong!" user-expr '= ans)])])))
;; reading and preparing the user's answer
;; "1 + 2 * (3 + 4)" --> '(1 + 2 * (3 + 4))
(define (read-the-answer)
(read (open-input-string (format "(~a)" (read-line)))))

View file

@ -1,6 +1,4 @@
#Option Explicit
#AppType Console
#Include <Include/Windows.inc>
Class Wall
bottles

View file

@ -1,11 +1,8 @@
#lang racket
(define (plural n)
(string-append (number->string n) " bottle" (if (equal? n 1) "" "s")))
(define (sing bottles)
(printf "~a of beer on the wall\n~a of beer\nTake on down, pass it around\n~a of beer on the wall\n\n"
(plural bottles) (plural bottles) (plural (sub1 bottles))))
(for ((i (in-range 100 0 -1)))
(sing i))
(define (plural n) (~a n " bottle" (if (= n 1) "" "s")))
(printf "~a of beer on the wall\n~a of beer\n~
Take one down, pass it around\n~a of beer on the wall\n\n"
(plural bottles) (plural bottles) (plural (sub1 bottles)))
(unless (= 1 bottles) (sing (sub1 bottles))))
(sing 100)

View file

@ -0,0 +1,13 @@
99 0 1 range each as $i
$i 1 = if
"bottle" as $b
else
"bottles" format as $b
$b $i "%d %s of beer on the wall,\n" print
$b $i "%d %s of beer,\n" print
"Take one down, pass it around,\n" print
$i 2 = if
"1 bottle"
else
$i 1 - "%d bottles" format
"%s of beer on the wall.\n\n" print

20
Task/A+B/COBOL/a+b.cobol Normal file
View file

@ -0,0 +1,20 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. A-Plus-B.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A PIC S9(5).
01 B PIC S9(5).
01 A-B-Sum PIC S9(5).
PROCEDURE DIVISION.
ACCEPT A
ACCEPT B
ADD A TO B GIVING A-B-Sum
DISPLAY A-B-Sum
GOBACK
.

7
Task/A+B/FBSL/a+b.fbsl Normal file
View file

@ -0,0 +1,7 @@
#APPTYPE CONSOLE
DIM %a, %b
SCANF("%d%d", @a, @b)
PRINT a, "+", b, "=", a + b
PAUSE

View file

@ -4,6 +4,6 @@ import "fmt"
func main() {
var a, b int
fmt.Scanf("%d %d", &a, &b)
fmt.Printf("%d\n", a+b)
fmt.Scan(&a, &b)
fmt.Println(a + b)
}

6
Task/A+B/Julia/a+b.julia Normal file
View file

@ -0,0 +1,6 @@
#A+B
function AB()
input = sum(map(int,split(readline(STDIN)," ")))
println(input)
end
AB()

View file

@ -1,5 +1,5 @@
("A+B")
A+B
(A+B)
comment
(always)
(+) (read) (default-input-port)
(read) (default-input-port)

View file

@ -0,0 +1,15 @@
Class Abstract.Class.Shape [ Abstract ]
{
Parameter SHAPE = 1;
Property Name As %String;
Method Description() {}
}
Class Abstract.Class.Square Extends (%RegisteredObject, Shape)
{
Method Description()
{
Write "SHAPE=", ..#SHAPE, !
Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape"
}
}

View file

@ -0,0 +1,14 @@
Class Abstract.DataType.Shape [ ClassType = datatype ]
{
Parameter SHAPE = 1;
Method Description() {}
}
Class Abstract.DataType.Square Extends (%RegisteredObject, Shape)
{
Method Description()
{
Write "SHAPE=", ..#SHAPE, !
Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape"
}
}

View file

@ -0,0 +1,2 @@
abstract «name»
abstract «name» <: «supertype»

View file

@ -0,0 +1,6 @@
abstract Number
abstract Real <: Number
abstract FloatingPoint <: Real
abstract Integer <: Real
abstract Signed <: Integer
abstract Unsigned <: Integer

View file

@ -1,20 +1,7 @@
julia> function accumulator(i)
function f(n)
i += n
return i
end
return f
function accumulator(i)
f(n) = i += n
end
# method added to generic function accumulator
julia> x = accumulator(1)
# methods for generic function f
f(Any,) at none:3
julia> x(5)
6
julia> print(accumulator(3))
f
julia> print(x(2.3))
8.3
x = accumulator(1)
x(5)
accumulator(3)
x(2.3)

View file

@ -1,6 +1,4 @@
#lang racket
(define (accumulator n)
(lambda (i)
(set! n (+ n i))
n))
(define ((accumulator n) i)
(set! n (+ n i))
n)

View file

@ -3,7 +3,7 @@ note
URI: "http://rosettacode.org/wiki/Ackermann_function"
class
ACKERMAN_EXAMPLE
APPLICATION
create
make
@ -27,15 +27,14 @@ feature {NONE} -- Initialization
feature -- Access
ackerman (m: NATURAL; n: NATURAL): NATURAL
ackerman (m, n: NATURAL): NATURAL
do
if m = 0 then
Result := n + 1
elseif m > 0 and n = 0 then
elseif n = 0 then
Result := ackerman (m - 1, 1)
elseif m > 0 and n > 0 then
else
Result := ackerman (m - 1, ackerman (m, n - 1))
end
end
end

View file

@ -1,10 +1,8 @@
-module(main).
-export([main/1]).
-module(ack).
-export([main/1, ack/2]).
main( [ A | [ B |[]]]) ->
io:fwrite("~p~n",[ack(toi(A),toi(B))]).
toi(E) -> element(1,string:to_integer(E)).
main( [A, B] ) ->
io:fwrite( "~p~n",[ack(erlang:list_to_integer(A), erlang:list_to_integer(B))] ).
ack(0,N) -> N + 1;
ack(M,0) -> ack(M-1, 1);

View file

@ -0,0 +1,22 @@
#APPTYPE CONSOLE
TestAckermann()
PAUSE
SUB TestAckermann()
FOR DIM m = 0 TO 3
FOR DIM n = 0 TO 10
PRINT AckermannF(m, n), " ";
NEXT
PRINT
NEXT
END SUB
FUNCTION AckermannF(m AS INTEGER, n AS INTEGER) AS INTEGER
IF NOT m THEN RETURN n + 1
IF NOT n THEN RETURN AckermannA(m - 1, 1)
RETURN AckermannC(m - 1, AckermannF(m, n - 1))
END FUNCTION
DYNC AckermannC(m AS INTEGER, n AS INTEGER) AS INTEGER

View file

@ -0,0 +1,11 @@
int Ackermann(int m, int n)
{
if (!m) return n + 1;
if (!n) return Ackermann(m - 1, 1);
return Ackermann(m - 1, Ackermann(m, n - 1));
}
int main(int m, int n)
{
return Ackermann(m, n);
}

View file

@ -0,0 +1,3 @@
END DYNC
DYNASM AckermannA(m AS INTEGER, n AS INTEGER) AS INTEGER

View file

@ -0,0 +1,35 @@
ENTER 0, 0
INVOKE Ackermann, m, n
LEAVE
RET
@Ackermann
ENTER 0, 0
.IF DWORD PTR [m] .THEN
JMP @F
.ENDIF
MOV EAX, n
INC EAX
JMP xit
@@
.IF DWORD PTR [n] .THEN
JMP @F
.ENDIF
MOV EAX, m
DEC EAX
INVOKE Ackermann, EAX, 1
JMP xit
@@
MOV EAX, n
DEC EAX
INVOKE Ackermann, m, EAX
MOV ECX, m
DEC ECX
INVOKE Ackermann, ECX, EAX
@xit
LEAVE
RET 8

View file

@ -0,0 +1 @@
END DYNASM

View file

@ -0,0 +1,9 @@
function ack(m,n)
if m == 0
return n + 1
elseif n == 0
return ack(m-1,1)
else
return ack(m-1,ack(m,n-1))
end
end

View file

@ -0,0 +1 @@
ack2(m,n) = m == 0 ? n + 1 : n == 0 ? ack2(m-1,1) : ack2(m-1,ack2(m,n-1))

View file

@ -1,7 +1,5 @@
#lang racket
(define (ackermann m n)
(cond [(zero? m) (add1 n)]
[(and (> m 0) (zero? n))
(ackermann (sub1 m) 1)]
[(and (> m 0) (> n 0))
(ackermann (sub1 m) (ackermann m (sub1 n)))]))
[(zero? n) (ackermann (sub1 m) 1)]
[else (ackermann (sub1 m) (ackermann m (sub1 n)))]))

View file

@ -1,14 +1,14 @@
("ackermann") m n
(ackermann) m n
0 3
(zero?) m
(add1) n
("ackermann") m n
(ackermann) m n
2 0
(and) (positive?) m (zero?) n
("ackermann") (sub1) m 1
(ackermann) (sub1) m 1
("ackermann") m n
(ackermann) m n
2 3
(and) (positive?) m (positive?) n
("ackermann") (sub1) m ("ackermann") m (sub1) n
(ackermann) (sub1) m (ackermann) m (sub1) n

View file

@ -0,0 +1,7 @@
-module(ldap_example).
-export( [main/1] ).
main( [Host, DN, Password] ) ->
{ok, Handle} = eldap:open( [Host] ),
ok = eldap:simple_bind( Handle, DN, Password ),
eldap:close( Handle ).

View file

@ -0,0 +1,16 @@
#lang racket
(require ffi/unsafe ffi/unsafe/define)
(define-ffi-definer defldap (ffi-lib "libldap"))
(defldap ldap_init (_fun _string _int -> _pointer))
(defldap ldap_unbind (_fun _pointer -> _void))
(defldap ldap_simple_bind_s (_fun _pointer _string _string -> _int))
(defldap ldap_err2string (_fun _int -> _string))
(define name ...)
(define password ...)
(define ld (ldap_init "ldap.somewhere.com" 389))
(ldap_simple_bind_s ld name password)
(ldap_unbind ld)

View file

@ -0,0 +1,62 @@
-module( active_object ).
-export( [delete/1, input/2, new/0, output/1, task/1] ).
-compile({no_auto_import,[time/0]}).
delete( Object ) ->
Object ! stop.
input( Object, Fun ) ->
Object ! {input, Fun}.
new( ) ->
K = fun zero/1,
S = 0,
T0 = seconds_with_decimals(),
erlang:spawn( fun() -> loop(K, S, T0) end ).
output( Object ) ->
Object ! {output, erlang:self()},
receive
{output, Object, Output} -> Output
end.
task( Integrate_millisec ) ->
Object = new(),
{ok, _Ref} = timer:send_interval( Integrate_millisec, Object, integrate ),
io:fwrite( "New ~p~n", [output(Object)] ),
input( Object, fun sine/1 ),
timer:sleep( 2000 ),
io:fwrite( "Sine ~p~n", [output(Object)] ),
input( Object, fun zero/1 ),
timer:sleep( 500 ),
io:fwrite( "Approx ~p~n", [output(Object)] ),
delete( Object ).
loop( Fun, Sum, T0 ) ->
receive
integrate ->
T1 = seconds_with_decimals(),
New_sum = trapeze( Sum, Fun, T0, T1 ),
loop( Fun, New_sum, T1 );
stop ->
ok;
{input, New_fun} ->
loop( New_fun, Sum, T0 );
{output, Pid} ->
Pid ! {output, erlang:self(), Sum},
loop( Fun, Sum, T0 )
end.
sine( T ) ->
math:sin( 2 * math:pi() * 0.5 * T ).
seconds_with_decimals() ->
{Megaseconds, Seconds, Microseconds} = os:timestamp(),
(Megaseconds * 1000000) + Seconds + (Microseconds / 1000000).
trapeze( Sum, Fun, T0, T1 ) ->
Sum + (Fun(T1) + Fun(T0)) * (T1 - T0) / 2.
zero( _ ) -> 0.

View file

@ -0,0 +1,94 @@
#APPTYPE CONSOLE
#INCLUDE <Include\Windows.inc>
DIM Entity AS NEW Integrator(): Sleep(2000) ' respawn and do the job
Entity.Relax(): Sleep(500) ' get some rest
PRINT ">>> ", Entity.Yield(): DELETE Entity ' report and die
PAUSE
' ------------- End Program Code -------------
#DEFINE SpawnMutex CreateMutex(NULL, FALSE, "mutex")
#DEFINE LockMutex WaitForSingleObject(mutex, INFINITE)
#DEFINE UnlockMutex ReleaseMutex(mutex)
#DEFINE KillMutex CloseHandle(mutex)
CLASS Integrator
PRIVATE:
TYPE LARGE_INTEGER
lowPart AS INTEGER
highPart AS INTEGER
END TYPE
DIM dfreq AS DOUBLE, dlast AS DOUBLE, dnow AS DOUBLE, llint AS LARGE_INTEGER
DIM dret0 AS DOUBLE, dret1 AS DOUBLE, mutex AS INTEGER, sum AS DOUBLE, thread AS INTEGER
' --------------------------------------------
SUB INITIALIZE()
mutex = SpawnMutex
QueryPerformanceFrequency(@llint)
dfreq = LargeInt2Double(llint)
QueryPerformanceCounter(@llint)
dlast = LargeInt2Double(llint) / dfreq
thread = FBSLTHREAD(ADDRESSOF Sampler)
FBSLTHREADRESUME(thread)
END SUB
SUB TERMINATE()
' nothing special
END SUB
' --------------------------------------------
SUB Sampler()
DO
LockMutex
Sleep(5)
QueryPerformanceCounter(@llint)
dnow = LargeInt2Double(llint) / dfreq
dret0 = Task(dlast): dret1 = Task(dnow)
sum = sum + (dret1 + dret0) * (dnow - dlast) / 2
dlast = dnow
UnlockMutex
LOOP
END SUB
FUNCTION LargeInt2Double(obj AS VARIANT) AS DOUBLE
STATIC ret
ret = obj.highPart
IF obj.highPart < 0 THEN ret = ret + (2 ^ 32)
ret = ret * 2 ^ 32
ret = ret + obj.lowPart
IF obj.lowPart < 0 THEN ret = ret + (2 ^ 32)
RETURN ret
END FUNCTION
PUBLIC:
METHOD Relax()
LockMutex
ADDRESSOF Task = ADDRESSOF Idle
UnlockMutex
END METHOD
METHOD Yield() AS DOUBLE
LockMutex
Yield = sum
FBSLTHREADKILL(thread)
UnlockMutex
KillMutex
END METHOD
END CLASS
FUNCTION Idle(BYVAL t AS DOUBLE) AS DOUBLE
RETURN 0.0
END FUNCTION
FUNCTION Task(BYVAL t AS DOUBLE) AS DOUBLE
RETURN SIN(2 * PI * 0.5 * t)
END FUNCTION

View file

@ -0,0 +1,31 @@
#APPTYPE CONSOLE
CLASS Growable
PRIVATE:
DIM instructions AS STRING = "Sleep(1)"
:ExecCode
DIM dummy AS INTEGER = EXECLINE(instructions, 1)
PUBLIC:
METHOD Absorb(code AS STRING)
instructions = code
GOTO ExecCode
END METHOD
METHOD Yield() AS VARIANT
RETURN result
END METHOD
END CLASS
DIM Sponge AS NEW Growable()
Sponge.Absorb("DIM b AS VARIANT = 1234567890: DIM result AS VARIANT = b")
PRINT Sponge.Yield()
Sponge.Absorb("b = ""Hello world!"": result = b")
PRINT Sponge.Yield()
PAUSE

View file

@ -0,0 +1,35 @@
#APPTYPE CONSOLE
DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
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."
DIM lines[] = SPLIT(s, CRLF), tokens[], l, t, length, margin, justify = "center"
FOREACH l IN lines
tokens = SPLIT(l, "$")
FOREACH t IN tokens
IF STRLEN(t) > length THEN length = INCR(STRLEN)
NEXT
NEXT
FOREACH l IN lines
tokens = SPLIT(l, "$")
FOREACH t IN tokens
SELECT CASE justify
CASE "left"
PRINT t, SPACE(length - STRLEN(t));
CASE "center"
margin = (length - STRLEN(t)) \ 2
PRINT SPACE(margin), t, SPACE(length - STRLEN - margin);
CASE "right"
PRINT SPACE(length - STRLEN(t)), t;
END SELECT
NEXT
PRINT
NEXT
PAUSE

View file

@ -0,0 +1,50 @@
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
bool is_deranged(const std::string& left, const std::string& right)
{
return (left.size() == right.size()) &&
(std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus<int>(), std::equal_to<char>()) == 0);
}
int main()
{
std::ifstream input("unixdict.txt");
if (!input) {
std::cerr << "can't open input file\n";
return EXIT_FAILURE;
}
typedef std::set<std::string> WordList;
typedef std::map<std::string, WordList> AnagraMap;
AnagraMap anagrams;
std::pair<std::string, std::string> result;
size_t longest = 0;
for (std::string value; input >> value; /**/) {
std::string key(value);
std::sort(key.begin(), key.end());
if (longest < value.length()) { // is it a long candidate?
if (0 < anagrams.count(key)) { // is it an anagram?
for (const auto& prior : anagrams[key]) {
if (is_deranged(prior, value)) { // are they deranged?
result = std::make_pair(prior, value);
longest = value.length();
}
}
}
}
anagrams[key].insert(value);
}
std::cout << result.first << ' ' << result.second << '\n';
return EXIT_SUCCESS;
}

View file

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

View file

@ -0,0 +1,28 @@
import std.stdio, std.file, std.algorithm, std.string,
std.typecons, std.range, std.functional;
auto findDeranged(in string[] words) pure /*nothrow*/ {
//return words.pairwise.filter!(ww=> ww[].zip.all!q{a[0] != a[1]});
Tuple!(string, string)[] result;
foreach (immutable i, const w1; words)
foreach (const w2; words[i + 1 .. $])
if (zip(w1, w2).all!q{ a[0] != a[1] })
result ~= tuple(w1, w2);
return result;
}
void main() {
Appender!(string[])[30] wClasses;
foreach (word; std.algorithm.splitter("unixdict.txt".readText))
wClasses[$ - word.length] ~= word;
"Longest deranged anagrams:".writeln;
foreach (words; wClasses[].map!q{ a.data }.filter!(not!empty)) {
string[][const ubyte[]] anags; // Assume ASCII input.
foreach (w; words)
anags[w.dup.representation.sort().release.idup] ~= w;
auto pairs = anags.byValue.map!findDeranged.join;
if (!pairs.empty)
return writefln(" %s, %s", pairs.front[]);
}
}

View file

@ -0,0 +1,45 @@
-module( deranged_anagrams ).
-export( [task/0] ).
task() ->
httpc_start(),
Words = words( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ),
Anagram_dict = anagrams:fetch( Words, dict:new() ),
Deranged_anagrams = deranged_anagrams( Anagram_dict ),
{_Length, Longest_anagrams} = dict:fold( fun keep_longest/3, {0, []}, Deranged_anagrams ),
Longest_anagrams.
deranged_anagrams( Dict ) ->
Deranged_dict = dict:map( fun deranged_words/2, Dict ),
dict:filter( fun is_anagram/2, Deranged_dict ).
deranged_words( _Key, [H | T] ) ->
[{H, X} || X <- T, is_deranged_word(H, X)].
httpc_start() ->
inets:start(),
inets:start( httpc, [] ).
keep_longest( _Key, [{One, _} | _]=New, {Length, Acc} ) ->
keep_longest_new( erlang:length(One), Length, New, Acc ).
keep_longest_new( New_length, Acc_length, New, _Acc ) when New_length > Acc_length ->
{New_length, New};
keep_longest_new( New_length, Acc_length, New, Acc ) when New_length =:= Acc_length ->
{Acc_length, Acc ++ New};
keep_longest_new( _New_length, Acc_length, _New, Acc ) ->
{Acc_length, Acc}.
is_anagram( _Key, [] ) -> false;
is_anagram( _Key, _Value ) -> true.
is_deranged_word( Word1, Word2 ) ->
lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ).
is_deranged_char( {One, Two} ) -> One =/= Two.
words( URL ) ->
{ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ),
string:tokens( Body, "\n" ).

View file

@ -2,17 +2,15 @@ from itertools import izip, ifilter
from collections import defaultdict
def find_deranged(words):
result = []
for i, w1 in enumerate(words):
for w2 in words[i+1:]:
if all(a != b for a,b in izip(w1, w2)):
result.append((w1, w2))
return result
return [(w1, w2) for i, w1 in enumerate(words)
for w2 in words[i + 1:]
if all(a != b for a,b in izip(w1, w2))]
def main():
wclasses = [[] for _ in xrange(30)]
for word in open("unixdict.txt").read().split():
wclasses[-len(word)].append(word)
print "Longest deranged anagrams:"
for words in ifilter(None, wclasses):
anags = defaultdict(list)

View file

@ -0,0 +1,42 @@
#lang racket
(define word-list-file "data/unixdict.txt")
(define (read-words-into-anagram-keyed-hash)
(define (anagram-key word) (sort (string->list word) char<?))
(for/fold ((hsh (hash)))
((word (in-lines)))
(hash-update hsh (anagram-key word) (curry cons word) null)))
(define anagrams-list
(sort
(for/list
((v (in-hash-values
(with-input-from-file
word-list-file
read-words-into-anagram-keyed-hash)))
#:when (> (length v) 1)) v)
> #:key (compose string-length first)))
(define (deranged-anagram-pairs l (acc null))
(define (deranged-anagram-pair? hd tl)
(define (first-underanged-char? hd tl)
(for/first
(((c h) (in-parallel hd tl))
#:when (char=? c h)) c))
(not (first-underanged-char? hd tl)))
(if (null? l) acc
(let ((hd (car l)) (tl (cdr l)))
(deranged-anagram-pairs
tl
(append acc (map (lambda (x) (list hd x))
(filter (curry deranged-anagram-pair? hd) tl)))))))
;; for*/first give the first set of deranged anagrams (as per the RC problem)
;; for*/list gives a full list of the sets of deranged anagrams (which might be interesting)
(for*/first
((anagrams (in-list anagrams-list))
(daps (in-value (deranged-anagram-pairs anagrams)))
#:unless (null? daps))
daps)

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,17 @@
#!/bin/gawk -f
{ patsplit($0, chars, ".")
asort(chars)
sorted = ""
for (i = 1; i <= length(chars); i++)
sorted = sorted chars[i]
if (++count[sorted] > countMax) countMax++
accum[sorted] = accum[sorted] " " $0
}
END {
for (i in accum)
if (count[i] == countMax)
print substr(accum[i], 2)
}

View file

@ -2,9 +2,9 @@
(def groups
(with-open [r (io/reader wordfile)]
(group-by sort (line-seq r)))
(group-by sort (line-seq r))))
(let [wordlists (sort-by (comp - count) (vals groups)
(let [wordlists (sort-by (comp - count) (vals groups))
maxlength (count (first wordlists))]
(doseq [wordlist (take-while #(= (count %) maxlength) wordlists)]
(println wordlist))

View file

@ -1,9 +1,9 @@
import std.stdio, std.algorithm, std.range, std.string;
import std.stdio, std.algorithm, std.range, std.string, std.exception;
void main() {
dstring[][dstring] anags;
foreach (dchar[] w; File("unixdict.txt").lines())
anags[w.chomp().sort().release().idup] ~= w.chomp().idup;
immutable m = anags.byValue.map!(ws => ws.length)().reduce!max();
writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m)());
string[][const ubyte[]] an;
foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no))
an[w.dup.representation.sort().release.assumeUnique] ~= w.idup;
immutable m = an.byValue.map!q{ a.length }.reduce!max;
writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m));
}

View file

@ -1,13 +1,13 @@
import std.stdio, std.algorithm, std.file;
import std.stdio, std.algorithm, std.file, std.string;
void main() {
char[] keys = cast(char[])read("unixdict.txt");
string vals = keys.idup;
char[] keys = cast(char[])"unixdict.txt".read;
immutable vals = keys.idup;
string[][string] anags;
foreach (w; std.array.splitter(keys)) {
const k = cast(string)sort(cast(ubyte[])w).release();
foreach (w; keys.splitter) {
immutable k = cast(string)w.representation.sort().release;
anags[k] ~= vals[k.ptr-keys.ptr .. k.ptr-keys.ptr + k.length];
}
immutable m = anags.byValue.map!(ws => ws.length)().reduce!max();
writefln("%(%s\n%)", filter!(ws => ws.length == m)(anags.byValue));
immutable m = anags.byValue.map!q{ a.length }.reduce!max;
writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m));
}

View file

@ -0,0 +1,160 @@
#APPTYPE CONSOLE
DIM gtc = GetTickCount()
Anagram()
PRINT "Done in ", (GetTickCount() - gtc) / 1000, " seconds"
PAUSE
DYNC Anagram()
#include <windows.h>
#include <stdio.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 = (HashEntry)malloc(sizeof(struct sHashEntry));
he->next = NULL;
he->key = strdup(hkey);
he->wordCount = 0;
he->words = NULL;
he->link = NULL;
*hep = he;
}
we = (DictWord)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;
}
void main()
{
HashEntry he;
DictWord we;
FILE* f1;
f1 = fopen("unixdict.txt", "r");
buildAnagrams(f1);
fclose(f1);
f1 = fopen("anaout.txt", "w");
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);
}
END DYNC

View file

@ -0,0 +1,4 @@
"resource:unixdict.txt" utf8 file-lines
[ [ natural-sort >string ] keep ] { } map>assoc sort-keys
[ [ first ] compare +eq+ = ] monotonic-split
dup 0 [ length max ] reduce '[ length _ = ] filter [ values ] map .

View file

@ -0,0 +1,8 @@
{
{ "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

@ -1,14 +1,14 @@
let explode str =
let l = ref [] in
let len = String.length str in
for i = len - 1 downto 0 do
let n = String.length str in
for i = n - 1 downto 0 do
l := str.[i] :: !l
done;
(!l)
let implode li =
let len = List.length li in
let s = String.create len in
let n = List.length li in
let s = String.create n in
let i = ref 0 in
List.iter (fun c -> s.[!i] <- c; incr i) li;
(s)
@ -18,7 +18,7 @@ let () =
let ic = open_in "unixdict.txt" in
try while true do
let w = input_line ic in
let k = implode(List.sort compare (explode w)) in
let k = implode (List.sort compare (explode w)) in
let l =
try Hashtbl.find h k
with Not_found -> []
@ -29,6 +29,5 @@ let () =
Hashtbl.iter (fun _ lw ->
if List.length lw >= n then
( List.iter (Printf.printf " %s") lw;
print_newline())
) h;
;;
print_newline () )
) h

View file

@ -0,0 +1,21 @@
#lang racket
(require net/url)
(define (get-lines url-string)
(define port (get-pure-port (string->url url-string)))
(for/list ([l (in-lines port)]) l))
(define (hash-words words)
(for/fold ([ws-hash (hash)]) ([w words])
(hash-update ws-hash
(list->string (sort (string->list w) < #:key (λ (c) (char->integer c))))
(λ (ws) (cons w ws))
(λ () '()))))
(define (get-maxes h)
(define max-ws (apply max (map length (hash-values h))))
(define max-keys (filter (λ (k) (= (length (hash-ref h k)) max-ws)) (hash-keys h)))
(map (λ (k) (hash-ref h k)) max-keys))
(get-maxes (hash-words (get-lines "http://www.puzzlers.org/pub/wordlists/unixdict.txt")))

View file

@ -0,0 +1,56 @@
$ include "seed7_05.s7i";
include "gethttp.s7i";
include "strifile.s7i";
const type: anagramHash is hash [string] array string;
const func string: sort (in string: stri) is func
result
var string: sortedStri is "";
local
var integer: i is 0;
var integer: j is 0;
var char: ch is ' ';
begin
sortedStri := stri;
for i range 1 to length(sortedStri) do
for j range succ(i) to length(sortedStri) do
if sortedStri[i] > sortedStri[j] then
ch := sortedStri[i];
sortedStri @:= [i] sortedStri[j];
sortedStri @:= [j] ch;
end if;
end for;
end for;
end func;
const proc: main is func
local
var file: dictFile is STD_NULL;
var string: word is "";
var string: sortedLetters is "";
var anagramHash: anagrams is anagramHash.value;
var integer: length is 0;
var integer: maxLength is 0;
begin
dictFile := openStrifile(getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt"));
while hasNext(dictFile) do
readln(dictFile, word);
sortedLetters := sort(word);
if sortedLetters in anagrams then
anagrams[sortedLetters] &:= word;
else
anagrams @:= [sortedLetters] [] (word);
end if;
length := length(anagrams[sortedLetters]);
if length > maxLength then
maxLength := length;
end if;
end while;
close(dictFile);
for sortedLetters range sort(keys(anagrams)) do
if length(anagrams[sortedLetters]) = maxLength then
writeln(join(anagrams[sortedLetters], ", "));
end if;
end for;
end func;

View file

@ -0,0 +1,57 @@
#INCLUDE <Include\Windows.inc>
FBSLSETTEXT(ME, "Pendulum")
FBSL.SETTIMER(ME, 1000, 10)
RESIZE(ME, 0, 0, 300, 200)
CENTER(ME)
SHOW(ME)
BEGIN EVENTS
SELECT CASE CBMSG
CASE WM_TIMER
' Request redraw
InvalidateRect(ME, NULL, FALSE)
RETURN 0
CASE WM_PAINT
Swing()
CASE WM_CLOSE
FBSL.KILLTIMER(ME, 1000)
END SELECT
END EVENTS
SUB Swing()
TYPE RECT: %rcLeft, %rcTop, %rcRight, %rcBottom: END TYPE
STATIC rc AS RECT, !!acceleration, !!velocity, !!angle = M_PI_2, %pendulum = 100
GetClientRect(ME, @rc)
' Recalculate
DIM headX = rc.rcRight / 2, headY = rc.rcBottom / 4
DIM tailX = headX + SIN(angle) * pendulum
DIM tailY = headY + COS(angle) * pendulum
acceleration = -9.81 / pendulum * SIN(angle)
INCR(velocity, acceleration * 0.1)(angle, velocity * 0.1)
' Create backbuffer
CreateCompatibleDC(GetDC(ME))
SelectObject(CreateCompatibleDC, CreateCompatibleBitmap(GetDC, rc.rcRight, rc.rcBottom))
' Draw to backbuffer
FILLSTYLE(FILL_SOLID): FILLCOLOR(RGB(200, 200, 0))
LINE(CreateCompatibleDC, 0, 0, rc.rcRight, rc.rcBottom, GetSysColor(COLOR_BTNHILIGHT), TRUE, TRUE)
LINE(CreateCompatibleDC, 0, headY, rc.rcRight, headY, GetSysColor(COLOR_3DSHADOW))
DRAWWIDTH(3)
LINE(CreateCompatibleDC, headX, headY, tailX, tailY, RGB(200, 0, 0))
DRAWWIDTH(1)
CIRCLE(CreateCompatibleDC, headX, headY, 2, GetSysColor, 0, 360, 1, TRUE)
CIRCLE(CreateCompatibleDC, tailX, tailY, 10, GetSysColor, 0, 360, 1, FALSE)
' Blit to window
BitBlt(GetDC, 0, 0, rc.rcRight, rc.rcBottom, CreateCompatibleDC, 0, 0, SRCCOPY)
ReleaseDC(ME, GetDC)
' Delete backbuffer
DeleteObject(SelectObject(CreateCompatibleDC, SelectObject))
DeleteDC(CreateCompatibleDC)
END SUB

View file

@ -1,7 +1,6 @@
#lang racket
(require 2htdp/image
2htdp/universe)
(require 2htdp/image 2htdp/universe)
(define (pendulum)
(define (accel θ) (- (sin θ)))

View file

@ -0,0 +1,30 @@
#INCLUDE <Include\Windows.inc>
FBSLSETTEXT(ME, "Hello world! ")
RESIZE(ME, 0, 0, 220, 0)
CENTER(ME)
SHOW(ME)
SetTimer(ME, 1000, 100, NULL)
BEGIN EVENTS
STATIC bForward AS BOOLEAN = TRUE
IF CBMSG = WM_TIMER THEN
Marquee(bForward)
RETURN 0
ELSEIF CBMSG = WM_NCLBUTTONDOWN THEN
IF CBWPARAM = HTCAPTION THEN bForward = NOT bForward
ELSEIF CBMSG = WM_CLOSE THEN
KillTimer(ME, 1000)
END IF
END EVENTS
SUB Marquee(BYVAL forward AS BOOLEAN)
STATIC caption AS STRING = FBSLGETTEXT(ME)
STATIC length AS INTEGER = STRLEN(caption)
IF forward THEN
caption = RIGHT(caption, 1) & LEFT(caption, length - 1)
ELSE
caption = MID(caption, 2) & LEFT(caption, 1)
END IF
FBSLSETTEXT(ME, caption)
END SUB

View file

@ -1,4 +1,4 @@
double fib(const double n)
double fib(double n)
{
if(n < 0)
{
@ -6,10 +6,9 @@ double fib(const double n)
}
else
{
class actual_fib
struct actual_fib
{
public:
static double calc(const double n)
static double calc(double n)
{
if(n < 2)
{

View file

@ -0,0 +1,26 @@
double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
double operator()(double n)
{
if(n < 2)
{
return n;
}
else
{
return (*this)(n-1) + (*this)(n-2);
}
}
};
return actual_fib()(n);
}
}

View file

@ -0,0 +1,15 @@
-module( anonymous_recursion ).
-export( [fib/1, fib_internal/1] ).
fib( N ) when N >= 0 ->
fib( N, 1, 0 ).
fib_internal( N ) when N >= 0 ->
Fun = fun (_F, 0, _Next, Acc ) -> Acc;
(F, N, Next, Acc) -> F( F, N - 1, Acc+Next, Next )
end,
Fun( Fun, N, 1, 0 ).
fib( 0, _Next, Acc ) -> Acc;
fib( N, Next, Acc ) -> fib( N - 1, Acc+Next, Next ).

View file

@ -0,0 +1,22 @@
#APPTYPE CONSOLE
FUNCTION Fibonacci(n)
IF n < 0 THEN
RETURN "Nuts!"
ELSE
RETURN Fib(n)
END IF
FUNCTION Fib(m)
IF m < 2 THEN
Fib = m
ELSE
Fib = Fib(m - 1) + Fib(m - 2)
END IF
END FUNCTION
END FUNCTION
PRINT Fibonacci(-1.5)
PRINT Fibonacci(1.5)
PRINT Fibonacci(13.666)
PAUSE

View file

@ -6,18 +6,18 @@ interface SelfApplicable<OUTPUT> {
}
class Utils {
public static <INPUT, OUTPUT> SelfApplicable<Function<Function<Function<INPUT, OUTPUT>, Function<INPUT, OUTPUT>>, Function<INPUT, OUTPUT>>> y(Class<INPUT> input, Class<OUTPUT> output) {
public static <INPUT, OUTPUT> SelfApplicable<Function<Function<Function<INPUT, OUTPUT>, Function<INPUT, OUTPUT>>, Function<INPUT, OUTPUT>>> y() {
return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x);
}
public static <INPUT, OUTPUT> Function<Function<Function<INPUT, OUTPUT>, Function<INPUT, OUTPUT>>, Function<INPUT, OUTPUT>> fix(Class<INPUT> input, Class<OUTPUT> output) {
return y(input, output).apply(y(input, output));
public static <INPUT, OUTPUT> Function<Function<Function<INPUT, OUTPUT>, Function<INPUT, OUTPUT>>, Function<INPUT, OUTPUT>> fix() {
return Utils.<INPUT, OUTPUT>y().apply(Utils.<INPUT, OUTPUT>y());
}
public static long fib(int m) {
if (m < 0)
throw new IllegalArgumentException("n can not be a negative number");
return fix(Integer.class, Long.class).apply(
return Utils.<Integer, Long>fix().apply(
f -> n -> (n < 2) ? n : (f.apply(n - 1) + f.apply(n - 2))
).apply(m);
}

View file

@ -0,0 +1,18 @@
<?php
class fib_helper {
function __invoke($n) {
if ($n < 2)
return 1;
else
return $this($n-1) + $this($n-2);
}
}
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = new fib_helper();
return $f($n);
}
echo fib(8), "\n";
?>

View file

@ -1,4 +1,5 @@
>>> Y = lambda f: (lambda x: x(x))(lambda y: lambda *args: f(y(y), *args))
>>>from functools import partial
>>> Y = lambda f: (lambda x: x(x))(lambda y: partial(f, lambda *args: y(y)(*args)))
>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

View file

@ -0,0 +1,14 @@
#lang racket
;; We use Z combinator (applicative order fixed-point operator)
(define Z
(λ (f)
((λ (x) (f (λ (g) ((x x) g))))
(λ (x) (f (λ (g) ((x x) g)))))))
(define fibonacci
(Z (λ (fibo)
(λ (n)
(if (<= n 2)
1
(+ (fibo (- n 1))
(fibo (- n 2))))))))

View file

@ -3,13 +3,13 @@
#include <algorithm>
#include <iterator>
int main( ) {
std::vector< int > intVec( 10 ) ;
std::iota( intVec.begin( ) , intVec.end( ) , 1 ) ;//fill the vector
std::transform( intVec.begin( ) , intVec.end( ) , intVec.begin( ) ,
[ ] ( int i ) { return i * i ; } ) ; //transform it with closures
std::copy( intVec.begin( ) , intVec.end( ) ,
std::ostream_iterator<int> ( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
int main() {
std::vector<int> intVec(10);
std::iota(std::begin(intVec), std::end(intVec), 1 ); // Fill the vector
std::transform(std::begin(intVec) , std::end(intVec), std::begin(intVec),
[](int i) { return i * i ; } ); // Transform it with closures
std::copy(std::begin(intVec), end(intVec) ,
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}

View file

@ -0,0 +1,23 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. Map.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Table-Size CONSTANT 30.
LOCAL-STORAGE SECTION.
01 I USAGE UNSIGNED-INT.
LINKAGE SECTION.
01 Table-Param.
03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES.
01 Func-Id PIC X(30).
PROCEDURE DIVISION USING Table-Param Func-Id.
PERFORM VARYING I FROM 1 BY 1 UNTIL Table-Size < I
CALL Func-Id USING BY REFERENCE Table-Values (I)
END-PERFORM
GOBACK
.

View file

@ -0,0 +1,17 @@
#APPTYPE CONSOLE
FOREACH DIM e IN MyMap(Add42, {1, 2, 3})
PRINT e, " ";
NEXT
PAUSE
FUNCTION MyMap(f, a)
DIM ret[]
FOREACH DIM e IN a
ret[] = f(e)
NEXT
RETURN ret
END FUNCTION
FUNCTION Add42(n): RETURN n + 42: END FUNCTION

View file

@ -0,0 +1,17 @@
#APPTYPE CONSOLE
DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _
{"French", {"un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix"}}}
MAP(SpeakALanguage, languages)
PAUSE
SUB NameANumber(lang, nb, number)
PRINT "The number ", nb, " is called ", STRENC(number), " in ", lang
END SUB
SUB SpeakALanguage(lang)
MAP(NameANumber, lang[0], 1 TO 10, lang[1])
PRINT LPAD("", 40, "-")
END SUB

View file

@ -0,0 +1,22 @@
numbers = [1, 3, 5, 7]
square1 = [square(n) for n in numbers] # list comprehension
squares2a = map(square, numbers) # functional form
squares2b = map(x -> x*x, numbers) # functional form with `lambda`
#There is also extended block form for the map function
squares2c = map(numbers) do x
sum = 0
for i = 1:x
sum += x^2 #trivial, but you get the point
end
return sum
end
squares3 = [n * n for n in numbers] # no need for a function,
squares4 = numbers .* numbers #element-wise operation
squares4a = numbers .^ 2 #includes .+, .-, ./, comparison, and bitwise operations as well

View file

@ -1,7 +1,7 @@
#lang racket
;; using the `for/vector` comprehension form
;; using the `for/vector' comprehension form
(for/vector ([i #(1 2 3 4 5)]) (sqr i))
;; the usual functional `map`
;; the usual functional `map'
(vector-map sqr #(1 2 3 4 5))

View file

@ -1,5 +1,5 @@
julia> @elapsed big = string(BigInt(5)^4^3^2)
0.06799983978271484 seconds
0.017507363
julia> length(big)
183231

View file

@ -0,0 +1,30 @@
-module( arena_storage_pool ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn_opt( fun() -> loop([]) end, [{min_heap_size, 10000}] ),
set( Pid, 1, ett ),
set( Pid, "kalle", "hobbe" ),
V1 = get( Pid, 1 ),
V2 = get( Pid, "kalle" ),
true = (V1 =:= ett) and (V2 =:= "hobbe"),
erlang:exit( Pid, normal ).
get( Pid, Key ) ->
Pid ! {get, Key, erlang:self()},
receive
{value, Value, Pid} -> Value
end.
loop( List ) ->
receive
{set, Key, Value} -> loop( [{Key, Value} | proplists:delete(Key, List)] );
{get, Key, Pid} ->
Pid ! {value, proplists:get_value(Key, List), erlang:self()},
loop( List )
end.
set( Pid, Key, Value ) -> Pid ! {set, Key, Value}.

View file

@ -0,0 +1,9 @@
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic) ; a block of memory without internal pointers
(malloc 1000 'nonatomic) ; a block of pointers
(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn) ; can be declared immutable when mutation is done
(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v) ; allocates a single cell that the GC will not move

View file

@ -0,0 +1,14 @@
% Implemented by Arjun Sunel
-module(arith).
-export([start/0]).
start() ->
case io:fread("","~d~d") of
{ok, [A,B]} ->
io:format("Sum = ~w~n",[A+B]),
io:format("Difference = ~w~n",[A-B]),
io:format("Product = ~w~n",[A*B]),
io:format("Quotient = ~w~n",[A div B]), % truncates towards zero
io:format("Remainder= ~w~n",[A rem B]), % same sign as the first operand
halt()
end.

View file

@ -1,5 +1,5 @@
my Int $a = floor $*IN.get;
my Int $b = floor $*IN.get;
my Int $a = get.floor;
my Int $b = get.floor;
say 'sum: ', $a + $b;
say 'difference: ', $a - $b;

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