YAPC::EU 2018 Glasgow Update!

This commit is contained in:
Ingy döt Net 2018-08-17 15:15:24 +01:00
parent 22f33d4004
commit 4e2d22a71d
1170 changed files with 15042 additions and 3047 deletions

View file

@ -1,5 +1,7 @@
var doors = falses(100)
for a in 1..100: for b in a..a..100:
doors[b] = not doors[b]
for a in 1..100:
print "Door $a is $((doors[a]) ? 'open.': 'closed.')"
print "Door $a is ${(doors[a]) ? 'open.': 'closed.'}"

View file

@ -0,0 +1,125 @@
#include <iostream> // compiled with clang (tags/RELEASE_600/final)
#include <type_traits> // or g++ (GCC) 7.3.1 20180406 -- from hare1039
namespace functional_list // basic building block for template meta programming
{
struct NIL
{
using head = NIL;
using tail = NIL;
friend std::ostream& operator << (std::ostream& os, NIL const) { return os; }
};
template <typename H, typename T = NIL>
struct list
{
using head = H;
using tail = T;
};
template <int i>
struct integer
{
static constexpr int value = i;
friend std::ostream& operator << (std::ostream& os, integer<i> const) { os << integer<i>::value; return os;}
};
template <typename L, int nTH> constexpr
auto at()
{
if constexpr (nTH == 0)
return (typename L::head){};
else if constexpr (not std::is_same_v<typename L::tail, NIL>)
return at<typename L::tail, nTH - 1>();
else
return NIL{};
}
template <typename L, int nTH>
using at_t = decltype(at<L, nTH>());
template <typename L, typename elem> constexpr
auto prepend() { return list<elem, L>{}; }
template <typename L, typename elem>
using prepend_t = decltype(prepend<L, elem>());
template <int Size, typename Dat = integer<0>> constexpr
auto gen_list()
{
if constexpr (Size == 0)
return NIL{};
else
{
using next = decltype(gen_list<Size - 1, Dat>());
return prepend<next, Dat>();
}
}
template <int Size, typename Dat = integer<0>>
using gen_list_t = decltype(gen_list<Size, Dat>());
} namespace fl = functional_list;
constexpr int door_amount = 101; // index from 1 to 100
template <typename L, int current, int moder> constexpr
auto construct_loop()
{
using val_t = fl::at_t<L, current>;
if constexpr (std::is_same_v<val_t, fl::NIL>)
return fl::NIL{};
else
{
constexpr int val = val_t::value;
using val_add_t = fl::integer<val + 1>;
using val_old_t = fl::integer<val>;
if constexpr (current == door_amount)
{
if constexpr(current % moder == 0)
return fl::list<val_add_t>{};
else
return fl::list<val_old_t>{};
}
else
{
using sub_list = decltype(construct_loop<L, current + 1, moder>());
if constexpr(current % moder == 0)
return fl::prepend<sub_list, val_add_t>();
else
return fl::prepend<sub_list, val_old_t>();
}
}
}
template <int iteration> constexpr
auto construct()
{
if constexpr (iteration == 1) // door index = 1
{
using l = fl::gen_list_t<door_amount>;
return construct_loop<l, 0, iteration>();
}
else
{
using prev_iter_list = decltype(construct<iteration - 1>());
return construct_loop<prev_iter_list, 0, iteration>();
}
}
template <typename L, int pos> constexpr
void show_ans()
{
if constexpr (std::is_same_v<typename L::head, fl::NIL>)
return;
else
{
if constexpr (L::head::value % 2 == 1)
std::cout << "Door " << pos << " is opened.\n";
show_ans<typename L::tail, pos + 1>();
}
}
int main()
{
using result = decltype(construct<100>());
show_ans<result, 0>();
}

View file

@ -1,7 +1,7 @@
import system'routines.
import extensions.
public program =
public program
[
var Doors := Array new:100; populate(:n)( false ).
@ -19,4 +19,4 @@ public program =
].
console readChar.
].
]

View file

@ -1,40 +1,10 @@
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? then 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
end
doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." }
doors = Array.new(101,0)
print "Open doors "
(1..100).step(){ |i|
(i..100).step(i) { |d|
doors[d] = doors[d]^= 1
if i == d and doors[d] == 1 then
print "#{i} "
end
}
}

View file

@ -1,18 +1,40 @@
n = 100
Open = "open"
Closed = "closed"
def Open.toggle
Closed
end
def Closed.toggle
Open
end
doors = [Closed] * (n + 1)
for mul in 1..n
for x in (mul..n).step(mul)
doors[x] = doors[x].toggle
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? then open else close end
end
def to_s
@state.to_s
end
end
doors.each_with_index do |b, i|
puts "Door #{i} is #{b}" if i > 0
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
end
doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." }

View file

@ -1,4 +1,18 @@
n = 100
(1..n).each do |i|
puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}"
Open = "open"
Closed = "closed"
def Open.toggle
Closed
end
def Closed.toggle
Open
end
doors = [Closed] * (n + 1)
for mul in 1..n
for x in (mul..n).step(mul)
doors[x] = doors[x].toggle
end
end
doors.each_with_index do |b, i|
puts "Door #{i} is #{b}" if i > 0
end

View file

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

View file

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

View file

@ -0,0 +1,28 @@
00000064 0000 1 n = 100
0000 0000 2 .entry doors, ^m<>
26'AF 9F 0002 3 pushab b^arr ; offset signed byte
50 64 8F 9A 0005 4 movzbl #n, r0
50 DD 0009 5 pushl r0 ; (sp) -> .ascid arr
000B 6 10$:
51 50 D0 000B 7 movl r0, r1 ; step = start index
000E 8 20$:
25'AF41 01 8C 000E 9 xorb2 #^a"0" \^a"1", b^arr-1[r1] ; \ xor toggle "1"<->"0"
FFF5 51 50 6E F1 0013 10 acbl (sp), r0, r1, 20$ ; limit, step, index
EF 50 F5 0019 11 sobgtr r0, 10$ ; n..1
001C 12
5E DD 001C 13 pushl sp ; descriptor by reference
00000000'GF 01 FB 001E 14 calls #1, g^lib$put_output ; show result
04 0025 15 ret
0026 16
30'30'30'30'30'30'30'30'30'30'30'30' 0026 17 arr: .byte ^a"0"[n]
30'30'30'30'30'30'30'30'30'30'30'30' 0032
30'30'30'30'30'30'30'30'30'30'30'30' 003E
30'30'30'30'30'30'30'30'30'30'30'30' 004A
30'30'30'30'30'30'30'30'30'30'30'30' 0056
30'30'30'30'30'30'30'30'30'30'30'30' 0062
30'30'30'30'30'30'30'30'30'30'30'30' 006E
30'30'30'30'30'30'30'30'30'30'30'30' 007A
30'30'30'30' 0086
008A 18 .end doors
$ run doors
1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001

View file

@ -167,9 +167,9 @@ extension gameOp
]
}
public program =
public program
[
var aGame := TwentyFourGame new; help.
while (aGame prompt; playRound(console readLine)) [].
].
]

View file

@ -1,7 +1,4 @@
# Project : 24 game
# Date : 2018/02/21
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "stdlib.ring"
digits = list(4)

View file

@ -1,29 +1,21 @@
-module(god_the_integer).
-export([example/0, names/1, print_pyramid/1]).
-module(triangle).
-export([start/1]).
start(N)->
print(1,1,N).
print(N,N,N)->
1;
print(A,B,N) when A>=B->
io:format("~p ",[formula(A,B)]),
print(A,B+1,N);
print(A,B,N) when B>A->
io:format("~n"),
print(A+1,1,N).
example() ->
Names = names( 10 ),
print_pyramid( Names ).
names( N ) ->
[names_row(X) || X <- lists:seq(1, N)].
print_pyramid( Names ) ->
Width = erlang:length( lists:last(Names) ),
[print_pyramid_row(Width, X) || X <- Names].
names_row( M ) ->
[p(M, X) || X <- lists:seq(1, M)].
p( N, K ) when K > N -> 0;
p( N, N ) -> 1;
p( _N, 0 ) -> 0;
p( N, K ) ->
p( N - 1, K - 1 ) + p( N - K, K ).
print_pyramid_row( Width, Row ) ->
io:fwrite( "~*s", [Width - erlang:length(Row), " "] ),
[io:fwrite("~p ", [X]) || X <- Row],
io:nl().
formula(_,0)->
0;
formula(B,B)->
1;
formula(A,B) when B>A->
0;
formula(A1,B1)->
formula(A1-1,B1-1)+formula(A1-B1,B1).

View file

@ -3,10 +3,10 @@ fun bottles(n):
| 1 => "1 bottle"
| _ => "$n bottles"
for n in !99..1:
for n in 99..-1..1:
print """
$(bottles n) of beer on the wall
$(bottles n) of beer
${bottles n} of beer on the wall
${bottles n} of beer
Take one down, pass it around
$(bottles n-1) of beer on the wall\n
${bottles n-1} of beer on the wall\n
"""

View file

@ -1,15 +1,28 @@
#include <stdlib.h>
/*
* 99 Bottles, C, KISS (i.e. keep it simple and straightforward) version
*/
#include <stdio.h>
int main(void)
{
unsigned int bottles = 99;
do
{
printf("%u bottles of beer on the wall\n", bottles);
printf("%u bottles of beer\n", bottles);
printf("Take one down, pass it around\n");
printf("%u bottles of beer on the wall\n\n", --bottles);
} while(bottles > 0);
return EXIT_SUCCESS;
int n;
for( n = 99; n > 2; n-- )
printf(
"%d bottles of beer on the wall, %d bottles of beer.\n"
"Take one down and pass it around, %d bottles of beer on the wall.\n\n",
n, n, n - 1);
printf(
"2 bottles of beer on the wall, 2 bottles of beer.\n"
"Take one down and pass it around, 1 bottle of beer on the wall.\n\n"
"1 bottle of beer on the wall, 1 bottle of beer.\n"
"Take one down and pass it around, no more bottles of beer on the wall.\n\n"
"No more bottles of beer on the wall, no more bottles of beer.\n"
"Go to the store and buy some more, 99 bottles of beer on the wall.\n");
return 0;
}

View file

@ -27,9 +27,9 @@ extension bottleOp
].
}
public program =
public program
[
var bottles := 99.
bottles bottleEnumerator; forEach:printingLn.
].
]

View file

@ -0,0 +1,4 @@
(let ((i 99))
(while (> i 0)
(princ-list i " bottles of beer on the wall" "\n Take one down, pass it around")
(setq i (1- i))))

View file

@ -1,36 +1,35 @@
: bottles ( n -- ) \ select the right grammar based on 'n'
dup
case
1 of ." One more bottle " drop endof
0 of ." No more bottles " drop endof
. ." bottles " \ default case
endcase ;
DECIMAL
: BOTTLES ( n -- )
DUP
CASE
1 OF ." One more bottle " DROP ENDOF
0 OF ." NO MORE bottles " DROP ENDOF
. ." bottles " \ DEFAULT CASE
ENDCASE ;
\ create punctuation with delay for artistic effect
: , [char] , emit 100 ms ;
: . [char] . emit 300 ms ;
: , [CHAR] , EMIT SPACE 100 MS CR ;
: . [CHAR] . EMIT 300 MS CR CR CR ;
\ create the words to write the program
: of ." of " ;
: beer ." beer " ;
: on ." on " ;
: the ." the " ;
: wall ." wall" ;
: take ." take " ;
: one ." one " ;
: down ." down" ;
: pass ." pass " ;
: it ." it " ;
: around ." around" ;
: OF ." of " ; : BEER ." beer " ;
: ON ." on " ; : THE ." the " ;
: WALL ." wall" ; : TAKE ." take " ;
: ONE ." one " ; : DOWN ." down, " ;
: PASS ." pass " ; : IT ." it " ;
: AROUND ." around" ;
\ who said Forth is write only?
: beers ( n -- ) \ USAGE: 99 beers
1 swap
cr
do
I bottles of beer on the wall , cr
I bottles of beer , cr
take one down , pass it around , cr
I 1- bottles of beer on the wall . cr
cr
-1 +loop ;
: POPONE 1 SWAP CR ;
: DRINK POSTPONE DO ; IMMEDIATE
: ANOTHER S" -1 +LOOP" EVALUATE ; IMMEDIATE
: HOWMANY S" I " EVALUATE ; IMMEDIATE
: ONELESS S" I 1- " EVALUATE ; IMMEDIATE
: HANGOVER ." :-(" CR QUIT ;
: BEERS ( n -- ) \ Usage: 99 BEERS
POPONE
DRINK
HOWMANY BOTTLES OF BEER ON THE WALL ,
HOWMANY BOTTLES OF BEER ,
TAKE ONE DOWN PASS IT AROUND ,
ONELESS BOTTLES OF BEER ON THE WALL .
ANOTHER
HANGOVER ;

View file

@ -0,0 +1,28 @@
"""Pythonic 99 beer song (readability counts)."""
regular_verse = '''\
{n} bottles of beer on the wall, {n} bottles of beer
Take one down and pass it around, {n_minus_1} bottles of beer on the wall.
'''
ending_verses = '''\
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
'''
# @todo: It is possible to refactor the code to avoid n-1 in the code,
# notice that the last line of any verse and the first line of the next
# verse share the same number of bottles. Nevertheless the code
# would be less readliable.
for n in range(99, 2, -1):
print(regular_verse.format(n=n, n_minus_1=n - 1))
print(ending_verses)

View file

@ -0,0 +1,26 @@
"""Pythonic 99 beer song (readability counts)."""
first = '''\
99 bottles of beer on the wall, 99 bottles of beer
'''
middle = '''\
Take one down and pass it around, {n} bottles of beer on the wall.
{n} bottles of beer on the wall, {n} bottles of beer
'''
last = '''\
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
'''
print(first)
for n in range(98, 1, -1):
print(middle.format(n=n))
print(last)

View file

@ -1,7 +1,5 @@
rebol [
Title: "99 Bottles of Beer"
Author: oofoe
Date: 2009-12-11
URL: http://rosettacode.org/wiki/99_Bottles_of_Beer
]

View file

@ -1,9 +1,9 @@
import extensions.
public program =
public program
[
var A := Integer new.
var B := Integer new.
console readLine(A,B); writeLine(A + B).
].
console readLine(A,B); writeLine(A + B)
]

View file

@ -1,10 +1,10 @@
import system'routines.
import extensions.
public program =
public program
[
console writeLine(console readLine;
split;
selectBy(%"convertorOp.toInt[0]");
summarize).
].
summarize)
]

View file

@ -0,0 +1,14 @@
import Foundation
let input = FileHandle.standardInput
let data = input.availableData
let str = String(data: data, encoding: .utf8)!
let nums = str.split(separator: " ")
.map { String($0.unicodeScalars
.filter { CharacterSet.decimalDigits.contains($0) }) }
let a = Int(nums[0])!
let b = Int(nums[1])!
print(" \(a + b)")

View file

@ -1,7 +1,8 @@
fun abc(str, list):
if list.isEmpty: return true
for i in indices(list) where s[!1] in list[i]:
return abc(str[:!2], remove(val list, i))
if list.isempty:
return true
for i in indices(list) where s[end] in list[i]:
return abc(str[end-1:], remove(val list, i))
false
let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
@ -9,4 +10,4 @@ let list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
for str in test:
print "$:>8(s) | $(abc(s, list))"
print "$|>8|{s} | ${abc(s, list)}"

View file

@ -21,7 +21,7 @@ extension op
]
}
public program =
public program
[
var blocks := ("BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
@ -33,5 +33,5 @@ public program =
words forEach(:word)
[
console printLine("can make '",word,"' : ",word canMakeWordFrom:blocks).
].
].
]
]

View file

@ -59,7 +59,7 @@ singleton AksTest
]
}
public program =
public program
[
0 till:10 do(:n)<int>
[
@ -78,5 +78,5 @@ public program =
]
].
console printLine; readLine
].
console printLine; readChar
]

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Abstract Type"
Author: oofoe
Date: 2009-12-05
URL: http://rosettacode.org/wiki/Abstract_type
]

View file

@ -0,0 +1,4 @@
p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v
++\1-:1`#^_$:28*:*:*/\28*vv_^#<<<!%*:*:*82:-1\-1\<<<\+**:*:*82<+>*:*:**\2-!#+
v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01<
>:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@

View file

@ -31,11 +31,11 @@ classifyNumbers =
]
}.
public program =
public program
[
int abundant := 0.
int deficient := 0.
int perfect := 0.
classifyNumbers eval(20000, &abundant, &deficient, &perfect).
console printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect).
].
console printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect)
]

View file

@ -0,0 +1,25 @@
\ RossetaCode 'accumulator factory'
\ The 'accumulate' word stores the accumulated value in an array, because arrays
\ are mutable:
: accumulate \ n [m] -- n+m \ [m] -> [n+m]
a:pop rot n:+
tuck a:push swap ;
\ To comply with the rules, this takes a number and wraps it in an array, and
\ then curries it. Since 'curry:' is "immediate", we need to postpone its
\ action using 'p:.
: make-accumulator
1 a:close
' accumulate
p: curry: ;
\ We 'curry' the initial value along with 'accumulate' to create
\ a new word, '+10', which will give us the accumulated values
10 make-accumulator +10
\ This loop will add 1, then 2, then 3, to the accumulator, which prints the
\ results 11,13,16:
( +10 . cr ) 1 3 loop
bye

View file

@ -1,5 +1,7 @@
fun accumulator(sum) = |n| => sum += n
fun accumulator(sum): n => sum += n
let f = accumulator(5.)
print f(5) # 10.0
print f(10) # 20.0
print f(2.4) # 22.4

View file

@ -1,10 +1,10 @@
function =
(:acc)((:n)(acc append:n)).
function(acc)
= (:n)(acc append:n).
accumulator =
(:n)(function(Variable new(n))).
accumulator(n)
= function(Variable new(n)).
public program =
public program
[
var x := accumulator(1).
@ -12,5 +12,5 @@ public program =
var y := accumulator(3).
console write(x(2.3r)).
].
console write(x(2.3r))
]

View file

@ -5,5 +5,5 @@ sub accumulator {
my $x = accumulator(1);
$x->(5);
print accumulator(3), "\n";
accumulator(3);
print $x->(2.3), "\n";

View file

@ -1,6 +1,6 @@
import extensions.
ackermann = (:m:n)
ackermann(m,n)
[
if((n < 0)||(m < 0))
[
@ -14,9 +14,9 @@ ackermann = (:m:n)
0 [ ^ackermann(m - 1,1) ];
! [ ^ackermann(m - 1,ackermann(m,n-1)) ]
]
].
]
public program =
public program
[
0 to:3 do(:i)
[
@ -26,5 +26,5 @@ public program =
]
].
console readChar.
].
console readChar
]

View file

@ -1,53 +1,90 @@
package main
import (
"fmt"
"math/big"
"unsafe"
"fmt"
"math/big"
"math/bits" // Added in Go 1.9
)
var one = big.NewInt(1)
var two = big.NewInt(2)
var three = big.NewInt(3)
var eight = big.NewInt(8)
var u uint
var uBits = int(unsafe.Sizeof(u))*8 - 1
func Ackermann2(m, n *big.Int) *big.Int {
if m.Cmp(three) <= 0 {
switch m.Int64() {
case 0:
return new(big.Int).Add(n, one)
case 1:
return new(big.Int).Add(n, two)
case 2:
r := new(big.Int).Lsh(n, 1)
return r.Add(r, three)
case 3:
if n.BitLen() > uBits {
panic("way too big")
}
r := new(big.Int).Lsh(eight, uint(n.Int64()))
return r.Sub(r, three)
}
}
if n.BitLen() == 0 {
return Ackermann2(new(big.Int).Sub(m, one), one)
}
return Ackermann2(new(big.Int).Sub(m, one),
Ackermann2(m, new(big.Int).Sub(n, one)))
if m.Cmp(three) <= 0 {
switch m.Int64() {
case 0:
return new(big.Int).Add(n, one)
case 1:
return new(big.Int).Add(n, two)
case 2:
r := new(big.Int).Lsh(n, 1)
return r.Add(r, three)
case 3:
if nb := n.BitLen(); nb > bits.UintSize {
// n is too large to represent as a
// uint for use in the Lsh method.
panic(TooBigError(nb))
// If we tried to continue anyway, doing
// 8*2^n-3 as bellow, we'd use hundreds
// of megabytes and lots of CPU time
// without the Exp call even returning.
r := new(big.Int).Exp(two, n, nil)
r.Mul(eight, r)
return r.Sub(r, three)
}
r := new(big.Int).Lsh(eight, uint(n.Int64()))
return r.Sub(r, three)
}
}
if n.BitLen() == 0 {
return Ackermann2(new(big.Int).Sub(m, one), one)
}
return Ackermann2(new(big.Int).Sub(m, one),
Ackermann2(m, new(big.Int).Sub(n, one)))
}
type TooBigError int
func (e TooBigError) Error() string {
return fmt.Sprintf("A(m,n) had n of %d bits; too large", int(e))
}
func main() {
show(0, 0)
show(1, 2)
show(2, 4)
show(3, 100)
show(4, 1)
show(4, 3)
show(0, 0)
show(1, 2)
show(2, 4)
show(3, 100)
show(3, 1e6)
show(4, 1)
show(4, 2)
show(4, 3)
}
func show(m, n int64) {
fmt.Printf("A(%d, %d) = ", m, n)
fmt.Println(Ackermann2(big.NewInt(m), big.NewInt(n)))
defer func() {
// Ackermann2 could/should have returned an error
// instead of a panic. But here's how to recover
// from the panic, and report "expected" errors.
if e := recover(); e != nil {
if err, ok := e.(TooBigError); ok {
fmt.Println("Error:", err)
} else {
panic(e)
}
}
}()
fmt.Printf("A(%d, %d) = ", m, n)
a := Ackermann2(big.NewInt(m), big.NewInt(n))
if a.BitLen() <= 256 {
fmt.Println(a)
} else {
s := a.String()
fmt.Printf("%d digits starting/ending with: %s...%s\n",
len(s), s[:20], s[len(s)-20:],
)
}
}

View file

@ -0,0 +1,6 @@
#! /usr/local/bin/newlisp
(define (ackermann m n)
(cond ((zero? m) (inc n))
((zero? n) (ackermann (dec m) 1))
(true (ackermann (- m 1) (ackermann m (dec n))))))

View file

@ -0,0 +1,36 @@
import org.apache.directory.api.ldap.model.message.SearchScope
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
object LdapSearchDemo extends App {
class LdapSearch {
def demonstrateSearch(): Unit = {
val conn = new LdapNetworkConnection("localhost", 11389)
try {
conn.bind("uid=admin,ou=system", "********")
search(conn, "*mil*")
conn.unBind()
} finally if (conn != null) conn.close()
}
private def search(connection: LdapConnection, uid: String): Unit = {
val baseDn = "ou=users,o=mojo"
val filter = "(&(objectClass=person)(&(uid=" + uid + ")))"
val scope = SearchScope.SUBTREE
val attributes = List("dn", "cn", "sn", "uid")
var ksearch = 0
val cursor = connection.search(baseDn, filter, scope, attributes: _*)
while (cursor.next) {
ksearch += 1
val entry = cursor.get
printf("Search entry %d = %s%n", ksearch, entry)
}
}
}
new LdapSearch().demonstrateSearch()
}

View file

@ -10,7 +10,7 @@ class Extender :: BaseExtender
]
}
public program =
public program
[
var anObject := 234.
@ -21,5 +21,5 @@ public program =
console printLine(anObject,".foo=",anObject foo).
console readChar.
].
console readChar
]

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Add Variables to Class at Runtime"
Author: oofoe
Date: 2009-12-04
URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime
]

View file

@ -1,5 +1,7 @@
var num = 12
var pointer = ptr(num) # get pointer
print pointer # print address
unsafe: # bad idea!
pointer.addr = 0xFFFE # set the address
@unsafe # bad idea!
pointer.addr = 0xFFFE # set the address

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Align Columns"
Author: oofoe
Date: 2010-09-29
URL: http://rosettacode.org/wiki/Align_columns
]

View file

@ -12,7 +12,7 @@ being K and subsequent members being the sum of the [[Proper divisors]] of the p
:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence <code>562, 284, 220, 284, 220, ...</code> such K are called '''cyclic'''.
:<br>And finally:
:* Some K form aliquot sequences that are not known to be either terminating or periodic. these K are to be called '''non-terminating'''. <br>For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. <br>For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
;Task:

View file

@ -1,5 +1,3 @@
/*Abhishek Ghosh, 1st November 2017*/
#include<stdlib.h>
#include<string.h>
#include<stdio.h>

View file

@ -1,5 +1,3 @@
/*Abhishek Ghosh, 7th November 2017*/
#include<string.h>
#include<stdlib.h>
#include<stdio.h>

View file

@ -0,0 +1,54 @@
USING: combinators combinators.short-circuit formatting kernel
literals locals math math.functions math.primes.factors
math.ranges namespaces pair-rocket sequences sets ;
FROM: namespaces => set ;
IN: rosetta-code.aliquot
SYMBOL: terms
CONSTANT: 2^47 $[ 2 47 ^ ]
CONSTANT: test-cases {
11 12 28 496 220 1184 12496 1264460 790
909 562 1064 1488 15355717786080
}
: next-term ( n -- m ) dup divisors sum swap - ;
: continue-aliquot? ( hs term -- hs term ? )
{
[ terms get 15 < ]
[ swap in? not ]
[ nip zero? not ]
[ nip 2^47 < ]
} 2&& ;
: next-aliquot ( hs term -- hs next-term term )
[ swap [ adjoin ] keep ]
[ dup [ next-term ] dip ] bi terms inc ;
: aliquot ( k -- seq )
0 terms set HS{ } clone swap
[ continue-aliquot? ] [ next-aliquot ] produce
[ drop ] 2dip swap suffix ;
: non-terminating? ( seq -- ? )
{ [ length 15 > ] [ [ 2^47 > ] any? ] } 1|| ;
:: classify ( seq -- classification-str )
{
[ seq non-terminating? ] => [ "non-terminating" ]
[ seq last zero? ] => [ "terminating" ]
[ seq length 2 = ] => [ "perfect" ]
[ seq length 3 = ] => [ "amicable" ]
[ seq first seq last = ] => [ "sociable" ]
[ seq 2 tail* first2 = ] => [ "aspiring" ]
[ "cyclic" ]
} cond ;
: .classify ( k -- )
dup aliquot [ classify ] keep "%14u: %15s: %[%d, %]\n"
printf ;
: main ( -- )
10 [1,b] test-cases append [ .classify ] each ;
MAIN: main

View file

@ -1,7 +1,4 @@
# Project : Aliquot sequence classnifications
# Date : 2017/11/16
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
see "Rosetta Code - aliquot sequence classnifications" + nl
while true

View file

@ -0,0 +1,66 @@
Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
'display the classification and sequences of the numbers one to ten inclusive
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next j
'show the classification and sequences of the following integers, in order:
Dim a
'15 355 717 786 080 : impossible in VBA ==> out of memory
a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)
For j = LBound(a) To UBound(a)
result = Aliq(CDbl(a(j)))
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next
End Sub
Private Function Aliq(Nb As Double) As Aliquot
Dim s() As Double, i As Long, temp, j As Long, cpt As Long
temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic")
ReDim s(0)
s(0) = Nb
For i = 1 To 15
cpt = cpt + 1
ReDim Preserve s(cpt)
s(i) = SumPDiv(s(i - 1))
If s(i) > 140737488355328# Then Exit For
If s(i) = 0 Then j = 1
If s(1) = s(0) Then j = 2
If s(i) = s(0) And i > 1 And i <> 2 Then j = 4
If s(i) = s(i - 1) And i > 1 Then j = 5
If i >= 2 Then
If s(2) = s(0) Then j = 3
If s(i) = s(i - 2) And i <> 2 Then j = 6
End If
If j > 0 Then Exit For
Next
Aliq.Classification = temp(j)
Aliq.Sequence = s
End Function
Private Function SumPDiv(n As Double) As Double
'returns the sum of the Proper divisors of n
Dim j As Long, t As Long
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then t = t + j
Next
End If
SumPDiv = t
End Function

View file

@ -0,0 +1,16 @@
AlmostPrimes:=proc(k, numvalues::posint:=10)
local aprimes, i, intfactors;
aprimes := Array([]);
i := 0;
do
i := i + 1;
intfactors := ifactors(i)[2];
intfactors := [seq(seq(intfactors[i][1], j=1..intfactors[i][2]),i = 1..numelems(intfactors))];
if numelems(intfactors) = k then
ArrayTools:-Append(aprimes,i);
end if;
until numelems(aprimes) = 10:
aprimes;
end proc:
<seq( AlmostPrimes(i), i = 1..5 )>;

View file

@ -2,46 +2,45 @@ import system'routines.
import extensions.
import extensions'routines.
joinable = (:aFormer:aLater)(aFormer[aFormer length - 1] == aLater[0]).
joinable(former,later) = (former[former length - 1] == later[0]).
dispatcher =
{
eval(object anArray, Func2 aFunction)
eval(object a, Func2 f)
[
^ aFunction(anArray[0],anArray[1]).
^ f(a[0],a[1]).
]
eval(object anArray, Func3 aFunction)
eval(object a, Func3 f)
[
^ aFunction(anArray[0], anArray[1],anArray[2]).
^ f(a[0], a[1],a[2]).
]
eval(object anArray, Func4 aFunction)
eval(object a, Func4 f)
[
^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3]).
^ f(a[0],a[1],a[2],a[3]).
]
eval(object anArray, Func5 aFunction)
eval(object a, Func5 f)
[
^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3],anArray[4]).
^ f(a[0],a[1],a[2],a[3],a[4]).
]
}.
class AmbValueCollection
{
object theCombinator.
constructor new(V<object> Arguments)
generic constructor new(V<object> args)
[
theCombinator := SequentialEnumerator new(Arguments).
theCombinator := SequentialEnumerator new(args).
]
seek : aCondition
seek : cond
[
theCombinator reset.
theCombinator seekEach(:v)(dispatcher eval(v,aCondition))
theCombinator seekEach(:v)(dispatcher eval(v,cond))
]
do : aFunction
@ -55,11 +54,11 @@ class AmbValueCollection
ambOperator =
{
generic for(V<object> Arguments)
= AmbValueCollection new(Arguments).
generic for(V<object> args)
= AmbValueCollection new(args).
}.
public program =
public program
[
try(ambOperator
for(("the","that","a"),("frog", "elephant", "thing"),("walked", "treaded", "grows"),("slowly", "quickly"));
@ -72,5 +71,5 @@ public program =
]
}.
console readChar.
].
console readChar
]

View file

@ -1,22 +1,22 @@
/*REXX program demonstrates the Amd operator, choosing a word from each set. */
@.=; @.1 = "the that a"
@.2 = "frog elephant thing"
@.3 = "walked treaded grows"
@.=; @.1 = "the that a"
@.2 = "frog elephant thing"
@.3 = "walked treaded grows"
@.4 = "slowly quickly"
call Amb 1 /*find all word combinations that works*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Amb: procedure expose @.; parse arg # x; arg . u /*2nd parse uppercases U*/
do j=1 until @.j==''; end /*locate a null string. */
t=j-1 /*define number of sets.*/
if #>t then do; w=word(u,1) /*W: is a uppercased U*/
do n=2 to words(u); ?=word(u, n)
if left(?, 1) \== right(w, 1) then return; w=?
end /*n*/
say space(x)
Amb: procedure expose @.; parse arg # x; arg . u /*ARG uppercases U values. */
do j=1 until @.j=='' /*locate a null string. */
end /*j*/
t= j-1 /*define number of sets. */
if #>t then do; y=word(u, 1) /*Y: is a uppercased U. */
do n=2 to words(u); ?=word(u, n)
if left(?, 1) \== right(y, 1) then return; y=?
end /*n*/
say space(x) /*¬show superfluous blanks.*/
end
do k=1 for words(@.#) /*process words in sets.*/
call Amb #+1 x word(@.#, k) /*generate combinations,*/
end /*k*/ /* [↑] (recursively).*/
return
do k=1 for words(@.#); call Amb #+1 x word(@.#, k)
end /*k*/ /* [↑] generate all combs */
return /* recursively. */

32
Task/Amb/Ring/amb.ring Normal file
View file

@ -0,0 +1,32 @@
# Project : Amb
set1 = ["the","that","a"]
set2 = ["frog","elephant","thing"]
set3 = ["walked","treaded","grows"]
set4 = ["slowly","quickly"]
text = amb(set1,set2,set3,set4)
if text != ""
see "Correct sentence would be: " + nl + text + nl
else
see "Failed to fine a correct sentence."
ok
func wordsok(string1, string2)
if substr(string1,len(string1),1) = substr(string2,1,1)
return true
ok
return false
func amb(a,b,c,d)
for a2 = 1 to len(a)
for b2 =1 to len(b)
for c2 = 1 to len(c)
for d2 = 1 to len(d)
if wordsok(a[a2],b[b2]) and wordsok(b[b2],c[c2]) and wordsok(c[c2],d[d2])
return a[a2]+" "+b[b2]+" "+c[c2]+" "+d[d2]
ok
next
next
next
next
return ""

View file

@ -0,0 +1,6 @@
v_@#-*8*:"2":$_:#!2#*8#g*#6:#0*#!:#-*#<v>*/.55+,
1>$$:28*:*:*%\28*:*:*/`06p28*:*:*/\2v %%^:*:<>*v
+|!:-1g60/*:*:*82::+**:*:<<>:#**#8:#<*^>.28*^8 :
:v>>*:*%/\28*:*:*%+\v>8+#$^#_+#`\:#0<:\`1/*:*2#<
2v^:*82\/*:*:*82:::_v#!%%*:*:*82\/*:*:*82::<_^#<
>>06p:28*:*:**1+01-\>1+::28*:*:*/\28*:*:*%:*\`!^

View file

@ -0,0 +1,33 @@
import extensions.
import system'routines'stex.
import system'math.
import system'collections.
const int Limit = 20000.
extension op
{
properDivisors
= Range new(1,self / 2); filterBy(:n)<int,bool>(self mod:n == 0).
amicablePairs
[
auto divsums := List<int>(Range new(0, self); selectBy(:i)<int,int>(i properDivisors; summarize)).
^ Range from:1 till(divsums length);
filterBy(:i)<int,bool>
[
var sum := divsums[i].
^ (i < sum) && (sum < divsums length) && (divsums[sum] == i)
];
selectBy(:i)<int,Tuple<int,int>>(Tuple<int,int>(i,divsums[i])).
]
}
public program
[
Limit amicablePairs; forEach(:pair)<Tuple<int,int>>
[
console printLine(pair item1, " ", pair item2).
]
]

View file

@ -1,7 +1,4 @@
# Project : Anagrams/Deranged anagrams
# Date : 2017/11/28
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "stdlib.ring"
fn1 = "unixdict.txt"

View file

@ -7,13 +7,13 @@ import extensions'text.
extension op
{
normalized
= self toArray; ascendant; summarize(StringWriter new); literal.
T<literal> normalized
= self toArray; ascendant; summarize(StringWriter new).
}
public program =
public program
[
var aDictionary := Dictionary new.
auto aDictionary := Map<literal,object>().
File new("unixdict.txt"); forEachLine(:aWord)
[
var s := aWord.
@ -29,8 +29,8 @@ public program =
].
aDictionary values;
sort(:aFormer:aLater)( aFormer length > aLater length );
top:20; forEach(:aPair)[ console printLine(aPair value) ].
sort(:aFormer:aLater)( aFormer item2; length > aLater item2; length );
top:20; forEach(:aPair)[ console printLine(aPair item2) ].
console readChar.
].
console readChar
]

View file

@ -1,7 +1,4 @@
# Project : Anagrams
# Date : 2017/11/28
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "stdlib.ring"
fn1 = "unixdict.txt"

View file

@ -5,46 +5,61 @@
include pGUI.e
Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
cdCanvas cdcanvas
constant g = 50
atom alpha = PI/2,
omega = 0
atom angle = PI/2,
velocity = 0
integer w, h, len = 0
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
-- new suspension point and length
{w, h} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cdcanvas)
cdCanvasClear(cdcanvas)
-- new suspension point:
integer sX = floor(w/2)
integer sY = floor(h/8)
integer len = sX-30
atom dt = 1/w
-- move:
atom epsilon = -len*sin(alpha)*g
omega += dt*epsilon
alpha += dt*omega
integer sY = floor(h/16)
-- repaint:
integer eX = floor(len*sin(alpha)+sX)
integer eY = floor(len*cos(alpha)+sY)
cdCanvasSetForeground(cddbuffer, CD_DARK_GREY)
cdCanvasLine(cddbuffer, sX, h-sY, eX, h-eY)
cdCanvasSetForeground(cddbuffer, CD_BLACK)
cdCanvasSector(cddbuffer, eX, h-eY, 35, 35, 0, 360)
cdCanvasFlush(cddbuffer)
integer eX = floor(len*sin(angle)+sX)
integer eY = floor(len*cos(angle)+sY)
cdCanvasSetForeground(cdcanvas, CD_CYAN)
cdCanvasLine(cdcanvas, sX, h-sY, eX, h-eY)
cdCanvasSetForeground(cdcanvas, CD_DARK_GREEN)
cdCanvasSector(cdcanvas, sX, h-sY, 5, 5, 0, 360)
cdCanvasSetForeground(cdcanvas, CD_BLUE)
cdCanvasSector(cdcanvas, eX, h-eY, 35, 35, 0, 360)
cdCanvasFlush(cdcanvas)
return IUP_DEFAULT
end function
function timer_cb(Ihandle /*ih*/)
integer newlen = floor(w/2)-30
if newlen!=len then
len = newlen
atom tmp = 2*g*len*(cos(angle))
velocity = iff(tmp<0?0:sqrt(tmp)*sign(velocity))
end if
atom dt = 0.2/w
atom delta = -len*sin(angle)*g
velocity += dt*delta
angle += dt*velocity
IupUpdate(canvas)
return IUP_IGNORE
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_GREY)
atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
IupGLMakeCurrent(canvas)
cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res})
cdCanvasSetBackground(cdcanvas, CD_PARCHMENT)
return IUP_DEFAULT
end function
function canvas_resize_cb(Ihandle /*canvas*/)
integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE")
atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
cdCanvasSetAttribute(cdcanvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res})
return IUP_DEFAULT
end function
@ -56,10 +71,11 @@ end function
procedure main()
IupOpen()
canvas = IupCanvas(NULL)
canvas = IupGLCanvas()
IupSetAttribute(canvas, "RASTERSIZE", "640x380")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb"))
timer = IupTimer(Icallback("timer_cb"), 20)

View file

@ -1,7 +1,4 @@
# Project : Animate a pendulum
# Date : 2018/04/09
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "guilib.ring"
load "stdlib.ring"

View file

@ -1,33 +1,33 @@
include arwen.ew
--
-- demo\rosetta\Animation.exw
--
include pGUI.e
string hw = "Hello World! "
integer direction = 1
bool direction = true
Ihandle label
constant main = create(Window, "Animation", 0, 0, 20, 20, 300, 150, 0),
label = create(Label,hw,0,main,65,40,200,40,0),
MainTimer = createTimer()
setFont(label, "Verdana", 18, Normal)
removeStyle(main,WS_THICKFRAME+WS_MINIMIZEBOX+WS_MAXIMIZEBOX)
function mainHandler(integer id, integer msg, atom wParam, object lParam)
if msg=WM_SHOWWINDOW then
startTimer(MainTimer,main,160)
elsif msg=WM_TIMER then
if direction then
hw = hw[$]&hw[1..-2]
else
hw = hw[2..$]&hw[1]
end if
setText(label,hw)
elsif msg=WM_LBUTTONUP then
direction = 1-direction
elsif msg=WM_CHAR
and wParam=VK_ESCAPE then
closeWindow(main)
if id or object(lParam) then end if -- suppress warnings
end if
return 0
function timer_cb(Ihandle /*ih*/)
hw = iff(direction?hw[$]&hw[1..-2]:hw[2..$]&hw[1])
IupSetAttribute(label,"TITLE",hw)
return IUP_IGNORE
end function
setHandler({main},routine_id("mainHandler"))
WinMain(main, SW_NORMAL)
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if c=K_UP then direction = not direction end if
return IUP_CONTINUE
end function
procedure main()
IupOpen()
label = IupLabel(hw,"FONT=\"Verdana, 18\"")
Ihandle dlg = IupDialog(label,"TITLE=Animation, DIALOGFRAME=YES, CHILDOFFSET=70x40, SIZE=200x80")
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
IupShow(dlg)
Ihandle hTimer = IupTimer(Icallback("timer_cb"), 160)
IupMainLoop()
IupClose()
end procedure
main()

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Basic Animation"
Author: oofoe
Date: 2009-12-06
URL: http://rosettacode.org/wiki/Basic_Animation
]

View file

@ -1,7 +1,4 @@
# Project : Animation
# Date : 2018/01/18
# Author : Gal Zsolt [~ CalmoSoft ~]
# Email : <calmosoft@gmail.com>
Load "guilib.ring"
load "stdlib.ring"

View file

@ -1,35 +1,28 @@
import extensions.
extension mathOp
{
fib
[
if (self < 0)
[ InvalidArgumentException new:"Must be non negative"; raise ].
fib(n)
[
if (n < 0)
[ InvalidArgumentException new:"Must be non negative"; raise ].
^ target evalSelf(:n)
[
if (n > 1)
[ ^ @self(n - 2) + @self(n - 1) ];
[ ^ n ]
].
]
}
^ (:n)
[
if (n > 1)
[ ^ @self(n - 2) + @self(n - 1) ];[ ^ n ]
](n)
]
public program =
public program
[
-1 to:10 do(:i)
[
console print("fib(",i,")=").
try (console printLine(i fib))
try (console printLine("fib(",i,")=",fib(i)))
{
on(Exception e)
[
console printLine:"invalid"
]
}.
}
].
console readChar.
].
console readChar
]

View file

@ -1,7 +1,4 @@
# Project : Anonymous recursion
# Date : 2018/01/03
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
t=0
for x = -2 to 12

View file

@ -1,6 +1,6 @@
import system'routines.
public program =
public program
[
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) forEach(:n) [ console writeLine(n * n) ].
].
]

View file

@ -0,0 +1 @@
map (\x->x+1) [1,2,3] -- [2,3,4]

View file

@ -0,0 +1 @@
map (+1) [1,2,3] -- [2,3,4]

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Array Callback"
Date: 2010-01-04
Author: oofoe
URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array
]

View file

@ -1,18 +1,19 @@
package main
import (
"fmt"
"math/big"
"fmt"
"math/big"
)
func main() {
answer := big.NewInt(42)
answer.Exp(big.NewInt(5), answer.Exp(big.NewInt(4),
answer.Exp(big.NewInt(3), big.NewInt(2), nil), nil), nil)
answer_string := answer.String()
length := len(answer_string)
fmt.Printf("has %d digits: %s ... %s\n",
length,
answer_string[0:20],
answer_string[length-20:])
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}

View file

@ -0,0 +1,142 @@
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
// VERY rudimentary C memory management independent of C library's malloc.
// Linked list (yes, this is inefficient)
struct __ALLOCC_ENTRY__
{
void * allocatedAddr;
size_t size;
struct __ALLOCC_ENTRY__ * next;
};
typedef struct __ALLOCC_ENTRY__ __ALLOCC_ENTRY__;
// Keeps track of allocated memory and metadata
__ALLOCC_ENTRY__ * __ALLOCC_ROOT__ = NULL;
__ALLOCC_ENTRY__ * __ALLOCC_TAIL__ = NULL;
// Add new metadata to the table
void _add_mem_entry(void * location, size_t size)
{
__ALLOCC_ENTRY__ * newEntry = (__ALLOCC_ENTRY__ *) mmap(NULL, sizeof(__ALLOCC_ENTRY__), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (__ALLOCC_TAIL__ != NULL)
{
__ALLOCC_TAIL__ -> next = newEntry;
__ALLOCC_TAIL__ = __ALLOCC_TAIL__ -> next;
}
else
{
// Create new table
__ALLOCC_ROOT__ = newEntry;
__ALLOCC_TAIL__ = newEntry;
}
__ALLOCC_ENTRY__ * tail = __ALLOCC_TAIL__;
tail -> allocatedAddr = location;
tail -> size = size;
tail -> next = NULL;
__ALLOCC_TAIL__ = tail;
}
// Remove metadata from the table given pointer
size_t _remove_mem_entry(void * location)
{
__ALLOCC_ENTRY__ * curNode = __ALLOCC_ROOT__;
// Nothing to do
if (curNode == NULL)
{
return 0;
}
// First entry matches
if (curNode -> allocatedAddr == location)
{
__ALLOCC_ROOT__ = curNode -> next;
size_t chunkSize = curNode -> size;
// No nodes left
if (__ALLOCC_ROOT__ == NULL)
{
__ALLOCC_TAIL__ = NULL;
}
munmap(curNode, sizeof(__ALLOCC_ENTRY__));
return chunkSize;
}
// If next node is null, remove it
while (curNode -> next != NULL)
{
__ALLOCC_ENTRY__ * nextNode = curNode -> next;
if (nextNode -> allocatedAddr == location)
{
size_t chunkSize = nextNode -> size;
if(curNode -> next == __ALLOCC_TAIL__)
{
__ALLOCC_TAIL__ = curNode;
}
curNode -> next = nextNode -> next;
munmap(nextNode, sizeof(__ALLOCC_ENTRY__));
return chunkSize;
}
curNode = nextNode;
}
// Nothing was found
return 0;
}
// Allocate a block of memory with size
// When customMalloc an already mapped location, causes undefined behavior
void * customMalloc(size_t size)
{
// Now we can use 0 as our error state
if (size == 0)
{
return NULL;
}
void * mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
// Store metadata
_add_mem_entry(mapped, size);
return mapped;
}
// Free a block of memory that has been customMalloc'ed
void customFree(void * addr)
{
size_t size = _remove_mem_entry(addr);
munmap(addr, size);
}
int main(int argc, char const *argv[])
{
int *p1 = customMalloc(4*sizeof(int)); // allocates enough for an array of 4 int
int *p2 = customMalloc(sizeof(int[4])); // same, naming the type directly
int *p3 = customMalloc(4*sizeof *p3); // same, without repeating the type name
if(p1) {
for(int n=0; n<4; ++n) // populate the array
p1[n] = n*n;
for(int n=0; n<4; ++n) // print it back out
printf("p1[%d] == %d\n", n, p1[n]);
}
customFree(p1);
customFree(p2);
customFree(p3);
return 0;
}

View file

@ -1,7 +1,7 @@
import system'math.
import extensions.
public program =
public program
[
var a := console readLineTo(Integer new).
var b := console readLineTo(Integer new).
@ -11,4 +11,4 @@ public program =
console printLine(a," * ",b," = ",a * b).
console printLine(a," / ",b," = ",a / b). // truncates towards 0
console printLine(a," % ",b," = ",a mod:b). // matches sign of first operand
].
]

View file

@ -1,7 +1,5 @@
REBOL [
Title: "Integer"
Author: oofoe
Date: 2010-09-29
URL: http://rosettacode.org/wiki/Arithmetic/Integer
]

View file

@ -83,53 +83,62 @@ class Expression
number => theTop.
}
operatorState : ch
[
ch =>
$40 [ // (
^ target newBracket; gotoStarting
];
! [
^ target newToken; append:ch; gotoToken
].
]
singleton operatorState
{
eval(ch)
[
ch =>
$40 [ // (
^ target newBracket; gotoStarting
];
! [
^ target newToken; append:ch; gotoToken
].
]
}
tokenState : ch
[
ch =>
$41 [ // )
^ target closeBracket; gotoToken
];
$42 [ // *
^ target newProduct; gotoOperator
];
$43 [ // +
^ target newSummary; gotoOperator
];
$45 [ // -
^ target newDifference; gotoOperator
];
$47 [ // /
^ target newFraction; gotoOperator
];
! [
^ target append:ch
].
]
singleton tokenState
{
eval(ch)
[
ch =>
$41 [ // )
^ target closeBracket; gotoToken
];
$42 [ // *
^ target newProduct; gotoOperator
];
$43 [ // +
^ target newSummary; gotoOperator
];
$45 [ // -
^ target newDifference; gotoOperator
];
$47 [ // /
^ target newFraction; gotoOperator
];
! [
^ target append:ch
].
]
}
startState : ch
[
ch =>
$40 [ // (
^ target newBracket; gotoStarting
];
$45 [ // -
^ target newToken; append:"0"; newDifference; gotoOperator
];
! [
^ target newToken; append:ch; gotoToken
].
]
singleton startState
{
eval(ch)
[
ch =>
$40 [ // (
^ target newBracket; gotoStarting
];
$45 [ // -
^ target newToken; append:"0"; newDifference; gotoOperator
];
! [
^ target newToken; append:ch; gotoToken
].
]
}
class Scope
{
@ -295,7 +304,7 @@ class Parser
]
}
public program =
public program
[
var aText := StringWriter new.
var aParser := Parser new.
@ -311,5 +320,5 @@ public program =
}.
aText clear
].
].
]
]

View file

@ -0,0 +1,39 @@
package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewFloat(1)
two := big.NewFloat(2)
four := big.NewFloat(4)
prec := uint(768) // say
a := big.NewFloat(1).SetPrec(prec)
g := new(big.Float).SetPrec(prec)
// temporary variables
t := new(big.Float).SetPrec(prec)
u := new(big.Float).SetPrec(prec)
g.Quo(a, t.Sqrt(two))
sum := new(big.Float)
pow := big.NewFloat(2)
for a.Cmp(g) != 0 {
t.Add(a, g)
t.Quo(t, two)
g.Sqrt(u.Mul(a, g))
a.Set(t)
pow.Mul(pow, two)
t.Sub(t.Mul(a, a), u.Mul(g, g))
sum.Add(sum, t.Mul(t, pow))
}
t.Mul(a, a)
t.Mul(t, four)
pi := t.Quo(t, u.Sub(one, sum))
fmt.Println(pi)
}

View file

@ -0,0 +1 @@
[1,2,3] [4,5,6] a:+ .

View file

@ -1,9 +1,9 @@
import extensions.
public program =
public program
[
var a := (1,2,3).
var b := (4,5).
console printLine("(",a,") + (",b,") = (",a + b,")"); readChar.
].
console printLine("(",a,") + (",b,") = (",a + b,")"); readChar
]

View file

@ -1,8 +1,18 @@
# the prefix:<|> operator (called "slip") can be used to interpolate arrays into a list:
sub cat-arrays(@a, @b) {
|@a, |@b
}
my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;
my @a1 = (1,2,3);
my @a2 = (2,3,4);
cat-arrays(@a1,@a2).join(", ").say;
# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.
my @array3 = |@array1, |@array2;
say @array3;
# or just flatten both arrays in one fell swoop
@array3 = flat @array1, @array2;
say @array3;
# On the other hand, if you just want to add the elements
# of the second array to the first, use the .append method.
say @array1.append: @array2;

View file

@ -0,0 +1 @@
{ "one" : 1, "two" : "bad" }

View file

@ -0,0 +1 @@
m:new "one" 1 m:! "two" "bad" m:!

View file

@ -1,6 +1,6 @@
import system'collections.
public program =
public program
[
// 1. Create
var aMap := Dictionary new.
@ -9,4 +9,4 @@ public program =
aMap["key2"]:= "foo2".
aMap["key3"]:= "foo3".
aMap["key4"]:= "foo4".
].
]

View file

@ -0,0 +1,12 @@
import system'collections.
public program
[
// 1. Create
auto aMap := Map<literal,literal>().
aMap["key"] := "foox".
aMap["key"] := "foo".
aMap["key2"]:= "foo2".
aMap["key3"]:= "foo3".
aMap["key4"]:= "foo4".
]

View file

@ -1,5 +1,5 @@
print $hash->{key1};
print $hashref->{key1};
$hash->{key1} = 'val1';
$hashref->{key1} = 'val1';
@hash->{'key1', 'three'} = ('val1', -238.83);
@{$hashref}{('key1', 'three')} = ('val1', -238.83);

View file

@ -1,7 +1,4 @@
# Project Associative array/Creation
# Date 2018/03/24
# Author Gal Zsolt [~ CalmoSoft ~]
# Email <calmosoft@gmail.com>
myarray = [["one",1],
["two",2],

View file

@ -0,0 +1,3 @@
{"one": 1, "two": "bad"}
( swap . space . cr )
m:each

View file

@ -0,0 +1,3 @@
{"one": 1, "two": "bad"} m:keys
( . cr )
a:each

View file

@ -1,7 +1,4 @@
;; Project : Associative array/Iteration
;; Date : 2018/03/08
;; Author : Gal Zsolt [~ CalmoSoft ~]
;; Email : <calmosoft@gmail.com>
(setf x (make-array '(3 2)
:initial-contents '(("hello" 13 ) ("world" 31) ("!" 71))))

View file

@ -2,7 +2,7 @@ import system'collections.
import system'routines.
import extensions.
public program =
public program
[
// 1. Create
var aMap := Dictionary new.
@ -15,4 +15,4 @@ public program =
// Enumerate
aMap forEach
(:aKeyValue)[ console printLine(aKeyValue key," : ",aKeyValue value) ].
].
]

View file

@ -0,0 +1,18 @@
import system'collections.
import system'routines.
import extensions.
public program
[
// 1. Create
auto aMap := Map<literal,literal>().
aMap["key"] := "foox".
aMap["key"] := "foo".
aMap["key2"]:= "foo2".
aMap["key3"]:= "foo3".
aMap["key4"]:= "foo4".
// Enumerate
aMap forEach
(:tuple)[ console printLine(tuple item1," : ",tuple item2) ].
]

View file

@ -1,7 +1,4 @@
# Project : Associative array/Iteration
# Date : 2017/10/22
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
lst = [["hello", 13], ["world", 31], ["!", 71]]
for n = 1 to len(lst)

View file

@ -0,0 +1,93 @@
var bucket
var bucket-size
\ The 'bucket' will be a simple array of some values:
: genbucket \ n --
a:new swap
(
\ make a random int up to 1000
rand-pcg n:abs 1000 n:mod
a:push
) swap times
bucket ! ;
\ display bucket and its total:
: .bucket
bucket lock @
dup . space
' n:+ 0 a:reduce . cr
bucket unlock drop ;
\ Get current value of bucket #x
: bucket@ \ n -- bucket[n]
bucket @
swap a:@ nip ;
\ Transfer x from bucket n to bucket m
: bucket-xfer \ m n x --
>r bucket @
\ m n bucket
over a:@ r@ n:-
rot swap a:!
\ m bucket
over a:@ r> n:+
rot swap a:!
drop ;
\ Get two random indices to check (ensure they're not the same):
: pick2
rand-pcg n:abs bucket-size @ n:mod dup >r
repeat
drop
rand-pcg n:abs bucket-size @ n:mod
r@ over n:=
while!
r> ;
\ Pick two buckets and make them more equal (by a quarter of their difference):
: make-equal
repeat
pick2
bucket lock @
third a:@ >r
over a:@ r> n:-
\ if they are equal, do nothing
dup not if
\ equal, so do nothing
drop -rot 2drop
else
4 n:/ n:int
>r -rot r>
bucket-xfer
then
drop
bucket unlock drop
again ;
\ Moves a quarter of the smaller value from one (random) bucket to another:
: make-redist
repeat
pick2 bucket lock @
\ n m bucket
over a:@ >r \ n m b b[m]
third a:@ r> \ n m b b[n]
n:min 4 n:/ n:int
nip bucket-xfer
bucket unlock drop
again ;
: app:main
\ create 10 buckets with random positive integer values:
10 genbucket bucket @ a:len bucket-size ! drop
\ print the bucket
.bucket
\ the problem's tasks:
' make-equal t:task
' make-redist t:task
\ the print-the-bucket task. We'll do it just 10 times and then quit:
( 1 sleep .bucket ) 10 times
bye ;

View file

@ -1,7 +1,4 @@
# Project : Atomic updates
# Date : 2018/01/01
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
bucket = list(10)
f2 = 0

View file

@ -18,8 +18,8 @@ extension op
^ aSum / aCount.
]
}
public program =
public program
[
var anArray := (1, 2, 3, 4, 5, 6, 7, 8).
console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar.
].
console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar
]

View file

@ -0,0 +1,8 @@
sub avg {
@_ or return 0;
my $sum = 0;
$sum += $_ foreach @_;
return $sum/@_;
}
print avg(qw(3 1 4 1 5 9)), "\n";

View file

@ -1,7 +1,5 @@
rebol [
Title: "Arithmetic Mean (Average)"
Author: oofoe
Date: 2009-12-11
URL: http://rosettacode.org/wiki/Average/Arithmetic_mean
]

View file

@ -1,7 +1,4 @@
# Project : Averages/Mean angle
# Date : 2018/01/08
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
load "stdlib.ring"
decimals(6)

View file

@ -20,7 +20,7 @@ extension op
]
}
public program =
public program
[
var a1 := (4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r).
var a2 := (4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r).
@ -29,4 +29,4 @@ public program =
console printLine("median of (",a2,") is ",a2 median).
console readChar.
].
]

View file

@ -0,0 +1,4 @@
med:{a:x@<x; i:_(#a)%2
$[2!#a; a@i; |a@i,i-1]}
med[v]
2.2819 4.8547

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