commit deletes

This commit is contained in:
Ingy döt Net 2013-10-27 23:48:49 +00:00
parent 776bba907c
commit 372c577f83
233 changed files with 0 additions and 6724 deletions

View file

@ -1,31 +0,0 @@
import std.stdio, std.algorithm, std.range;
enum DoorState : bool { closed, open }
alias Doors = DoorState[];
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;
return doors;
}
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;
}
void main() {
auto doors = new Doors(100);
foreach (const open; [doors.dup.flipUnoptimized,
doors.dup.flipOptimized])
iota(1, open.length + 1).filter!(i => open[i - 1]).writeln;
}

View file

@ -1,5 +0,0 @@
doors() ->
F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end,
Out = fun(X, true) -> io:format("Door ~p: open~n",[X]);
(X, false)-> io:format("Door ~p: close~n",[X]) end,
[Out(X,F(X)) || X <- lists:seq(1,100)].

View file

@ -1,23 +0,0 @@
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

@ -1,15 +0,0 @@
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

@ -1,50 +0,0 @@
#lang racket
(define (random-4)
(sort (for/list ((i (in-range 4)))
(add1 (random 9)))
<))
(define (check-valid-chars lst-nums str)
(define regx (string-join (list
"^["
(string-join (map number->string lst-nums) "")
"\\(\\)\\+\\-\\/\\*\\ ]*$")
""))
(regexp-match? regx str))
(define (check-all-numbers lst-nums str)
(equal?
(sort
(map (λ (x) (string->number x))
(regexp-match* "([0-9])" str)) <)
lst-nums))
(define (start-game)
(display "** 24 **\n")
(display "Input \"q\" to quit or your answer in Racket ")
(display "notation, like (- 1 (* 3 2))\n\n")
(new-question))
(define (new-question)
(define numbers (random-4))
(apply printf "Your numbers: ~a - ~a - ~a - ~a\n" numbers)
(define (do-loop)
(define user-expr (read-line))
(cond
[(equal? user-expr "q")
(exit)]
[(not (check-valid-chars numbers user-expr))
(display "Your expression seems invalid, please retry:\n")
(do-loop)]
[(not (check-all-numbers numbers user-expr))
(display "You didn't use all the provided numbers, please retry:\n")
(do-loop)]
[(if (equal? 24 (eval (with-input-from-string user-expr read) (make-base-namespace)))
(display "OK!!")
(begin
(display "Incorrect\n")
(do-loop)))]))
(do-loop))
(start-game)

View file

@ -1,21 +0,0 @@
local $bottleNo=99
local $lyrics=" "
While $bottleNo<>0
If $bottleNo=1 Then
$lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF
$lyrics&=$bottleNo & " bottles of beer" & @CRLF
$lyrics&="Take one down, pass it around" & @CRLF
Else
$lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF
$lyrics&=$bottleNo & " bottles of beer" & @CRLF
$lyrics&="Take one down, pass it around" & @CRLF
EndIf
If $bottleNo=1 Then
$lyrics&=$bottleNo-1 & " bottle of beer" & @CRLF
Else
$lyrics&=$bottleNo-1 & " bottles of beer" & @CRLF
EndIf
$bottleNo-=1
WEnd
MsgBox(1,"99",$lyrics)

View file

@ -1,29 +0,0 @@
DELIMITER $$
DROP PROCEDURE IF EXISTS bottles_$$
CREATE pROCEDURE `bottles_`(inout bottle_count int, inout song text)
BEGIN
declare bottles_text varchar(30);
IF bottle_count > 0 THEN
if bottle_count != 1 then
set bottles_text := ' bottles of beer ';
else set bottles_text = ' bottle of beer ';
end if;
SELECT concat(song, bottle_count, bottles_text, ' \n') INTO song;
SELECT concat(song, bottle_count, bottles_text, 'on the wall\n') INTO song;
SELECT concat(song, 'Take one down, pass it around\n') into song;
SELECT concat(song, bottle_count -1 , bottles_text, 'on the wall\n\n') INTO song;
set bottle_count := bottle_count -1;
CALL bottles_( bottle_count, song);
END IF;
END$$
set @bottles=99;
set max_sp_recursion_depth=@bottles;
set @song='';
call bottles_( @bottles, @song);
select @song;

View file

@ -1,14 +0,0 @@
<html>
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
a = window.prompt 'enter A number', ''
b = window.prompt 'enter B number', ''
document.getElementById('input').innerHTML = a + ' ' + b
sum = parseInt(a) + parseInt(b)
document.getElementById('output').innerHTML = sum
</script>
<body>
<div id='input'></div>
<div id='output'></div>
</body>
</html>

View file

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

View file

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

View file

@ -1,8 +0,0 @@
import java.math.BigInteger;
public static BigInteger ack(BigInteger m, BigInteger n) {
return m.equals(BigInteger.ZERO)
? n.add(BigInteger.ONE)
: ack(m.subtract(BigInteger.ONE),
n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE)));
}

View file

@ -1,12 +0,0 @@
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
#One-liner
ack2(m,n) = m == 0 ? n + 1 : n == 0 ? ack2(m-1,1) : ack2(m-1,ack2(m,n-1))

View file

@ -1,28 +0,0 @@
import std.stdio, std.file, std.string, std.algorithm,
std.typecons, std.range;
auto findDeranged(in string[] words) /*pure nothrow*/ {
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(readText("unixdict.txt")))
wClasses[$ - word.length] ~= word;
auto r = wClasses[].map!q{ a.data }().filter!q{ a.length }();
writeln("Longest deranged anagrams:");
foreach (words; r) {
string[][const ubyte[]] anags; // Assume input is ASCII.
foreach (w; words)
anags[(cast(ubyte[])w).sort().release().idup] ~= w.idup;
auto pairs = anags.byValue.filter!q{ a.length > 1 }()
.map!findDeranged().filter!q{ a.length }();
if (!pairs.empty)
return writefln(" %s, %s", pairs.front[0].tupleof);
}
}

View file

@ -1,26 +0,0 @@
# 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

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

View file

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

View file

@ -1,11 +0,0 @@
sub agm ($a, $g) {
sub iter ($old) {
my $new := [ 0.5 * [+](@$old), sqrt [*](@$old) ];
last if $new ~~ $old;
$new;
}
([$a,$g], &iter ... 0)[*-1][0];
}
say agm 1, 1/sqrt 2;

View file

@ -1,14 +0,0 @@
#include <vector>
#include <iostream>
int main()
{
std::vector<int> a(3), b(4);
a[0] = 11; a[1] = 12; a[2] = 13;
b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
a.insert(a.end(), b.begin(), b.end());
for (int i = 0; i < a.size(); ++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
}

View file

@ -1,41 +0,0 @@
// All D arrays are capable of bounds checks.
import std.stdio, core.stdc.stdlib;
import std.container: Array;
void main() {
// GC-managed heap allocated dynamic array:
auto array1 = new int[1];
array1[0] = 1;
array1 ~= 3; // append a second item
// array1[10] = 4; // run-time error
writeln("A) Element 0: ", array1[0]);
writeln("A) Element 1: ", array1[1]);
// Stack-allocated fixed-size array:
int[5] array2;
array2[0] = 1;
array2[1] = 3;
// array2[2] = 4; // compile-time error
writeln("B) Element 0: ", array2[0]);
writeln("B) Element 1: ", array2[1]);
// Stack-allocated dynamic fixed-sized array,
// length known only at run-time:
int n = 2;
int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
array3[0] = 1;
array3[1] = 3;
// array3[10] = 4; // run-time error
writeln("C) Element 0: ", array3[0]);
writeln("C) Element 1: ", array3[1]);
// Phobos-defined heap allocated not GC-managed array:
Array!int array4;
array4.length = 2;
array4[0] = 1;
array4[1] = 3;
// array4[10] = 4; // run-time exception
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 1: ", array4[1]);
}

View file

@ -1,10 +0,0 @@
#include <assert.h>
void
test()
{
int a;
// ... input or change a here
assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
}

View file

@ -1,69 +0,0 @@
module AtomicUpdates (main) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_)
import Control.Monad (forever, forM_)
import Data.IntMap (IntMap, (!), toAscList, fromList, adjust)
import System.Random (randomRIO)
import Text.Printf (printf)
-------------------------------------------------------------------------------
type Index = Int
type Value = Integer
data Buckets = Buckets Index (MVar (IntMap Value))
makeBuckets :: Int -> IO Buckets
size :: Buckets -> Index
currentValue :: Buckets -> Index -> IO Value
currentValues :: Buckets -> IO (IntMap Value)
transfer :: Buckets -> Index -> Index -> Value -> IO ()
-------------------------------------------------------------------------------
makeBuckets n = do v <- newMVar (fromList [(i, 100) | i <- [1..n]])
return (Buckets n v)
size (Buckets n _) = n
currentValue (Buckets _ v) i = fmap (! i) (readMVar v)
currentValues (Buckets _ v) = readMVar v
transfer b@(Buckets n v) i j amt | amt < 0 = transfer b j i (-amt)
| otherwise = do
modifyMVar_ v $ \map -> let amt' = min amt (map ! i)
in return $ adjust (subtract amt') i
$ adjust (+ amt') j
$ map
-------------------------------------------------------------------------------
roughen, smooth, display :: Buckets -> IO ()
pick buckets = randomRIO (1, size buckets)
roughen buckets = forever loop where
loop = do i <- pick buckets
j <- pick buckets
iv <- currentValue buckets i
transfer buckets i j (iv `div` 3)
smooth buckets = forever loop where
loop = do i <- pick buckets
j <- pick buckets
iv <- currentValue buckets i
jv <- currentValue buckets j
transfer buckets i j ((iv - jv) `div` 4)
display buckets = forever loop where
loop = do threadDelay 1000000
bmap <- currentValues buckets
putStrLn (report $ map snd $ toAscList bmap)
report list = "\nTotal: " ++ show (sum list) ++ "\n" ++ bars
where bars = concatMap row $ map (*40) $ reverse [1..5]
row lim = printf "%3d " lim ++ [if x >= lim then '*' else ' ' | x <- list] ++ "\n"
main = do buckets <- makeBuckets 100
forkIO (roughen buckets)
forkIO (smooth buckets)
display buckets

View file

@ -1,119 +0,0 @@
import java.util.Arrays;
import java.util.Random;
public class AtomicUpdates
{
public static class Buckets
{
private final int[] data;
public Buckets(int[] data)
{
this.data = data.clone();
}
public int getBucket(int index)
{
synchronized (data)
{ return data[index]; }
}
public int transfer(int srcBucketIndex, int destBucketIndex, int amount)
{
if (amount == 0)
return 0;
// Negative transfers will happen in the opposite direction
if (amount < 0)
{
int tempIndex = srcBucketIndex;
srcBucketIndex = destBucketIndex;
destBucketIndex = tempIndex;
amount = -amount;
}
synchronized (data)
{
if (amount > data[srcBucketIndex])
amount = data[srcBucketIndex];
if (amount <= 0)
return 0;
data[srcBucketIndex] -= amount;
data[destBucketIndex] += amount;
return amount;
}
}
public int[] getBuckets()
{
synchronized (data)
{ return data.clone(); }
}
}
public static int getTotal(int[] values)
{
int totalValue = 0;
for (int i = values.length - 1; i >= 0; i--)
totalValue += values[i];
return totalValue;
}
public static void main(String[] args)
{
final int NUM_BUCKETS = 10;
Random rnd = new Random();
final int[] values = new int[NUM_BUCKETS];
for (int i = 0; i < values.length; i++)
values[i] = rnd.nextInt(10);
System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values));
final Buckets buckets = new Buckets(values);
new Thread(new Runnable() {
public void run()
{
Random r = new Random();
while (true)
{
int srcBucketIndex = r.nextInt(NUM_BUCKETS);
int destBucketIndex = r.nextInt(NUM_BUCKETS);
int amount = (buckets.getBucket(srcBucketIndex) - buckets.getBucket(destBucketIndex)) >> 1;
if (amount != 0)
buckets.transfer(srcBucketIndex, destBucketIndex, amount);
}
}
}
).start();
new Thread(new Runnable() {
public void run()
{
Random r = new Random();
while (true)
{
int srcBucketIndex = r.nextInt(NUM_BUCKETS);
int destBucketIndex = r.nextInt(NUM_BUCKETS);
int srcBucketAmount = buckets.getBucket(srcBucketIndex);
int destBucketAmount = buckets.getBucket(destBucketIndex);
int amount = r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount;
if (amount != 0)
buckets.transfer(srcBucketIndex, destBucketIndex, amount);
}
}
}
).start();
while (true)
{
long nextPrintTime = System.currentTimeMillis() + 3000;
long curTime;
while ((curTime = System.currentTimeMillis()) < nextPrintTime)
{
try
{ Thread.sleep(nextPrintTime - curTime); }
catch (InterruptedException e)
{ }
}
int[] bucketValues = buckets.getBuckets();
System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues));
}
}
}

View file

@ -1,6 +0,0 @@
(defn mean [sq]
(let [length (count sq)]
(if (zero? length)
0
(/ (reduce + sq) length)))
)

View file

@ -1,22 +0,0 @@
package main
import (
"fmt"
"math"
"math/cmplx"
)
func deg2rad(d float64) float64 { return d * math.Pi / 180 }
func rad2deg(r float64) float64 { return r * 180 / math.Pi }
func mean_angle(deg []float64) float64 {
sum := 0i
for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) }
return rad2deg(cmplx.Phase(sum))
}
func main() {
for _, angles := range [][]float64 {{350, 10}, {90, 180, 270, 360}, {10, 20, 30}} {
fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles))
}
}

View file

@ -1,4 +0,0 @@
sub median {
my @a = sort @_;
return (@a[@a.end / 2] + @a[@a / 2]) / 2;
}

View file

@ -1,36 +0,0 @@
import scala.collection.mutable.ListBuffer
import scala.util.Random
object BalancedBrackets extends App {
val random = new Random()
def generateRandom: List[String] = {
import scala.util.Random._
val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_)
(1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList
}
def generate(n: Int): List[String] = {
val base = "["*n+"]"*n
var lb = ListBuffer[String]()
base.permutations.foreach(s=>lb+=s)
lb.toList.sorted
}
def checkBalance(brackets: String):Boolean = {
def balI(brackets: String, depth: Int):Boolean = {
if (brackets == "") depth == 0
else brackets(0) match {
case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1))
case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1))
case _ => false
}
}
balI(brackets, 0)
}
println("arbitrary random order:")
generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
println("\n"+"check all permutations of given length:")
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
}

View file

@ -1,26 +0,0 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 binary_number pic X(21).
01 str pic X(21).
01 binary_digit pic X.
01 digit pic 9.
01 n pic 9(7).
01 nstr pic X(7).
PROCEDURE DIVISION.
accept nstr
move nstr to n
perform until n equal 0
divide n by 2 giving n remainder digit
move digit to binary_digit
string binary_digit DELIMITED BY SIZE
binary_number DELIMITED BY SPACE
into str
move str to binary_number
end-perform.
display binary_number
stop run.

View file

@ -1,4 +0,0 @@
16.times do |i|
puts '%b' % i
puts i.to_s 2
end

View file

@ -1,34 +0,0 @@
PRAGMAT READ "Bresenhams_line_algorithm.a68" PRAGMAT;
cubic bezier OF class image :=
( REF IMAGE picture,
POINT p1, p2, p3, p4,
PIXEL color,
UNION(INT, VOID) in n
)VOID:
BEGIN
INT n = (in n|(INT n):n|20); # default 20 #
[0:n]POINT points;
FOR i FROM LWB points TO UPB points DO
REAL t = i / n,
a = (1 - t)**3,
b = 3 * t * (1 - t)**2,
c = 3 * t**2 * (1 - t),
d = t**3;
x OF points [i] := ENTIER (0.5 + a * x OF p1 + b * x OF p2 + c * x OF p3 + d * x OF p4);
y OF points [i] := ENTIER (0.5 + a * y OF p1 + b * y OF p2 + c * y OF p3 + d * y OF p4)
OD;
FOR i FROM LWB points TO UPB points - 1 DO
(line OF class image)(picture, points (i), points (i + 1), color)
OD
END # cubic bezier #;
#
The following test
#
IF test THEN
REF IMAGE x = INIT LOC[16,16]PIXEL;
(fill OF class image)(x, (white OF class image));
(cubic bezier OF class image)(x, (16, 1), (1, 4), (3, 16), (15, 11), (black OF class image), EMPTY);
(print OF class image) (x)
FI

View file

@ -1,53 +0,0 @@
PRAGMAT READ "Basic_bitmap_storage.a68" PRAGMAT;
line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID:
BEGIN
REAL dx = ABS (x OF stop - x OF start),
dy = ABS (y OF stop - y OF start);
REAL err;
POINT here := start,
step := (1, 1);
IF x OF start > x OF stop THEN
x OF step := -1
FI;
IF y OF start > y OF stop THEN
y OF step := -1
FI;
IF dx > dy THEN
err := dx / 2;
WHILE x OF here /= x OF stop DO
picture[x OF here, y OF here] := color;
err -:= dy;
IF err < 0 THEN
y OF here +:= y OF step;
err +:= dx
FI;
x OF here +:= x OF step
OD
ELSE
err := dy / 2;
WHILE y OF here /= y OF stop DO
picture[x OF here, y OF here] := color;
err -:= dx;
IF err < 0 THEN
x OF here +:= x OF step;
err +:= dy
FI;
y OF here +:= y OF step
OD
FI;
picture[x OF here, y OF here] := color # ensure dots to be drawn #
END # line #;
###
The test program:
###
IF test THEN
REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL;
(fill OF class image)(x, white OF class image);
(line OF class image)(x, ( 1, 8), ( 8,16), black OF class image);
(line OF class image)(x, ( 8,16), (16, 8), black OF class image);
(line OF class image)(x, (16, 8), ( 8, 1), black OF class image);
(line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image);
(print OF class image)(x)
FI

View file

@ -1,58 +0,0 @@
def line(self, x0, y0, x1, y1):
"Bresenham's line algorithm"
dx = abs(x1 - x0)
dy = abs(y1 - y0)
x, y = x0, y0
sx = -1 if x0 > x1 else 1
sy = -1 if y0 > y1 else 1
if dx > dy:
err = dx / 2.0
while x != x1:
self.set(x, y)
err -= dy
if err < 0:
y += sy
err += dx
x += sx
else:
err = dy / 2.0
while y != y1:
self.set(x, y)
err -= dx
if err < 0:
x += sx
err += dy
y += sy
self.set(x, y)
Bitmap.line = line
bitmap = Bitmap(17,17)
for points in ((1,8,8,16),(8,16,16,8),(16,8,8,1),(8,1,1,8)):
bitmap.line(*points)
bitmap.chardisplay()
'''
The origin, 0,0; is the lower left, with x increasing to the right,
and Y increasing upwards.
The chardisplay above produces the following output :
+-----------------+
| @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @ |
| @ @|
| @ @ |
| @ @ |
| @ @@ |
| @ @ |
| @ @ |
| @ @ |
| @ |
| |
+-----------------+
'''

View file

@ -1,46 +0,0 @@
PRAGMAT READ "Basic_bitmap_storage.a68" PRAGMAT;
circle OF class image :=
( REF IMAGE picture,
POINT center,
INT radius,
PIXEL color
)VOID:
BEGIN
INT f := 1 - radius,
POINT ddf := (0, -2 * radius),
df := (0, radius);
picture [x OF center, y OF center + radius] :=
picture [x OF center, y OF center - radius] :=
picture [x OF center + radius, y OF center] :=
picture [x OF center - radius, y OF center] := color;
WHILE x OF df < y OF df DO
IF f >= 0 THEN
y OF df -:= 1;
y OF ddf +:= 2;
f +:= y OF ddf
FI;
x OF df +:= 1;
x OF ddf +:= 2;
f +:= x OF ddf + 1;
picture [x OF center + x OF df, y OF center + y OF df] :=
picture [x OF center - x OF df, y OF center + y OF df] :=
picture [x OF center + x OF df, y OF center - y OF df] :=
picture [x OF center - x OF df, y OF center - y OF df] :=
picture [x OF center + y OF df, y OF center + x OF df] :=
picture [x OF center - y OF df, y OF center + x OF df] :=
picture [x OF center + y OF df, y OF center - x OF df] :=
picture [x OF center - y OF df, y OF center - x OF df] := color
OD
END # circle #;
#
The following illustrates use:
#
IF test THEN
REF IMAGE x = INIT LOC [1:16, 1:16] PIXEL;
(fill OF class image)(x, (white OF class image));
(circle OF class image)(x, (8, 8), 5, (black OF class image));
(print OF class image)(x)
FI

View file

@ -1,54 +0,0 @@
MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue);
MODE POINT = STRUCT(INT x,y);
MODE IMAGE = [0,0]PIXEL; # instance attributes #
MODE CLASSIMAGE = STRUCT ( # class attributes #
PIXEL black, red, green, blue, white,
PROC (REF IMAGE)REF IMAGE init,
PROC (REF IMAGE, PIXEL)VOID fill,
PROC (REF IMAGE)VOID print,
# virtual: #
REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line,
REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle,
REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier
);
CLASSIMAGE class image = (
# black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00),
# red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00),
# green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00),
# blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff),
# white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff),
# PROC init = # (REF IMAGE self)REF IMAGE:
BEGIN
(fill OF class image)(self, black OF class image);
self
END,
# PROC fill = # (REF IMAGE self, PIXEL color)VOID:
FOR x FROM 1 LWB self TO 1 UPB self DO
FOR y FROM 2 LWB self TO 2 UPB self DO
self[x,y] := color
OD
OD,
# PROC print = # (REF IMAGE self)VOID:
printf(($n(UPB self)(3(16r2d))l$, self)),
# virtual: #
# REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID,
# REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID,
# REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID
);
OP CLASSOF = (IMAGE image)CLASSIMAGE: class image;
OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image);
BOOL test = TRUE;
IF test THEN
###
The test program
###
REF IMAGE x := INIT LOC[1:16, 1:16]PIXEL;
(fill OF class image) (x, white OF class image);
(print OF class image) (x)
FI

View file

@ -1,4 +0,0 @@
#Boolean and conditional expressions only accept 'true' or 'false'
#Convert a number or numeric array to boolean
bool(x)

View file

@ -1,32 +0,0 @@
function cowsbulls()
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
You get one bull for every right number in the right position.\n
You get one cow for every right number, but in the wrong position.\n
Enter 'n' to pick a new number and 'q' to quit.\n>")
function new_number()
s = [1:9]
n = ""
for i = 9:-1:6
n *= string(delete!(s,rand(1:i)))
end
return n
end
answer = new_number()
while true
input = chomp(readline(STDIN))
input == "q" && break
if input == "n"
answer = new_number()
print("\nI've picked a new number, go ahead and guess\n>")
continue
end
!ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue)
if input == answer
print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>")
else
bulls = sum(answer.data .== input.data)
cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])
print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>")
end
end
end

View file

@ -1,44 +0,0 @@
def generate_word(len)
([1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle)[0,len].join("")
end
def get_guess(len)
while true
print "Enter a guess: "
guess = gets.strip
err = case
when guess.match(/\D/) : "digits only"
when guess.length != len : "exactly #{len} digits"
when guess.split("").uniq.length != len: "digits must be unique "
else nil
end
break if err.nil?
puts "the word must be #{len} unique digits between 1 and 9 (#{err}). Try again."
end
guess
end
def score(word, guess)
bulls = cows = 0
guess.bytes.each_with_index do |byte, idx|
if word[idx] == byte
bulls += 1
elsif word.include? byte
cows += 1
end
end
[bulls, cows]
end
srand
word_length = 4
puts "I have chosen a number with #{word_length} unique digits from 1 to 9."
word = generate_word(word_length)
count = 0
while true
guess = get_guess(word_length)
count += 1
break if word == guess
puts "that guess has %d bulls and %d cows" % score(word, guess)
end
puts "you guessed correctly in #{count} tries."

View file

@ -1,203 +0,0 @@
import java.util.TimeZone
import java.util.Locale
import java.util.Calendar
import java.util.GregorianCalendar
object Helper {
def monthsMax(locale: Locale = Locale.getDefault): Int = {
val cal = Calendar.getInstance(locale)
cal.getMaximum(Calendar.MONTH)
}
def numberOfMonths(locale: Locale = Locale.getDefault): Int = monthsMax(locale)+1
def namesOfMonths(year: Int, locale: Locale = Locale.getDefault): List[String] = {
val cal = Calendar.getInstance(locale)
val f1: Int => String = i => {
cal.set(year,i,1)
cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locale)
}
(0 to monthsMax(locale)) map f1 toList
}
def jgt(cal: GregorianCalendar): Int = {cal.setTime(cal.getGregorianChange); cal.get(Calendar.YEAR)}
def isJGT(year: Int, cal: GregorianCalendar) = year==jgt(cal)
def offsets(year: Int, locale: Locale = Locale.getDefault): List[Int] = {
val cal = Calendar.getInstance(locale)
val months = cal.getMaximum(Calendar.MONTH)
val f1: Int => Int = i => {
cal.set(year,i,1)
cal.get(Calendar.DAY_OF_WEEK)
}
((0 to months) map f1 toList) map {i=>if((i-2)<0) i+5 else i-2}
}
def headerNameOfDays(locale: Locale = Locale.getDefault) = {
val cal = Calendar.getInstance(locale)
val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale) // map days of week
val it = mdow.keySet.iterator
import scala.collection.mutable.ListBuffer
val lb = new ListBuffer[String]
while (it.hasNext) lb+=it.next
val lpdow = lb.toList.map{k=>(mdow.get(k),k.substring(0,2))} // list pair days of week
(lpdow map {p=>if((p._1-2)<0) (p._1+5, p._2) else (p._1-2, p._2)} sortWith(_._1<_._1) map (_._2)).foldRight("")(_+" "+_)
}
}
object CalendarPrint extends App {
import Helper._
val tzd = TimeZone.getDefault
val locd = Locale.getDefault
def printCalendar(year: Int, printerWidth: Int, loc: Locale, tz: TimeZone) = {
def getCal: List[Triple[Int, Int, String]] = {
val cal = new GregorianCalendar(tz, loc)
def getGregCal: List[Triple[Int, Int, String]] = {
val month = 0
val day = 1
cal.set(year,month,day)
val f1: Int => Triple[Int, Int, Int] = i => {
val cal = Calendar.getInstance(tz, loc)
cal.set(year,i,1)
val minday = cal.getActualMinimum(Calendar.DAY_OF_MONTH)
val maxday = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
(i, minday, maxday)
}
val limits = (0 to monthsMax(loc)) map f1
val f2: (Int, Int, Int) => String = (year, month, day) => {
val cal = Calendar.getInstance(tz, loc)
cal.set(year,month,day)
cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, loc)
}
val calend = for {
i <- 0 to monthsMax(loc)
j <- limits(i)._2 to limits(i)._3
val dow = f2(year, i, j)
} yield (i, j, dow)
if (isJGT(year, new GregorianCalendar(tz, loc))) calend.filter{_._1!=9}.toList else calend.toList
}
def getJGT: List[Triple[Int, Int, String]] = {
if (!isJGT(year, new GregorianCalendar(tz, loc))) return Nil
val cal = new GregorianCalendar(tz, loc)
cal.set(year,9,1)
var ldom = 0
def it = new Iterator[Tuple3[Int,Int, String]]{
def next={
val res = (cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.GERMAN))
ldom = res._2
cal.roll(Calendar.DAY_OF_MONTH, true)
res
}
def hasNext = (cal.get(Calendar.DAY_OF_MONTH)>ldom)
}
it.toList
}
(getGregCal++getJGT).sortWith((s,t)=>s._1*100+s._2<t._1*100+t._2)
}
def printCal(calList: List[Triple[Int, Int, String]]) = {
val pwmax = 300 // printer width maximum
val mw = 20 // month width
val gwf = 2 // gap width fixed
val gwm = 2 // gap width minimum
val fgw = true
val arr = Array.ofDim[String](6,7)
def clear = for (i <- 0 until 6) for (j <- 0 until 7) arr(i)(j) = " "
def limits(printerWidth: Int): Tuple5[Int, Int, Int, Int, Int] = {
val pw = if (printerWidth<20) 20 else if (printerWidth>300) 300 else printerWidth
def getFGW(msbs: Int,gsm: Int) = {val r=(pw-msbs*mw-gsm)/2; (r,gwf,r)} // fixed gap width
def getVGW(msbs: Int,gsm: Int) = pw-msbs*mw-gsm match { // variable gap width
case a if (a<2*gwm) => (a/2,gwm,a/2)
case b => {val x = (b+gsm)/(msbs+1); (x,x,x)}
}
// months side by side, gaps sum minimum
val (msbs, gsm) = {
val (x, y) = {val c = if (pw/mw>12) 12 else pw/mw; if (c*mw+(c-1)*gwm<=pw) (c, c*gwm) else (c-1, (c-1)*gwm)}
val x1 = x match {
case 5 => 4
case a if (a>6 && a<12) => 6
case other => other
}
(x1, (x1-1)*gwm)
}
// left margin, gap width, right margin
val (lm,gw,rm) = if (fgw) getFGW(msbs,gsm) else getVGW(msbs,gsm)
(pw,msbs,lm,gw,rm)
}
val (pw,msbs,lm,gw,rm) = limits(printerWidth)
val monthsList = (0 to monthsMax(loc)).map{m=>calList.filter{_._1==m}}.toList
val nom = namesOfMonths(year,loc)
val offsetList = offsets(year,loc)
val hnod = headerNameOfDays(loc)
val fsplit: List[(Int, Int, String)] => List[String] = list => {
val fap: Int => (Int, Int) = p => (p/7,p%7)
clear
for (i <- 0 until list.size) arr(fap(i+offsetList(list(i)._1))._1)(fap(i+offsetList(list(i)._1))._2)="%2d".format(list(i)._2)
//arr.toList.map(_.toList).map(_.foldLeft("")(_+" "+_))
arr.toList.map(_.toList).map(_.foldRight("")(_+" "+_))
}
val monthsRows = monthsList.map(fsplit)
val center: (String, Int) => String = (s,l) => {
if (s.size>=l) s.substring(0,l) else
(" "*((l-s.size)/2)+s+" "*((l-s.size)/2)+" ").substring(0,l)
}
println(center("[Snoopy Picture]",pw))
println
println(center(""+year,pw))
println
val ul = numberOfMonths(loc)
val rowblocks = (1 to ul/msbs).map{i=>
(0 to 5).map{j=>
val lb = new scala.collection.mutable.ListBuffer[String]
val k = (i-1)*msbs
(k to k+msbs-1).map{l=>
lb+=monthsRows(l)(j)
}
lb.toList
}.toList
}.toList
val mheaders = (1 to ul/msbs).map{i=>(0 to msbs-1).map{j=>center(nom(j+(i-1)*msbs),20)}.toList}.toList
val dowheaders = (1 to ul/msbs).map{i=>(0 to msbs-1).map{j=>center(hnod,20)}.toList}.toList
(1 to 12/msbs).foreach{i=>
println(" "*lm+mheaders(i-1).foldRight("")(_+" "*gw+_))
println(" "*lm+dowheaders(i-1).foldRight("")(_+" "*gw+_))
rowblocks(i-1).foreach{xs=>println(" "*lm+xs.foldRight("")(_+" "*(gw-1)+_))}
println
}
}
val calList = getCal
printCal(calList)
}
def printGregCal(year: Int = 1969, pw: Int = 80, JGT: Boolean = false, loc: Locale = Locale.getDefault, tz: TimeZone = TimeZone.getDefault) {
val _year = if (JGT==false) year else jgt(new GregorianCalendar(tz, loc))
printCalendar(_year, pw, loc, tz)
}
printGregCal()
printGregCal(JGT=true, loc=Locale.UK, pw=132, tz=TimeZone.getTimeZone("UK/London"))
}

View file

@ -1,137 +0,0 @@
/*REXX program to demonstrate various methods of calling a REXX function*/
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function that REQUIRES no arguments.
In the REXX language, there is no way to require the caller to not
pass arguments, but the programmer can check if any arguments were
(or weren't) passed.
*/
yr=yearFunc()
say 'year=' yr
exit
yearFunc: procedure
if arg()\==0 then call sayErr "SomeFunc function won't accept arguments."
return left(date('Sorted'),3)
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function with a fixed number of arguments.
I take this to mean that the function requires a fixed number of
arguments. As above, REXX doesn't enforce calling (or invoking)
a (any) function with a certain number of arguments, but the
programmer can check if the correct number of arguments have been
specified (or not).
*/
ggg=FourFunc(12,abc,6+q,zz%2,'da 5th disagreement')
say 'ggg squared=' ggg**2
exit
FourFunc: procedure; parse arg a1,a2,a3; a4=arg(4) /*another way get a4*/
if arg()\==4 then do
call sayErr "FourFunc function requires 4 arguments,"
call sayErr "but instead it found" arg() 'arguments.'
exit 13
end
return a1+a2+a3+a4
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function with optional arguments.
Note that not passing an argument isn't the same as passing a null
argument (a REXX variable whose value is length zero).
*/
x=12; w=x/2; y=x**2; z=x//7 /* z is x modulo seven.*/
say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass 5 args, 4th is null*/
exit
SumIt: procedure; sum=0
do j=1 for arg()
if arg(j,'E') then sum=sum+arg(j) /*the Jth arg may have been omitted*/
end
return sum
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function with a variable number of arguments.
This situation isn't any different then the previous example.
It's up to the programmer to code how to utilize the arguments.
*/
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function with named arguments.
REXX allows almost anything to be passed, so the following is one
way this can be accomplished.
*/
what=parserFunc('name=Luna',"gravity=.1654",'moon=yes')
say 'name=' common.name
gr=common.gr
say 'gravity=' gr
exit
parseFunc: procedure expose common.
do j=1 for arg()
parse var arg(j) name '=' val
upper name
call value 'COMMON.'name,val
end
return arg()
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function in statement context.
REXX allows functions to be called (invoked) two ways, the first
example (above) is calling a function in statement context.
*/
/*┌────────────────────────────────────────────────────────────────────┐
Calling a function in within an expression.
This is a variant of the first example.
*/
yr=yearFunc()+20
say 'two decades from now, the year will be:' yr
exit
/*┌────────────────────────────────────────────────────────────────────┐
Obtaining the return value of a function.
There are two ways to get the (return) value of a function.
*/
currYear=yearFunc()
say 'the current year is' currYear
call yearFunc
say 'the current year is' result
/*┌────────────────────────────────────────────────────────────────────┐
Distinguishing built-in functions and user-defined functions.
One objective of the REXX language is to allow the user to use any
function (or subroutine) name whether or not there is a built-in
function with the same name (there isn't a penality for this).
*/
qqq=date() /*number of real dates that Bob was on. */
say "Bob's been out" qqq 'times.'
www='DATE'('USA') /*returns date in format mm/dd/yyy */
exit /*any function in quotes is external. */
date: return 4
/*┌────────────────────────────────────────────────────────────────────┐
Distinguishing subroutines and functions.
There is no programatic difference between subroutines and
functions if the subroutine returns a value (which effectively
makes it a function). REXX allows you to call a function as if
it were a subroutine.
*/
/*┌────────────────────────────────────────────────────────────────────┐
In REXX, all arguments are passed by value, never by name, but it
is possible to accomplish this if the variable's name is passed
and the subroutine/function could use the built-in-function VALUE
to retrieve the variable's value.
*/
/*┌────────────────────────────────────────────────────────────────────┐
In the REXX language, partial application is possible, depending
how partial application is defined; I prefer the 1st definition (as
(as per the "discussion" for "Partial Function Application" task:
1. The "syntactic sugar" that allows one to write (some examples
are: map (f 7 9) [1..9]
or: map(f(7,_,9),{1,...,9})
*/

View file

@ -1,20 +0,0 @@
use Test;
plan *;
is tan(atan(1/2)+atan(1/3)), 1;
is tan(2*atan(1/3)+atan(1/7)), 1;
is tan(4*atan(1/5)-atan(1/239)), 1;
is tan(5*atan(1/7)+2*atan(3/79)), 1;
is tan(5*atan(29/278)+7*atan(3/79)), 1;
is tan(atan(1/2)+atan(1/5)+atan(1/8)), 1;
is tan(4*atan(1/5)-atan(1/70)+atan(1/99)), 1;
is tan(5*atan(1/7)+4*atan(1/53)+2*atan(1/4443)), 1;
is tan(6*atan(1/8)+2*atan(1/57)+atan(1/239)), 1;
is tan(8*atan(1/10)-atan(1/239)-4*atan(1/515)), 1;
is tan(12*atan(1/18)+8*atan(1/57)-5*atan(1/239)), 1;
is tan(16*atan(1/21)+3*atan(1/239)+4*atan(3/1042)), 1;
is tan(22*atan(1/28)+2*atan(1/443)-5*atan(1/1393)-10*atan(1/11018)), 1;
is tan(22*atan(1/38)+17*atan(7/601)+10*atan(7/8149)), 1;
is tan(44*atan(1/57)+7*atan(1/239)-12*atan(1/682)+24*atan(1/12943)), 1;
is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12943)), 1;
is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12944)), 1;

View file

@ -1,86 +0,0 @@
import std.stdio, std.range;
const struct CombRep {
immutable uint nt, nc;
private immutable ulong[] combVal;
this(in uint numType, in uint numChoice) pure nothrow
in {
assert(0 < numType && numType + numChoice <= 64,
"Valid only for nt + nc <= 64 (ulong bit size)");
} body {
nt = numType;
nc = numChoice;
if (nc == 0)
return;
ulong v = (1UL << (nt - 1)) - 1;
// Init to smallest number that has nt-1 bit set
// a set bit is metaphored as a _type_ seperator.
immutable limit = v << nc;
// Limit is the largest nt-1 bit set number that has nc
// zero-bit a zero-bit means a _choice_ between _type_
// seperators.
while (v <= limit) {
combVal ~= v;
if (v == 0)
break;
// Get next nt-1 bit number.
immutable t = (v | (v - 1)) + 1;
v = t | ((((t & -t) / (v & -v)) >> 1) - 1);
}
}
uint length() @property const pure nothrow {
return combVal.length;
}
uint[] opIndex(in uint idx) const pure nothrow {
return val2set(combVal[idx]);
}
int opApply(immutable int delegate(in ref uint[]) dg) {
foreach (immutable v; combVal) {
auto set = val2set(v);
if (dg(set))
break;
}
return 1;
}
private uint[] val2set(in ulong v) const pure nothrow {
// Convert bit pattern to selection set
immutable uint bitLimit = nt + nc - 1;
uint typeIdx = 0;
uint[] set;
foreach (immutable bitNum; 0 .. bitLimit)
if (v & (1 << (bitLimit - bitNum - 1)))
typeIdx++;
else
set ~= typeIdx;
return set;
}
}
// For finite Random Access Range.
auto combRep(R)(R types, in uint numChoice) /*pure nothrow*/
if (hasLength!R && isRandomAccessRange!R) {
ElementType!R[][] result;
foreach (const s; CombRep(types.length, numChoice)) {
ElementType!R[] r;
foreach (immutable i; s)
r ~= types[i];
result ~= r;
}
return result;
}
void main() {
foreach (const e; combRep(["iced", "jam", "plain"], 2))
writefln("%-(%5s %)", e);
writeln("Ways to select 3 from 10 types is ",
CombRep(10, 3).length);
}

View file

@ -1,54 +0,0 @@
MODE DATA = INT;
PRIO C = 7;
# Calculate the number of combinations anticipated #
OP C = (INT n, k)INT:
CASE k + 1 IN
# case 0: # 1,
# case 1: # n
OUT (n - 1) C (k - 1) * n OVER k
ESAC;
PROC combinations = (INT m, []DATA list)[,]DATA: (
CASE m IN
# case 1: # ( # transpose list #
[UPB list,1]DATA out;
out[,1]:=list;
out
)
OUT
[UPB list C m, m]DATA out;
INT index out := 1;
FOR i TO UPB list DO
DATA x = list[i];
[,]DATA y = combinations(m - 1, list[i+1:]);
FOR suffix TO UPB y DO
out[index out,1 ] := x;
out[index out,2:] := y[suffix,];
index out +:= 1
OD
OD;
out
ESAC
);
PRIO COMB = 7;
OP COMB = (INT n, k)[,]INT: (
[k]DATA list; # create a list to recombine #
FOR i TO UPB list DO list[i]:=i OD;
combinations(n,list)
);
INT m = 3;
#IF formatted transput possible THEN#
FORMAT data repr = $d$;
FORMAT list repr = $"("n(m-1)(f(data repr)",")f(data repr)")"$;
printf ((list repr, 3 COMB 5, $l$));
#ELSE#
[,]DATA result = 3 COMB 5;
FOR row TO UPB result DO
print ((result[row,], new line))
OD
#FI#

View file

@ -1,12 +0,0 @@
proto combine (Int, @) {*}
multi combine (0, @) { [] }
multi combine ($, []) { () }
multi combine ($n, [$head, *@tail]) {
gather {
take [$head, @$_] for combine($n-1, @tail);
take [ @$_ ] for combine($n , @tail);
}
}
say combine(3, [^5]).perl;

View file

@ -1,8 +0,0 @@
implicit def toComb(m: Int) = new AnyRef {
def comb(n: Int) = recurse(m, List.range(0, n))
private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match {
case (0, _) => List(Nil)
case (_, Nil) => Nil
case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail)
}
}

View file

@ -1 +0,0 @@
* an asterisk in 7th column comments the line out

View file

@ -1,6 +0,0 @@
eval(2*3) # eval(2*3) "#" and text after it aren't processed but passed along
dnl this text completely disappears, including the new line
divert(-1)
Everything diverted to -1 is processed but the output is discarded.
A comment could take this form as long as no macro names are used.
divert

View file

@ -1,20 +0,0 @@
#include <iostream>
#include <ppl.h> // MSVC++
void a(void) { std::cout << "Eat\n"; }
void b(void) { std::cout << "At\n"; }
void c(void) { std::cout << "Joe's\n"; }
int main()
{
// function pointers
Concurrency::parallel_invoke(&a, &b, &c);
// C++11 lambda functions
Concurrency::parallel_invoke(
[]{ std::cout << "Enjoy\n"; },
[]{ std::cout << "Rosetta\n"; },
[]{ std::cout << "Code\n"; }
);
return 0;
}

View file

@ -1,2 +0,0 @@
(doseq [text ["Enjoy" "Rosetta" "Code"]]
(future (println text)))

View file

@ -1,5 +0,0 @@
exec = require('child_process').exec
for word in ["Enjoy", "Rosetta", "Code"]
exec "echo #{word}", (err, stdout) ->
console.log stdout

View file

@ -1,17 +0,0 @@
void
foo()
{
if (pari_daemon()) {
// Original
if (pari_daemon()) {
// Original
pari_printf("Enjoy\n");
} else {
// Daemon #2
pari_printf("Code\n");
}
} else {
// Daemon #1
pari_printf("Rosetta\n");
}
}

View file

@ -1,19 +0,0 @@
; if
x = 1
If x
MsgBox, x is %x%
Else If x > 1
MsgBox, x is %x%
Else
MsgBox, x is %x%
; ternary if
x = 2
y = 1
var := x > y ? 2 : 3
MsgBox, % var
; while
While (A_Index < 3) {
MsgBox, %A_Index% is less than 3
}

View file

@ -1,91 +0,0 @@
public class GameOfLife{
public static void main(String[] args){
String[] dish= {
"_#_",
"_#_",
"_#_",};
int gens= 3;
for(int i= 0;i < gens;i++){
System.out.println("Generation " + i + ":");
print(dish);
dish= life(dish);
}
}
public static String[] life(String[] dish){
String[] newGen= new String[dish.length];
for(int row= 0;row < dish.length;row++){//each row
newGen[row]= "";
for(int i= 0;i < dish[row].length();i++){//each char in the row
String above= "";//neighbors above
String same= "";//neighbors in the same row
String below= "";//neighbors below
if(i == 0){//all the way on the left
//no one above if on the top row
//otherwise grab the neighbors from above
above= (row == 0) ? null : dish[row - 1].substring(i,
i + 2);
same= dish[row].substring(i + 1, i + 2);
//no one below if on the bottom row
//otherwise grab the neighbors from below
below= (row == dish.length - 1) ? null : dish[row + 1]
.substring(i, i + 2);
}else if(i == dish[row].length() - 1){//right
//no one above if on the top row
//otherwise grab the neighbors from above
above= (row == 0) ? null : dish[row - 1].substring(i - 1,
i + 1);
same= dish[row].substring(i - 1, i);
//no one below if on the bottom row
//otherwise grab the neighbors from below
below= (row == dish.length - 1) ? null : dish[row + 1]
.substring(i - 1, i + 1);
}else{//anywhere else
//no one above if on the top row
//otherwise grab the neighbors from above
above= (row == 0) ? null : dish[row - 1].substring(i - 1,
i + 2);
same= dish[row].substring(i - 1, i)
+ dish[row].substring(i + 1, i + 2);
//no one below if on the bottom row
//otherwise grab the neighbors from below
below= (row == dish.length - 1) ? null : dish[row + 1]
.substring(i - 1, i + 2);
}
int neighbors= getNeighbors(above, same, below);
if(neighbors < 2 || neighbors > 3){
newGen[row]+= "_";//<2 or >3 neighbors -> die
}else if(neighbors == 3){
newGen[row]+= "#";//3 neighbors -> spawn/live
}else{
newGen[row]+= dish[row].charAt(i);//2 neighbors -> stay
}
}
}
return newGen;
}
public static int getNeighbors(String above, String same, String below){
int ans= 0;
if(above != null){//no one above
for(char x: above.toCharArray()){//each neighbor from above
if(x == '#') ans++;//count it if someone is here
}
}
for(char x: same.toCharArray()){//two on either side
if(x == '#') ans++;//count it if someone is here
}
if(below != null){//no one below
for(char x: below.toCharArray()){//each neighbor below
if(x == '#') ans++;//count it if someone is here
}
}
return ans;
}
public static void print(String[] dish){
for(String s: dish){
System.out.println(s);
}
}
}

View file

@ -1,68 +0,0 @@
#include <fstream>
#include <boost/array.hpp>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sstream>
void makeGap( int gap , std::string & text ) {
for ( int i = 0 ; i < gap ; i++ )
text.append( " " ) ;
}
int main( ) {
boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ;
int headgap = 3 ;
int bodygap = 3 ;
int tablegap = 6 ;
int rowgap = 9 ;
std::string tabletext( "<html>\n" ) ;
makeGap( headgap , tabletext ) ;
tabletext += "<head></head>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "<body>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "<table>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<thead align=\"right\">\n" ;
makeGap( tablegap, tabletext ) ;
tabletext += "<tr><th></th>" ;
for ( int i = 0 ; i < 3 ; i++ ) {
tabletext += "<td>" ;
tabletext += *(chars.begin( ) + i ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</thead>" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<tbody align=\"right\">\n" ;
srand( time( 0 ) ) ;
for ( int row = 0 ; row < 5 ; row++ ) {
makeGap( rowgap , tabletext ) ;
std::ostringstream oss ;
tabletext += "<tr><td>" ;
oss << row ;
tabletext += oss.str( ) ;
for ( int col = 0 ; col < 3 ; col++ ) {
oss.str( "" ) ;
int randnumber = rand( ) % 10000 ;
oss << randnumber ;
tabletext += "<td>" ;
tabletext.append( oss.str( ) ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
}
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</tbody>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "</table>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "</body>\n" ;
tabletext += "</html>\n" ;
std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ;
htmltable << tabletext ;
htmltable.close( ) ;
return 0 ;
}

View file

@ -1,13 +0,0 @@
import java.util.{Calendar, GregorianCalendar}
import Calendar._
object DayOfTheWeek {
def main(args:Array[String]) {
for (year <- 2008 to 2121;
date <- Some(new GregorianCalendar(year, DECEMBER, 25));
if date.get(DAY_OF_WEEK) == SUNDAY) {
println(year)
}
}
}

View file

@ -1,76 +0,0 @@
#include <windows.h>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class fc_dealer
{
public:
void deal( int game )
{
_gn = game;
fillDeck();
shuffle();
display();
}
private:
void fillDeck()
{
int p = 0;
for( int c = 0; c < 13; c++ )
for( int s = 0; s < 4; s++ )
_cards[p++] = c | s << 4;
}
void shuffle()
{
srand( _gn );
int cc = 52, nc, lc;
while( cc )
{
nc = rand() % cc;
lc = _cards[--cc];
_cards[cc] = _cards[nc];
_cards[nc] = lc;
}
}
void display()
{
char* suit = "CDHS";
char* symb = "A23456789TJQK";
int z = 0;
cout << "GAME #" << _gn << endl << "=======================" << endl;
for( int c = 51; c >= 0; c-- )
{
cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " ";
if( ++z >= 8 )
{
cout << endl;
z = 0;
}
}
}
int _cards[52], _gn;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
fc_dealer dealer;
int gn;
while( true )
{
cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn;
if( !gn ) break;
system( "cls" );
dealer.deal( gn );
cout << endl << endl;
}
return 0;
}
//--------------------------------------------------------------------------------------------------

View file

@ -1,76 +0,0 @@
#import <Foundation/Foundation.h>
@interface Delegator : NSObject {
id delegate;
}
- (id)delegate;
- (void)setDelegate:(id)obj;
- (NSString *)operation;
@end
@implementation Delegator
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)obj {
delegate = obj; // Weak reference
}
- (NSString *)operation {
if ([delegate respondsToSelector:@selector(thing)])
return [delegate thing];
return @"default implementation";
}
@end
// Any object may implement these
@interface NSObject (DelegatorDelegating)
- (NSString *)thing;
@end
@interface Delegate : NSObject
// Don't need to declare -thing because any NSObject has this method
@end
@implementation Delegate
- (NSString *)thing {
return @"delegate implementation";
}
@end
// Example usage
// Memory management ignored for simplification
int main() {
// Without a delegate:
Delegator *a = [[Delegator alloc] init];
NSLog(@"%d\n", [[a operation] isEqualToString:@"default implementation"]);
// With a delegate that does not implement thing:
[a setDelegate:@"A delegate may be any object"];
NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]);
// With a delegate that implements "thing":
Delegate *d = [[Delegate alloc] init];
[a setDelegate:d];
NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]);
return 0;
}

View file

@ -1,11 +0,0 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files.
PROCEDURE DIVISION.
CALL "CBL_DELETE_FILE" USING "input.txt"
CALL "CBL_DELETE_DIR" USING "docs"
CALL "CBL_DELETE_FILE" USING "/input.txt"
CALL "CBL_DELETE_DIR" USING "/docs"
GOBACK
.

View file

@ -1,58 +0,0 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. Is-Numeric.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Numeric-Chars PIC X(10) VALUE "0123456789".
01 Success CONSTANT 0.
*> By convention, a non-zero value is used to signify failure
01 Failure CONSTANT 128.
LOCAL-STORAGE SECTION.
01 I PIC 99.
01 Num-Decimal-Points PIC 99.
01 Num-Valid-Chars PIC 99.
LINKAGE SECTION.
01 Str PIC X(30).
PROCEDURE DIVISION USING BY VALUE Str.
IF Str = SPACES
MOVE Failure TO Return-Code
GOBACK
END-IF
MOVE FUNCTION TRIM(Str) TO Str
INSPECT Str TALLYING Num-Decimal-Points FOR ALL "."
IF Num-Decimal-Points > 1
MOVE Failure TO Return-Code
GOBACK
ELSE
ADD Num-Decimal-Points TO Num-Valid-Chars
END-IF
IF Str (1:1) = "-" OR "+"
ADD 1 TO Num-Valid-Chars
END-IF
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10
INSPECT Str TALLYING Num-Valid-Chars
FOR ALL Numeric-Chars (I:1) BEFORE SPACE
END-PERFORM
INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES
IF Num-Valid-Chars = FUNCTION LENGTH(Str)
MOVE Success TO Return-Code
ELSE
MOVE Failure TO Return-Code
END-IF
GOBACK
.

View file

@ -1 +0,0 @@
(define (string-numeric? s) (number? (string->number s)))

View file

@ -1,15 +0,0 @@
floor[x_,y_]:=Flatten[Position[y,x]][[1]]
Select[Permutations[{"Baker","Cooper","Fletcher","Miller","Smith"}],
( floor["Baker",#] < 5 )
&&( Abs[floor["Fletcher",#] - floor["Cooper",#]] > 1 )
&&( Abs[floor["Fletcher",#] - floor["Smith",#]] > 1 )
&&( 1 < floor["Cooper",#] < floor["Miller",#] )
&&( 1 < floor["Fletcher",#] < 5 )
&] [[1]] //Reverse //Column
->
Miller
Fletcher
Baker
Cooper
Smith

View file

@ -1,38 +0,0 @@
def dinesman(floors, names, criteria)
# the "bindVars" method returns a context where the "name" variables are bound to values
eval "
def bindVars(#{names.map {|n| n.downcase}.join ','})
return binding
end
"
expression = criteria.map {|c| "(#{c.downcase})"}.join " and "
floors.permutation.each do |perm|
b = bindVars *perm
return b if b.eval(expression)
end
nil
end
floors = (1..5).to_a
names = %w(Baker Cooper Fletcher Miller Smith)
criteria = [
"Baker != 5",
"Cooper != 1",
"Fletcher != 1",
"Fletcher != 5",
"Miller > Cooper",
"(Smith - Fletcher).abs != 1",
"(Fletcher - Cooper).abs != 1",
]
b = dinesman(floors, names, criteria)
if b.nil?
puts "no solution"
else
puts "Found a solution:"
len = names.map {|n| n.length}.max
residents = names.inject({}) {|r, n| r[b.eval(n.downcase)] = n; r}
floors.each {|f| puts " Floor #{f}: #{residents[f]}"}
end

View file

@ -1,65 +0,0 @@
module Philosophers where
import Control.Monad
import Control.Concurrent
import Control.Concurrent.STM
import System.Random
-- TMVars are transactional references. They can only be used in transactional actions.
-- They are either empty or contain one value. Taking an empty reference fails and
-- putting a value in a full reference fails. A transactional action only succeeds
-- when all the component actions succeed, else it rolls back and retries until it
-- succeeds.
-- The Int is just for display purposes.
type Fork = TMVar Int
newFork :: Int -> IO Fork
newFork i = newTMVarIO i
-- The basic transactional operations on forks
takeFork :: Fork -> STM Int
takeFork fork = takeTMVar fork
releaseFork :: Int -> Fork -> STM ()
releaseFork i fork = putTMVar fork i
type Name = String
runPhilosopher :: Name -> (Fork, Fork) -> IO ()
runPhilosopher name (left, right) = forever $ do
putStrLn (name ++ " is hungry.")
-- Run the transactional action atomically.
-- The type system ensures this is the only way to run transactional actions.
(leftNum, rightNum) <- atomically $ do
leftNum <- takeFork left
rightNum <- takeFork right
return (leftNum, rightNum)
putStrLn (name ++ " got forks " ++ show leftNum ++ " and " ++ show rightNum ++ " and is now eating.")
delay <- randomRIO (1,10)
threadDelay (delay * 1000000) -- 1, 10 seconds. threadDelay uses nanoseconds.
putStrLn (name ++ " is done eating. Going back to thinking.")
atomically $ do
releaseFork leftNum left
releaseFork rightNum right
delay <- randomRIO (1, 10)
threadDelay (delay * 1000000)
philosophers :: [String]
philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"]
main = do
forks <- mapM newFork [1..5]
let namedPhilosophers = map runPhilosopher philosophers
forkPairs = zip forks (tail . cycle $ forks)
philosophersWithForks = zipWith ($) namedPhilosophers forkPairs
putStrLn "Running the philosophers. Press enter to quit."
mapM_ forkIO philosophersWithForks
-- All threads exit when the main thread exits.
getLine

View file

@ -1,19 +0,0 @@
import java.util.{GregorianCalendar, Calendar}
val DISCORDIAN_SEASONS=Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath")
def ddate(year:Int, month:Int, day:Int):String={
val date=new GregorianCalendar(year, month-1, day)
val dyear=year+1166
val isLeapYear=date.isLeapYear(year)
if(isLeapYear && month==2 && day==29)
return "St. Tib's Day "+dyear+" YOLD"
var dayOfYear=date.get(Calendar.DAY_OF_YEAR)
if(isLeapYear && dayOfYear>=60)
dayOfYear-=1 // compensate for St. Tib's Day
val dday=dayOfYear%73
val season=dayOfYear/73
"%s %d, %d YOLD".format(DISCORDIAN_SEASONS(season), dday, dyear)
}

View file

@ -1,36 +0,0 @@
/*REXX program to show how to display embedded documention in REXX code.*/
parse arg doc
doc=space(doc)
if doc=='?' then call help /*show doc if arg is a single ? */
/*════════════════════════regular═══════════════════════════════════════*/
/*════════════════════════════════mainline══════════════════════════════*/
/*═════════════════════════════════════════code═════════════════════════*/
/*══════════════════════════════════════════════here.═══════════════════*/
exit
/*──────────────────────────────────HELP subroutine─────────────────────*/
help: help=0; do j=1 for sourceline()
_=sourceline(j)
if _=='<help>' then do; help=1; iterate; end
if _=='</help>' then exit
if help then say _
end /*j*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────start of the in─line documentation.
<help>
To use the YYYY program, enter:
YYYY numberOfItems
YYYY (with no args for the default)
YYYY ? (to see this documentation)
where:
numberOfItems is the number of items to be processed.
If no "numberOfItems" are entered, the default of 100 is used.
</help>
end of the inline documentation. */

View file

@ -1,113 +0,0 @@
MODE DATA = STRING; # user defined data type #
MODE MNODE = STRUCT (
NODE pred,
succ,
DATA value
);
MODE LIST = REF MNODE;
MODE NODE = REF MNODE;
STRUCT (
PROC LIST new list,
PROC (LIST)BOOL is empty,
PROC (LIST)NODE get head,
get tail,
PROC (LIST, NODE)NODE add tail,
add head,
PROC (LIST)NODE remove head,
remove tail,
PROC (LIST, NODE, NODE)NODE insert after,
PROC (LIST, NODE)NODE remove node
) class list;
new list OF class list := LIST: (
HEAP MNODE master link;
master link := (master link, master link, ~);
master link
);
is empty OF class list := (LIST self)BOOL:
(LIST(pred OF self) :=: LIST(self)) AND (LIST(self) :=: LIST(succ OF self));
get head OF class list := (LIST self)NODE:
succ OF self;
get tail OF class list := (LIST self)NODE:
pred OF self;
add tail OF class list := (LIST self, NODE node)NODE:
(insert after OF class list)(self, pred OF self, node);
add head OF class list := (LIST self, NODE node)NODE:
(insert after OF class list)(self, succ OF self, node);
remove head OF class list := (LIST self)NODE:
(remove node OF class list)(self, succ OF self);
remove tail OF class list := (LIST self)NODE:
(remove node OF class list)(self, pred OF self);
insert after OF class list := (LIST self, NODE cursor, NODE node)NODE: (
succ OF node := succ OF cursor;
pred OF node := cursor;
succ OF cursor := node;
pred OF succ OF node := node;
node
);
remove node OF class list := (LIST self, NODE node)NODE: (
succ OF pred OF node := succ OF node;
pred OF succ OF node := pred OF node;
succ OF node := pred OF node := NIL; # garbage collection hint #
node
);
main: (
[]DATA sample = ("Was", "it", "a", "cat", "I", "saw");
LIST list a := new list OF class list;
NODE tmp;
IF list a :/=: REF LIST(NIL) THEN # technically "list a" is never NIL #
# Add some data to a list #
FOR i TO UPB sample DO
tmp := HEAP MNODE;
IF tmp :/=: NODE(NIL) THEN # technically "tmp" is never NIL #
value OF tmp := sample[i];
(add tail OF class list)(list a, tmp)
FI
OD;
# Iterate throught the list forward #
NODE node := (get head OF class list)(list a);
print("Iterate orward: ");
WHILE node :/=: NODE(list a) DO
print((value OF node, " "));
node := succ OF node
OD;
print(new line);
# Iterate throught the list backward #
node := (get tail OF class list)(list a);
print("Iterate backward: ");
WHILE node :/=: NODE(list a) DO
print((value OF node, " "));
node := pred OF node
OD;
print(new line);
# Finally empty the list #
print("Empty from tail: ");
WHILE NOT (is empty OF class list)(list a) DO
tmp := (remove tail OF class list)(list a);
print((value OF tmp, " "))
# sweep heap #
OD;
print(new line)
# sweep heap #
FI
)

View file

@ -1,42 +0,0 @@
import std.stdio;
struct Node(T) {
T data;
Node* prev, next;
this(T data_, Node* prev_=null, Node* next_=null) {
data = data_;
prev = prev_;
next = next_;
}
}
void prepend(T)(ref Node!(T)* head, T item) {
auto newNode = new Node!T(item, null, head);
if (head)
head.prev = newNode;
head = newNode;
}
void main() {
Node!(string)* head;
prepend(head, "D");
prepend(head, "C");
prepend(head, "B");
prepend(head, "A");
auto p = head;
auto last = p;
while (p) {
write(p.data, " ");
last = p;
p = p.next;
}
writeln();
while (last) {
write(last.data, " ");
last = last.prev;
}
writeln();
}

View file

@ -1,40 +0,0 @@
import std.stdio, std.algorithm, std.conv, std.string,
std.typetuple, std.traits;
T[][] elementwise(string op, T, U)(in T[][] A, in U B)
@safe pure /*nothrow*/
if (isNumeric!U || (isArray!U && isArray!(ForeachType!U) &&
isNumeric!(ForeachType!(ForeachType!U)))) {
static if (!isNumeric!U)
assert(A.length == B.length);
if (!A.length)
return null;
auto R = new typeof(return)(A.length, A[0].length);
foreach (r, row; A)
static if (isNumeric!U) {
R[r][] = mixin("row[] " ~ op ~ "B");
} else {
assert(row.length == B[r].length);
R[r][] = mixin("row[] " ~ op ~ "B[r][]");
}
return R;
}
string matRep(T)(in T[][] m) /*@safe pure nothrow*/ {
return "[" ~ join(map!text(m), ",\n ") ~ "]";
}
void main() {
const matrix = [[3, 5, 7],
[1, 2, 3],
[2, 4, 6]];
const scalar = 2;
foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) {
writeln(op, ":");
writeln(matRep(elementwise!op(matrix, scalar)), "\n");
writeln(matRep(elementwise!op(matrix, matrix)), "\n");
}
}

View file

@ -1,3 +0,0 @@
const integer: foo is 42;
const string: bar is "bar";
const blahtype: blah is blahvalue;

View file

@ -1,5 +0,0 @@
sub entropy(@a) {
[+] map -> \p { p * -log p }, @a.bag.values »/» +@a;
}
say log(2) R/ entropy '1223334444'.comb;

View file

@ -1,34 +0,0 @@
from __future__ import division
import math
def hist(source):
hist = {}; l = 0;
for e in source:
l += 1
if e not in hist:
hist[e] = 0
hist[e] += 1
return (l,hist)
def entropy(hist,l):
elist = []
for v in hist.values():
c = v / l
elist.append(-c * math.log(c ,2))
return sum(elist)
def printHist(h):
flip = lambda (k,v) : (v,k)
h = sorted(h.iteritems(), key = flip)
print 'Sym\thi\tfi\tInf'
for (k,v) in h:
print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h)

View file

@ -1,8 +0,0 @@
function factorial(n)
factorial = 1
if n>0 then
for p=1 to n
factorial *= p
next p
end if
end function

View file

@ -1,10 +0,0 @@
function factorial(n::Integer)
if n < 0
return zero(n)
end
f = one(n)
for i = 2:n
f *= i
end
return f
end

View file

@ -1,3 +0,0 @@
sub postfix:<!> { [*] 1..$^n }
say 5!; #prints 120

View file

@ -1 +0,0 @@
fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)

View file

@ -1,13 +0,0 @@
/*REXX pgm to verify a file's size (by reading the lines) in CD & root. */
parse arg iFID . /*let user specify the file ID. */
if iFID=='' then iFID='FILESIZ.DAT' /*Not specified? Then use default*/
say 'size of' iFID '=' filesize(iFID) /*current directory.*/
say 'size of \..\'iFID '=' filesize('\..\'iFID) /* root directory.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────FILESIZE subroutine─────────────────*/
filesize: parse arg f
do r=1 while lines(f)\==0
call linein f
end /*r*/
return r-1

View file

@ -1,6 +0,0 @@
var arr:Array = new Array(1, 2, 3, 4, 5);
var evens:Array = new Array();
for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0)
evens.push(arr[i]);
}

View file

@ -1 +0,0 @@
selecteven(v)=vecextract(v,1<<(#v\2*2+1)\3);

View file

@ -1,39 +0,0 @@
public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/"); //split on file separator
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j]; //grab the next folder name in the first path
boolean allMatched = true; //assume all have matched in case there are no more paths
for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths
if(folders[i].length < j){ //if there is no folder here
allMatched = false; //no match
break; //stop looking because we've gone as far as we can
}
//otherwise
allMatched &= folders[i][j].equals(thisFolder); //check if it matched
}
if(allMatched){ //if they all matched this folder name
commonPath += thisFolder + "/"; //add it to the answer
}else{//otherwise
break;//stop looking
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}

View file

@ -1,6 +0,0 @@
(use 'clojure.contrib.combinatorics)
(use 'clojure.set)
(def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" )))
(def s1 (apply hash-set (permutations "ABCD")))
(def missing (difference s1 given))

View file

@ -1,10 +0,0 @@
#lang racket
(define (compose f g) (λ (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 0.5)))

View file

@ -1,45 +0,0 @@
function startsOnFriday(month, year)
{
// 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
return new Date(year, month, 1).getDay() === 5;
}
function has31Days(month, year)
{
return new Date(year, month, 31).getDate() === 31;
}
function checkMonths(year)
{
var month, count = 0;
for (month = 0; month < 12; month += 1)
{
if (startsOnFriday(month, year) && has31Days(month, year))
{
count += 1;
document.write(year + ' ' + month + '<br>');
}
}
return count;
}
function fiveWeekends()
{
var
startYear = 1900,
endYear = 2100,
year,
monthTotal = 0,
yearsWithoutFiveWeekends = [],
total = 0;
for (year = startYear; year <= endYear; year += 1)
{
monthTotal = checkMonths(year);
total += monthTotal;
// extra credit
if (monthTotal === 0)
yearsWithoutFiveWeekends.push(year);
}
document.write('Total number of months: ' + total + '<br>');
document.write('<br>');
document.write(yearsWithoutFiveWeekends + '<br>');
document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '<br>');
}
fiveWeekends();

View file

@ -1,22 +0,0 @@
;; Solution 1:
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(princ (cond ((zerop (mod x 15)) "FizzBuzz")
((zerop (mod x 3)) "Fizz")
((zerop (mod x 5)) "Buzz")
(t x)))
(terpri)))
;; Solution 2:
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(format t "~&~{~A~}"
(or (append (when (zerop (mod x 3)) '("Fizz"))
(when (zerop (mod x 5)) '("Buzz")))
(list x)))))
;; Solution 3:
(defun fizzbuzz ()
(loop for n from 1 to 100
do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%"
(mod n 3) (mod n 5) n)))

View file

@ -1,11 +0,0 @@
for i = 1:100
if i % 15 == 0
println("FizzBuzz")
elseif i % 3 == 0
println("Fizz")
elseif i % 5 == 0
println("Buzz")
else
println(i)
end
end

View file

@ -1,4 +0,0 @@
(defun flatten (structure)
(cond ((null structure) nil)
((atom structure) `(,structure))
(t (mapcan #'flatten structure))))

View file

@ -1,10 +0,0 @@
julia> t = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
8-element Int32 Array:
1
2
3
4
5
6
7
8

View file

@ -1,6 +0,0 @@
#floyd(n) creates an n-row floyd's triangle counting from 1 to (n/2+.5)*n
function floyd(n)
x = 1
dig(x,line,n) = (while line < n; x+=line; line+= 1 end; return ndigits(x)+1)
for line = 1:n, i = 1:line; print(lpad(x,dig(x,line,n)," ")); x+=1; i==line && print("\n") end
end

View file

@ -1,3 +0,0 @@
put edit (X) (p'999999.V999'); /* Western format. */
put edit (X) (p'999999,V999'); /* In European format. */

View file

@ -1,3 +0,0 @@
7.125 "%09.3f" print
00007.125

View file

@ -1,67 +0,0 @@
import std.stdio, std.traits;
void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
in T b0, in T b1, in T b2, in T b3,
out T o0, out T o1,
out T o2, out T o3,
out T overflow) pure nothrow {
// A XOR using only NOT, AND and OR, as task requires
static T xor(in T x, in T y) pure nothrow {
return (~x & y) | (x & ~y);
}
static void halfAdder(in T a, in T b,
out T s, out T c) pure nothrow {
s = xor(a, b);
// s = a ^ b; // a natural XOR in D
c = a & b;
}
static void fullAdder(in T a, in T b, in T ic,
out T s, out T oc) pure nothrow {
T ps, pc, tc;
halfAdder(/*input*/a, b, /*output*/ps, pc);
halfAdder(/*input*/ps, ic, /*output*/s, tc);
oc = tc | pc;
}
T zero, tc0, tc1, tc2;
fullAdder(/*input*/a0, b0, zero, /*output*/o0, tc0);
fullAdder(/*input*/a1, b1, tc0, /*output*/o1, tc1);
fullAdder(/*input*/a2, b2, tc1, /*output*/o2, tc2);
fullAdder(/*input*/a3, b3, tc2, /*output*/o3, overflow);
}
void main() {
alias size_t T;
static assert(isUnsigned!T);
enum T one = T.max,
zero = T.min,
a0 = zero, a1 = one, a2 = zero, a3 = zero,
b0 = zero, b1 = one, b2 = one, b3 = one;
T s0, s1, s2, s3, overflow;
fourBitsAdder(/*input*/ a0, a1, a2, a3,
/*input*/ b0, b1, b2, b3,
/*output*/s0, s1, s2, s3, overflow);
writefln(" a3 %032b", a3);
writefln(" a2 %032b", a2);
writefln(" a1 %032b", a1);
writefln(" a0 %032b", a0);
writefln(" +");
writefln(" b3 %032b", b3);
writefln(" b2 %032b", b2);
writefln(" b1 %032b", b1);
writefln(" b0 %032b", b0);
writefln(" =");
writefln(" s3 %032b", s3);
writefln(" s2 %032b", s2);
writefln(" s1 %032b", s1);
writefln(" s0 %032b", s0);
writefln("overflow %032b", overflow);
}

View file

@ -1,43 +0,0 @@
import dfl.all;
import std.math;
class FractalTree: Form {
private const double DEG_TO_RAD = PI / 180.0;
this() {
width = 600;
height = 500;
text = "Fractal Tree";
backColor = Color(0xFF, 0xFF, 0xFF);
startPosition = FormStartPosition.CENTER_SCREEN;
formBorderStyle = FormBorderStyle.FIXED_DIALOG;
maximizeBox = false;
}
private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) {
if (depth == 0) return;
int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0);
int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0);
g.drawLine(p, x1, y1, x2, y2);
drawTree(g, p, x2, y2, angle - 20, depth - 1);
drawTree(g, p, x2, y2, angle + 20, depth - 1);
}
protected override void onPaint(PaintEventArgs ea){
super.onPaint(ea);
Pen p = new Pen(Color(0, 0xAA, 0));
drawTree(ea.graphics, p, 300, 450, -90, 9);
}
}
int main() {
int result = 0;
try {
Application.run(new FractalTree);
} catch(Object o) {
msgBox(o.toString(), "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR);
result = 1;
}
return result;
}

View file

@ -1,3 +0,0 @@
function multiply(a::Number,b::Number)
return a*b
end

View file

@ -1,93 +0,0 @@
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, randButton;
public Interact(){
//stop the GUI threads when the user hits the X button
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numberField = new JTextField();
incButton = new JButton("Increment");
randButton = new JButton("Random");
numberField.setText("0");//start at 0
//listen for button presses in the text field
numberField.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
//if the entered character is not a digit
if(!Character.isDigit(e.getKeyChar())){
//eat the event (i.e. stop it from being processed)
e.consume();
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e){}
});
//listen for button clicks on the increment button
incButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String text = numberField.getText();
if(text.isEmpty()){
numberField.setText("1");
}else{
numberField.setText((Long.valueOf(text) + 1) + "");
}
}
});
//listen for button clicks on the random button
randButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//show a dialog and if they answer "Yes"
if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
JOptionPane.YES_OPTION){
//set the text field text to a random positive long
numberField.setText(Long.toString((long)(Math.random()
* Long.MAX_VALUE)));
}
}
});
//arrange the components in a grid with 2 rows and 1 column
setLayout(new GridLayout(2, 1));
//a secondary panel for arranging both buttons in one grid space in the window
JPanel buttonPanel = new JPanel();
//the buttons are in a grid with 1 row and 2 columns
buttonPanel.setLayout(new GridLayout(1, 2));
//add the buttons
buttonPanel.add(incButton);
buttonPanel.add(randButton);
//put the number field on top of the buttons
add(numberField);
add(buttonPanel);
//size the window appropriately
pack();
}
public static void main(String[] args){
new Interact().setVisible(true);
}
}

View file

@ -1,8 +0,0 @@
procedure Swap_T(var a, b: T);
var
temp: T;
begin
temp := a;
a := b;
b := temp;
end;

View file

@ -1,6 +0,0 @@
fn gcd(a: int,b: int) -> int {
match b {
0 => return a,
_ => return gcd(b,(a%b)),
}
}

View file

@ -1,30 +0,0 @@
import std.stdio;
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow {
int maxSum, thisSum, i, start, end = -1;
foreach (j, x; sequence) {
thisSum += x;
if (thisSum < 0) {
i = j + 1;
thisSum = 0;
} else if (thisSum > maxSum) {
maxSum = thisSum;
start = i;
end = j;
}
}
if (start <= end && start >= 0 && end >= 0)
return sequence[start .. end + 1];
else
return [];
}
void main() {
const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
writeln("Maximal subsequence: ", maxSubseq(a1));
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
writeln("Maximal subsequence: ", maxSubseq(a2));
}

View file

@ -1,30 +0,0 @@
#include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
/* second char is for the newline from hitting [return] */
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
/* using a binary search */
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( "\nAwwwright\n" );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Is the number %d? (Y/H/L) ", choice );
}while( scanf( "%1s", input ) == 1 );
return 0;
}

View file

@ -1,24 +0,0 @@
/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/
parse arg x .; if x=='' then x=27 /*get the optional first argument*/
numeric digits 20
$=hailstone(x) /*═════════════task 1════════════*/
say x 'has a hailstone sequence of' #hs 'and starts with: ' subword($,1,4),
' and ends with:' subword($,#hs-3)
say
w=0; do j=1 for 99999 /*═════════════task 2════════════*/
call hailstone j /*compute the hailstone sequence.*/
if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/
bigJ=j; w=#hs /*remember what # has biggest HS.*/
end /*j*/
say '(between 199,999) ' bigJ 'has the longest hailstone sequence:' w
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────HAILSTONE subroutine────────────────*/
hailstone: procedure expose #hs; parse arg n 1 s /*N & S set to 1st arg*/
do #hs=1 while n\==1 /*loop while N isn't unity. */
if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */
else n=n%2 /* " " " even, perform fast ÷ */
s=s n /*build a sequence list (append).*/
end /*#hs*/
return s

View file

@ -1,15 +0,0 @@
function happy(x)
happy_ints = ref(Int)
int_try = 1
while length(happy_ints) < x
n = int_try
past = ref(Int)
while n != 1
n = sum([int(string(y))^2 for y in string(n)])
contains(past,n) ? break : push!(past,n)
end
if n == 1 push!(happy_ints,int_try) end
int_try += 1
end
return happy_ints
end

View file

@ -1,11 +0,0 @@
use List::Util qw(sum);
sub is_happy ($)
{for (my ($n, %seen) = shift ;; $n = sum map {$_**2} split //, $n)
{$n == 1 and return 1;
$seen{$n}++ and return 0;}}
for (my ($n, $happy) = (1, 0) ; $happy < 8 ; ++$n)
{is_happy $n or next;
print "$n\n";
++$happy;}

View file

@ -1,24 +0,0 @@
/*REXX program finds first X Niven numbers; also first Niven number > Y.*/
parse arg X Y . /*get optional arguments: X Y */
if X=='' then X=20 /*Not specified? Then use default*/
if Y=='' then Y=1000 /*Not specified? Then use default*/
#=0; $= /*Niven# count, Niven# list. */
do j=1 until #==X /*let's go Niven number hunting. */
if j//sumDigs(j)\==0 then iterate /*Not a Niven number? Then skip.*/
#=#+1; $=$ j /*bump Niven# count, add to list.*/
end /*j*/
say 'first' X 'Niven numbers:' $
do t=1 /*let's go Niven number searching*/
if t//sumDigs(t)\==0 then iterate /*Not a Niven number? Then skip.*/
if t>Y then leave /*if too low, then keep searching*/
end /*t*/
say 'first Niven number >' Y " is: " t
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────SUMDIGS subroutine──────────────────*/
sumDigs: procedure; parse arg ?; sum = left(?,1)
do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/
return sum

View file

@ -1,20 +0,0 @@
#lang racket
(require math/number-theory)
(define (digital-sum n)
(let inner
((n n) (s 0))
(if (zero? n) s
(let-values ([(q r) (quotient/remainder n 10)])
(inner q (+ s r))))))
(define (harshad-number? n)
(and (>= n 1)
(divides? (digital-sum n) n)))
;; find 1st 20 Harshad numbers
(for ((i (in-range 1 (add1 20)))
(h (sequence-filter harshad-number? (in-naturals 1))))
(printf "#~a ~a~%" i h))
;; find 1st Harshad number > 1000
(displayln (for/first ((h (sequence-filter harshad-number? (in-naturals 1001)))) h))

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