task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PARI.2FGP | PARI/GP | v=[];
v=concat(v,7);
v[1] |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Swift_2 | Swift | struct RecursiveFunc<F> {
let o : RecursiveFunc<F> -> F
}
func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B {
let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } }
return r.o(r)
}
let fac = Y { (f: Int -> Int) in
{ $0 <= 1 ? 1 : $0 * f($0-1) }
}
let fib = Y { (f: Int -> Int) in
{ $0 <= 2 ? 1 : f($0-1)+f($0-2) }
}
println("fac(5) = \(fac(5))")
println("fib(9) = \(fib(9))") |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #uBasic.2F4tH | uBasic/4tH | S = 5
i = 1
j = 1
For e = 0 To (S*S)-1
@((i-1) * S + (j-1)) = e
If (i + j) % 2 = 0 Then
If j < S Then
j = j + 1
Else
i = i + 2
EndIf
If i > 1 Then
i = i - 1
EndIf
Else
If i < S
i = i + 1
Else
j = j + 2
EndIf
If j > 1
j = j - 1
EndIf
EndIf
Next
For r = 0 To S-1
For c = 0 To S-1
Print Using "___#";@(r * S + c);
Next
Print
Next |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Ursala | Ursala | #import std
#import nat
zigzag = ~&mlPK2xnSS+ num+ ==+sum~~|=xK9xSL@iiK0+ iota |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Haskell | Haskell | data Door
= Open
| Closed
deriving (Eq, Show)
toggle :: Door -> Door
toggle Open = Closed
toggle Closed = Open
toggleEvery :: Int -> [Door] -> [Door]
toggleEvery k = zipWith toggleK [1 ..]
where
toggleK n door
| n `mod` k == 0 = toggle door
| otherwise = door
run :: Int -> [Door]
run n = foldr toggleEvery (replicate n Closed) [1 .. n]
main :: IO ()
main = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Pascal | Pascal |
Program ArrayDemo;
uses
SysUtils;
var
StaticArray: array[0..9] of Integer;
DynamicArray: array of Integer;
StaticArrayText,
DynamicArrayText: string;
lcv: Integer;
begin
// Setting the length of the dynamic array the same as the static one
SetLength(DynamicArray, Length(StaticArray));
// Asking random numbers storing into the static array
for lcv := 0 to Pred(Length(StaticArray)) do
begin
write('Enter a integer random number for position ', Succ(lcv), ': ');
readln(StaticArray[lcv]);
end;
// Storing entered numbers of the static array in reverse order into the dynamic
for lcv := 0 to Pred(Length(StaticArray)) do
DynamicArray[Pred(Length(DynamicArray)) - lcv] := StaticArray[lcv];
// Concatenating the static and dynamic array into a single string variable
StaticArrayText := '';
DynamicArrayText := '';
for lcv := 0 to Pred(Length(StaticArray)) do
begin
StaticArrayText := StaticArrayText + IntToStr(StaticArray[lcv]) + ' ';
DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]) + ' ';
end;
// Displaying both arrays
writeln(StaticArrayText);
writeln(DynamicArrayText);
end.
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Tailspin | Tailspin |
// YCombinator is not needed since tailspin supports recursion readily, but this demonstrates passing functions as parameters
templates combinator&{stepper:}
templates makeStep&{rec:}
$ -> stepper&{next: rec&{rec: rec}} !
end makeStep
$ -> makeStep&{rec: makeStep} !
end combinator
templates factorial
templates seed&{next:}
<=0> 1 !
<>
$ * ($ - 1 -> next) !
end seed
$ -> combinator&{stepper: seed} !
end factorial
5 -> factorial -> 'factorial 5: $;
' -> !OUT::write
templates fibonacci
templates seed&{next:}
<..1> $ !
<>
($ - 2 -> next) + ($ - 1 -> next) !
end seed
$ -> combinator&{stepper: seed} !
end fibonacci
5 -> fibonacci -> 'fibonacci 5: $;
' -> !OUT::write
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Tcl | Tcl | ;; The Y combinator:
(defun y (f)
[(op @1 @1)
(op f (op [@@1 @@1]))])
;; The Y-combinator-based factorial:
(defun fac (f)
(do if (zerop @1)
1
(* @1 [f (- @1 1)])))
;; Test:
(format t "~s\n" [[y fac] 4]) |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #VBA | VBA |
Public Sub zigzag(n)
Dim a() As Integer
'populate a (1,1) to a(n,n) in zigzag pattern
'check if n too small
If n < 1 Then
Debug.Print "zigzag: enter a number greater than 1"
Exit Sub
End If
'initialize
ReDim a(1 To n, 1 To n)
i = 1 'i is the row
j = 1 'j is the column
P = 0 'P is the next number
a(i, j) = P 'fill in initial value
'now zigzag through the matrix and fill it in
Do While (i <= n) And (j <= n)
'move one position to the right or down the rightmost column, if possible
If j < n Then
j = j + 1
ElseIf i < n Then
i = i + 1
Else
Exit Do
End If
'fill in
P = P + 1: a(i, j) = P
'move down to the left
While (j > 1) And (i < n)
i = i + 1: j = j - 1
P = P + 1: a(i, j) = P
Wend
'move one position down or to the right in the bottom row, if possible
If i < n Then
i = i + 1
ElseIf j < n Then
j = j + 1
Else
Exit Do
End If
P = P + 1: a(i, j) = P
'move back up to the right
While (i > 1) And (j < n)
i = i - 1: j = j + 1
P = P + 1: a(i, j) = P
Wend
Loop
'print result
Debug.Print "Result for n="; n; ":"
For i = 1 To n
For j = 1 To n
Debug.Print a(i, j),
Next
Debug.Print
Next
End Sub
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #VBScript | VBScript | ZigZag(Cint(WScript.Arguments(0)))
Function ZigZag(n)
Dim arrZ()
ReDim arrZ(n-1,n-1)
i = 1
j = 1
For e = 0 To (n^2) - 1
arrZ(i-1,j-1) = e
If ((i + j ) And 1) = 0 Then
If j < n Then
j = j + 1
Else
i = i + 2
End If
If i > 1 Then
i = i - 1
End If
Else
If i < n Then
i = i + 1
Else
j = j + 2
End If
If j > 1 Then
j = j - 1
End If
End If
Next
For k = 0 To n-1
For l = 0 To n-1
WScript.StdOut.Write Right(" " & arrZ(k,l),3)
Next
WScript.StdOut.WriteLine
Next
End Function |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Haxe | Haxe | class RosettaDemo
{
static public function main()
{
findOpenLockers(100);
}
static function findOpenLockers(n : Int)
{
var i = 1;
while((i*i) <= n)
{
Sys.print(i*i + "\n");
i++;
}
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Perl | Perl | my @empty;
my @empty_too = ();
my @populated = ('This', 'That', 'And', 'The', 'Other');
print $populated[2]; # And
my $aref = ['This', 'That', 'And', 'The', 'Other'];
print $aref->[2]; # And
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #TXR | TXR | ;; The Y combinator:
(defun y (f)
[(op @1 @1)
(op f (op [@@1 @@1]))])
;; The Y-combinator-based factorial:
(defun fac (f)
(do if (zerop @1)
1
(* @1 [f (- @1 1)])))
;; Test:
(format t "~s\n" [[y fac] 4]) |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Ursala | Ursala | (r "f") "x" = "f"("f","x")
my_fix "h" = r ("f","x"). ("h" r "f") "x" |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Wren | Wren | import "/fmt" for Conv, Fmt
var zigzag = Fn.new { |n|
var r = List.filled(n*n, 0)
var i = 0
var n2 = n * 2
for (d in 1..n2) {
var x = d - n
if (x < 0) x = 0
var y = d - 1
if (y > n - 1) y = n - 1
var j = n2 - d
if (j > d) j = d
for (k in 0...j) {
if (d&1 == 0) {
r[(x+k)*n+y-k] = i
} else {
r[(y-k)*n+x+k] = i
}
i = i + 1
}
}
return r
}
var n = 5
var w = Conv.itoa(n*n - 1).count
var i = 0
for (e in zigzag.call(n)) {
Fmt.write("$*d ", w, e)
if (i%n == n - 1) System.print()
i = i + 1
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #HicEst | HicEst | REAL :: n=100, open=1, door(n)
door = 1 - open ! = closed
DO i = 1, n
DO j = i, n, i
door(j) = open - door(j)
ENDDO
ENDDO
DLG(Text=door, TItle=SUM(door)//" doors open") |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Phix | Phix | -- simple one-dimensional arrays:
sequence s1 = {0.5, 1, 4.7, 9}, -- length(s1) is now 4
s2 = repeat(0,6), -- s2 is {0,0,0,0,0,0}
s3 = tagset(5) -- s3 is {1,2,3,4,5}
?s1[3] -- displays 4.7 (nb 1-based indexing)
s1[3] = 0 -- replace that 4.7
s1 &= {5,6} -- length(s1) is now 6 ({0.5,1,0,9,5,6})
s1 = s1[2..5] -- length(s1) is now 4 ({1,0,9,5})
s1[2..3] = {2,3,4} -- length(s1) is now 5 ({1,2,3,4,5})
s1 = append(s1,6) -- length(s1) is now 6 ({1,2,3,4,5,6})
s1 = prepend(s1,0) -- length(s1) is now 7 ({0,1,2,3,4,5,6})
-- negative subscripts can also be used, counting from the other end, eg
s2[-2..-1] = {-2,-1} -- s2 is now {0,0,0,0,-2,-1}
-- multi dimensional arrays:
sequence y = {{{1,1},{3,3},{5,5}},
{{0,0},{0,1},{9,1}},
{{1,7},{1,1},{2,2}}}
-- y[2][3][1] is 9
y = repeat(repeat(repeat(0,2),3),3)
-- same structure, but all 0s
-- Array of strings:
sequence s = {"Hello", "World", "Phix", "", "Last One"}
-- s[3] is "Phix"
-- s[3][2] is 'h'
-- A Structure:
sequence employee = {{"John","Smith"},
45000,
27,
185.5}
-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:
constant SALARY = 2
-- Array of structures:
sequence employees = {
{{"Jane","Adams"}, 47000, 34, 135.5}, -- a[1]
{{"Bill","Jones"}, 57000, 48, 177.2}, -- a[2]
-- .... etc.
}
-- employees[2][SALARY] is 57000
-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:
sequence tree = {{"b",3,2},
{"c",0,0},
{"a",0,0}}
-- ie assuming
constant ROOT=1, VALUE=1, LEFT=2, RIGHT=3 -- then
-- tree[ROOT][VALUE] is "b"
-- tree[ROOT][LEFT] is 3, and tree[3] is the "a"
-- tree[ROOT][RIGHT] is 2, and tree[2] is the "c"
-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:
tree = {}
tree = append(tree,{"b",0,0})
tree = append(tree,{"c",0,0})
tree[1][RIGHT] = length(tree)
tree = append(tree,{"a",0,0})
tree[1][LEFT] = length(tree)
-- Finally, some tests (recall that we have already output a 4.7):
?s[3]
?tree
?tree[ROOT][VALUE]
employees = append(employees, employee)
?employees[3][SALARY]
?s1
?s2
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #VBA | VBA | Private Function call_fn(f As String, n As Long) As Long
call_fn = Application.Run(f, f, n)
End Function
Private Function Y(f As String) As String
Y = f
End Function
Private Function fac(self As String, n As Long) As Long
If n > 1 Then
fac = n * call_fn(self, n - 1)
Else
fac = 1
End If
End Function
Private Function fib(self As String, n As Long) As Long
If n > 1 Then
fib = call_fn(self, n - 1) + call_fn(self, n - 2)
Else
fib = n
End If
End Function
Private Sub test(name As String)
Dim f As String: f = Y(name)
Dim i As Long
Debug.Print name
For i = 1 To 10
Debug.Print call_fn(f, i);
Next i
Debug.Print
End Sub
Public Sub main()
test "fac"
test "fib"
End Sub |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #XPL0 | XPL0 | include c:\cxpl\codes;
def N=6;
int A(N,N), X, Y, I, D;
[I:=0; X:=0; Y:=0; D:=1;
repeat A(X,Y):=I;
case of
X+D>=N: [D:=-D; Y:=Y+1];
Y-D>=N: [D:=-D; X:=X+1];
X+D<0: [D:=-D; Y:=Y+1];
Y-D<0: [D:=-D; X:=X+1]
other [X:=X+D; Y:=Y-D];
I:=I+1;
until I>=N*N;
for Y:=0 to N-1 do
[for X:=0 to N-1 do
[I:=A(X,Y);
ChOut(0,^ );
if I<10 then ChOut(0,^ );
IntOut(0, I);
];
CrLf(0);
];
] |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #HolyC | HolyC | U8 is_open[100];
U8 pass = 0, door = 0;
/* do the 100 passes */
for (pass = 0; pass < 100; ++pass)
for (door = pass; door < 100; door += pass + 1)
is_open[door] = !is_open[door];
/* output the result */
for (door = 0; door < 100; ++door)
if (is_open[door])
Print("Door #%d is open.\n", door + 1);
else
Print("Door #%d is closed.\n", door + 1);
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
0 tolist /# create an empty array/list. '( )' is equivalent #/
drop /# remove top of the stack #/
0 10 repeat /# put an array/list of 10 elements (each element has value 0) to the stack #/
flush /# remove all elements. List is empty [] #/
drop
( 1 2 "Hello" pi ) /# put an initialize array/list to stack #/
-7 1 set /# modified first element to -7 #/
0 get /# get the last element. '-1 get' is equivalent #/
drop
( "next" "level" ) 2 put /# insert a list in a list = [-7, ["next", "level"], 2, "Hello", 3.141592653589793]] #/
3 2 slice /# extract the subarray/sublist [ 2 "Hello" ] #/
pstack /# show the content of the stack #/ |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Verbexx | Verbexx | /////// Y-combinator function (for single-argument lambdas) ///////
y @FN [f]
{ @( x -> { @f (z -> {@(@x x) z}) } ) // output of this expression is treated as a verb, due to outer @( )
( x -> { @f (z -> {@(@x x) z}) } ) // this is the argument supplied to the above verb expression
};
/////// Function to generate an anonymous factorial function as the return value -- (not tail-recursive) ///////
fact_gen @FN [f]
{ n -> { (n<=0) ? {1} {n * (@f n-1)}
}
};
/////// Function to generate an anonymous fibonacci function as the return value -- (not tail-recursive) ///////
fib_gen @FN [f]
{ n -> { (n<=0) ? { 0 }
{ (n<=2) ? {1} { (@f n-1) + (@f n-2) } }
}
};
/////// loops to test the above functions ///////
@VAR factorial = @y fact_gen;
@VAR fibonacci = @y fib_gen;
@LOOP init:{@VAR i = -1} while:(i <= 20) next:{i++}
{ @SAY i "factorial =" (@factorial i) };
@LOOP init:{ i = -1} while:(i <= 16) next:{i++}
{ @SAY "fibonacci<" i "> =" (@fibonacci i) }; |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Yabasic | Yabasic | Size = 5
DIM array(Size-1, Size-1)
i = 1
j = 1
FOR e = 0 TO Size^2-1
array(i-1, j-1) = e
IF and((i + j), 1) = 0 THEN
IF j < Size then j = j + 1 ELSE i = i + 2 end if
IF i > 1 i = i - 1
ELSE
IF i < Size then i = i + 1 ELSE j = j + 2 end if
IF j > 1 j = j - 1
ENDIF
NEXT e
FOR row = 0 TO Size-1
FOR col = 0 TO Size-1
PRINT array(row,col) USING "##";
NEXT col
PRINT
NEXT row |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Hoon | Hoon | |^
=/ doors=(list ?) (reap 100 %.n)
=/ passes=(list (list ?)) (turn (gulf 1 100) pass-n)
|-
?~ passes doors
$(doors (toggle doors i.passes), passes t.passes)
++ pass-n
|= n=@ud
(turn (gulf 1 100) |=(k=@ud =((mod k n) 0)))
++ toggle
|= [a=(list ?) b=(list ?)]
=| c=(list ?)
|-
?: |(?=(~ a) ?=(~ b)) (flop c)
$(a t.a, b t.b, c [=((mix i.a i.b) 1) c])
-- |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PHP | PHP | $NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array("a", "b", "c", "d", "e", "f");
$simpleForm = ['apple', 'orange']; |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Vim_Script | Vim Script | " Translated from Python. Works with: Vim 7.0
func! Lambx(sig, expr, dict)
let fanon = {'d': a:dict}
exec printf("
\func fanon.f(%s) dict\n
\ return %s\n
\endfunc",
\ a:sig, a:expr)
return fanon
endfunc
func! Callx(fanon, arglist)
return call(a:fanon.f, a:arglist, a:fanon.d)
endfunc
let g:Y = Lambx('f', 'Callx(Lambx("x", "Callx(a:x, [a:x])", {}), [Lambx("y", ''Callx(self.f, [Lambx("...", "Callx(Callx(self.y, [self.y]), a:000)", {"y": a:y})])'', {"f": a:f})])', {})
let g:fac = Lambx('f', 'Lambx("n", "a:n<2 ? 1 : a:n * Callx(self.f, [a:n-1])", {"f": a:f})', {})
echo Callx(Callx(g:Y, [g:fac]), [5])
echo map(range(10), 'Callx(Callx(Y, [fac]), [v:val])')
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #zkl | zkl | fcn zz(n){
grid := (0).pump(n,List, (0).pump(n,List).copy).copy();
ri := Ref(0);
foreach d in ([1..n*2]){
x:=(0).max(d - n); y:=(n - 1).min(d - 1);
(0).pump(d.min(n*2 - d),Void,'wrap(it){
grid[if(d%2)y-it else x+it][if(d%2)x+it else y-it] = ri.inc();
});
}
grid.pump(String,'wrap(r){("%3s"*n+"\n").fmt(r.xplode())});
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Huginn | Huginn | #! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn
import Algorithms as algo;
main() {
doorCount = 100;
doors = [].resize( doorCount, false );
for ( pass : algo.range( doorCount ) ) {
i = 0;
step = pass + 1;
while ( i < doorCount ) {
doors[i] = ! doors[i];
i += step;
}
}
for ( i : algo.range( doorCount ) ) {
if ( doors[i] ) {
print( "door {} is open\n".format( i ) );
}
}
return ( 0 );
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Picat | Picat | import util.
go =>
% Create an array of length 10
Len = 10,
A = new_array(Len),
bind_vars(A,0), % Initialize all values to 0
println(a=A),
A[1] := 1, % Assign a value
println(a=A),
println(a1=A[1]), % print first element
% (re)assign a value
foreach(I in 1..Len) A[I] := I end,
println(A[3..7]), % print some interval of an array
nl,
% 2D arrays
A2 = new_array(4,4),
foreach(I in 1..4, J in 1..4)
A2[I,J] := (I-1)*4+J
end,
foreach(Row in A2) println(Row) end,
% These functions are defined in the util module.
% They returns lists so we have to convert them to arrays.
println('rows '=to_array(A2.rows)),
println('columns '=A2.columns.to_array),
println(diagonal1=A2.diagonal1.to_array),
println(diagonal2=A2.diagonal2.to_array),
nl,
% Pushing values to an array
A3 = {}, % an empty array
foreach(I in 1..4)
A3 := A3 ++ {10**I+I}
end,
println(a3=A3),
nl,
% Some misc functions
println([first=A3.first(), second=A3.second(),last=A3.last()]),
nl.
|
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Wart | Wart | # Better names due to Jim Weirich: http://vimeo.com/45140590
def (Y improver)
((fn(gen) gen.gen)
(fn(gen)
(fn(n)
((improver gen.gen) n))))
factorial <- (Y (fn(f)
(fn(n)
(if zero?.n
1
(n * (f n-1))))))
prn factorial.5 |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Hy | Hy | (setv doors (* [False] 100))
(for [pass (range (len doors))]
(for [i (range pass (len doors) (inc pass))]
(assoc doors i (not (get doors i)))))
(for [i (range (len doors))]
(print (.format "Door {} is {}."
(inc i)
(if (get doors i) "open" "closed")))) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PicoLisp | PicoLisp | (setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
(mapc println A) # Show it |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Wren | Wren | var y = Fn.new { |f|
var g = Fn.new { |r| f.call { |x| r.call(r).call(x) } }
return g.call(g)
}
var almostFac = Fn.new { |f| Fn.new { |x| x <= 1 ? 1 : x * f.call(x-1) } }
var almostFib = Fn.new { |f| Fn.new { |x| x <= 2 ? 1 : f.call(x-1) + f.call(x-2) } }
var fac = y.call(almostFac)
var fib = y.call(almostFib)
System.print("fac(10) = %(fac.call(10))")
System.print("fib(10) = %(fib.call(10))") |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #I | I | software {
var doors = len(100)
for pass over [1, 100]
var door = pass - 1
loop door < len(doors) {
doors[door] = doors[door]/0
door += pass
}
end
for door,isopen in doors
if isopen
print("Door ",door+1,": open")
end
end
print("All other doors are closed")
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Pike | Pike | int main(){
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
arr += ({"adding","to","the","array"}); // Lets add some elements.
write(arr[5] + "\n"); // And finally print element 5.
} |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #XQuery | XQuery | let $Y := function($f) {
(function($x) { ($x)($x) })( function($g) { $f( (function($a) { $g($g) ($a)}) ) } )
}
let $fac := $Y(function($f) { function($n) { if($n < 2) then 1 else $n * $f($n - 1) } })
let $fib := $Y(function($f) { function($n) { if($n <= 1) then $n else $f($n - 1) + $f($n - 2) } })
return (
$fac(6),
$fib(6)
)
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Icon_and_Unicon | Icon and Unicon |
procedure main()
door := table(0) # default value of entries is 0
every pass := 1 to 100 do
every door[i := pass to 100 by pass] := 1 - door[i]
every write("Door ", i := 1 to 100, " is ", if door[i] = 1 then "open" else "closed")
end
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #11l | 11l | :start:
I :argv.len != 5
print(‘Usage : #. < Followed by level, id, source string and description>’.format(:argv[0]))
E
os:(‘EventCreate /t #. /id #. /l APPLICATION /so #. /d "#."’.format(:argv[1], :argv[2], :argv[3], :argv[4])) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PL.2FI | PL/I | /* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);
A(6) = -45;
/* Example of an array having dynamic bounds. */
get list (N);
begin;
declare B(N) float initial (9, 4, 7, 3, 8, 11, 0, 5, 15, 6);
B(3) = -11;
put (B(2));
end;
/* Example of a dynamic array. */
declare C(N) float controlled;
get list (N);
allocate C;
C = 0;
c(7) = 12;
put (C(9)); |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #Yabasic | Yabasic | sub fac(self$, n)
if n > 1 then
return n * execute(self$, self$, n - 1)
else
return 1
end if
end sub
sub fib(self$, n)
if n > 1 then
return execute(self$, self$, n - 1) + execute(self$, self$, n - 2)
else
return n
end if
end sub
sub test(name$)
local i
print name$, ": ";
for i = 1 to 10
print execute(name$, name$, i);
next
print
end sub
test("fac")
test("fib") |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Idris | Idris | import Data.Vect
-- Creates list from 0 to n (not including n)
upTo : (m : Nat) -> Vect m (Fin m)
upTo Z = []
upTo (S n) = 0 :: (map FS (upTo n))
data DoorState = DoorOpen | DoorClosed
toggleDoor : DoorState -> DoorState
toggleDoor DoorOpen = DoorClosed
toggleDoor DoorClosed = DoorOpen
isOpen : DoorState -> Bool
isOpen DoorOpen = True
isOpen DoorClosed = False
initialDoors : Vect 100 DoorState
initialDoors = fromList $ map (\_ => DoorClosed) [1..100]
iterate : (n : Fin m) -> Vect m DoorState -> Vect m DoorState
iterate n doors {m} =
map (\(idx, doorState) =>
if ((S (finToNat idx)) `mod` (S (finToNat n))) == Z
then toggleDoor doorState
else doorState)
(zip (upTo m) doors)
-- Returns all doors left open at the end
solveDoors : List (Fin 100)
solveDoors =
findIndices isOpen $ foldl (\doors,val => iterate val doors) initialDoors (upTo 100)
main : IO ()
main = print $ map (\n => S (finToNat n)) solveDoors |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #AutoHotkey | AutoHotkey | ; By ABCza, http://www.autohotkey.com/board/topic/76170-function-send-windows-log-events/
h := RegisterForEvents("AutoHotkey")
SendWinLogEvent(h, "Test Message")
DeregisterForEvents(h)
/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: SendWinLogEvent
--------------------------------------------------------------------------------------------------------------------------------
Writes an entry at the end of the specified Windows event log. Returns nonzero if the function succeeds or zero if it fails.
PARAMETERS:
~~~~~~~~~~~
hSource - Handle to a previously registered events source with RegisterForEvents.
evType - EVENTLOG_SUCCESS := 0x0000
EVENTLOG_AUDIT_FAILURE := 0x0010
EVENTLOG_AUDIT_SUCCESS := 0x0008
EVENTLOG_ERROR_TYPE := 0x0001
EVENTLOG_INFORMATION_TYPE := 0x0004
EVENTLOG_WARNING_TYPE := 0x0002
evId - Event ID, can be any dword value.
evCat - Any value, used to organize events in categories.
pStrings - A continuation section with newline separated strings (each max 31839 chars).
pData - A buffer containing the binary data.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
ReportEvent - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
Event Identifiers - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363651(v=vs.85).aspx
Event categories - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363649(v=vs.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
SendWinLogEvent(hSource, String="", evType=0x0004, evId=0x03EA, evCat=0, pData=0) {
Ptr := A_PtrSize ? "Ptr" : "UInt"
LPCtSTRs := A_PtrSize ? "Ptr*" : "UInt"
StringPut := A_IsUnicode ? "StrPut" : "StrPut2"
; Reserve and initialise space for the event message.
VarSetCapacity(eventMessage, StrLen(String), 0)
%StringPut%(String, &eventMessage, A_IsUnicode ? "UTF-16" : "")
r := DllCall("Advapi32.dll\ReportEvent" (A_IsUnicode ? "W" : "A")
, UInt, hSource ; handle
, UShort, evType ; WORD, eventlog_information_type
, UShort, evCat ; WORD, category
, UInt, evId ; DWORD, event ID, 0x03EA
, Ptr, 0 ; PSID, ptr to user security ID
, UShort, 1 ; WORD, number of strings
, UInt, VarSetCapacity(pData) ; DWORD, data size
, LPCtSTRs, &eventMessage ; LPCTSTR*, ptr to a buffer ...
, Ptr, (VarSetCapacity(pData)) ? &pData : 0 ) ; ptr to a buffer of binary data
; Release memory.
VarSetCapacity(eventMessage, 0)
Return r
}
/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: RegisterForEvents
--------------------------------------------------------------------------------------------------------------------------------
Registers the application to send Windows log events. Returns a handle to the registered source.
PARAMETERS:
~~~~~~~~~~~
logName - Can be "Application", "System" or a custom log name.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
RegisterEventSource - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363678(v=VS.85).aspx
Event Sources - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
RegisterForEvents(logName) {
Return DllCall("Advapi32.dll\RegisterEventSource" (A_IsUnicode ? "W" : "A")
, UInt, 0 ; LPCTSTR, Local computer
, Str, logName) ; LPCTSTR Source name
}
/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: DeregisterForEvents
--------------------------------------------------------------------------------------------------------------------------------
Deregisters the previously registered application.
PARAMETERS:
~~~~~~~~~~~
hSource - Handle to a registered source.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
DeregisterEventSource - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363642(v=vs.85).aspx
Event Sources - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
DeregisterForEvents(hSource) {
IfNotEqual, hSource, 0, Return DllCall( "Advapi32.dll\DeregisterEventSource"
, UInt, hSource )
}
; StrPut for AutoHotkey Basic
StrPut2(String, Address="", Length=-1, Encoding=0)
{
; Flexible parameter handling:
if Address is not integer ; StrPut(String [, Encoding])
Encoding := Address, Length := 0, Address := 1024
else if Length is not integer ; StrPut(String, Address, Encoding)
Encoding := Length, Length := -1
; Check for obvious errors.
if (Address+0 < 1024)
return
; Ensure 'Encoding' contains a numeric identifier.
if Encoding = UTF-16
Encoding = 1200
else if Encoding = UTF-8
Encoding = 65001
else if SubStr(Encoding,1,2)="CP"
Encoding := SubStr(Encoding,3)
if !Encoding ; "" or 0
{
; No conversion required.
char_count := StrLen(String) + 1 ; + 1 because generally a null-terminator is wanted.
if (Length)
{
; Check for sufficient buffer space.
if (StrLen(String) <= Length || Length == -1)
{
if (StrLen(String) == Length)
; Exceptional case: caller doesn't want a null-terminator.
char_count--
; Copy the string, including null-terminator if requested.
DllCall("RtlMoveMemory", "uint", Address, "uint", &String, "uint", char_count)
}
else
; For consistency with the sections below, don't truncate the string.
char_count = 0
}
;else: Caller just wants the the required buffer size (char_count), which will be returned below.
}
else if Encoding = 1200 ; UTF-16
{
; See the 'else' to this 'if' below for comments.
if (Length <= 0)
{
char_count := DllCall("MultiByteToWideChar", "uint", 0, "uint", 0, "uint", &String, "int", StrLen(String), "uint", 0, "int", 0) + 1
if (Length == 0)
return char_count
Length := char_count
}
char_count := DllCall("MultiByteToWideChar", "uint", 0, "uint", 0, "uint", &String, "int", StrLen(String), "uint", Address, "int", Length)
if (char_count && char_count < Length)
NumPut(0, Address+0, char_count++*2, "UShort")
}
else if Encoding is integer
{
; Convert native ANSI string to UTF-16 first. NOTE - wbuf_len includes the null-terminator.
VarSetCapacity(wbuf, 2 * wbuf_len := StrPut2(String, "UTF-16")), StrPut2(String, &wbuf, "UTF-16")
; UTF-8 and some other encodings do not support this flag. Avoid it for UTF-8
; (which is probably common) and rely on the fallback behaviour for other encodings.
flags := Encoding=65001 ? 0 : 0x400 ; WC_NO_BEST_FIT_CHARS
if (Length <= 0) ; -1 or 0
{
; Determine required buffer size.
loop 2 {
char_count := DllCall("WideCharToMultiByte", "uint", Encoding, "uint", flags, "uint", &wbuf, "int", wbuf_len, "uint", 0, "int", 0, "uint", 0, "uint", 0)
if (char_count || A_LastError != 1004) ; ERROR_INVALID_FLAGS
break
flags := 0 ; Try again without WC_NO_BEST_FIT_CHARS.
}
if (!char_count)
return ; FAIL
if (Length == 0) ; Caller just wants the required buffer size.
return char_count
; Assume there is sufficient buffer space and hope for the best:
Length := char_count
}
; Convert to target encoding.
char_count := DllCall("WideCharToMultiByte", "uint", Encoding, "uint", flags, "uint", &wbuf, "int", wbuf_len, "uint", Address, "int", Length, "uint", 0, "uint", 0)
; Since above did not null-terminate, check for buffer space and null-terminate if there's room.
; It is tempting to always null-terminate (potentially replacing the last byte of data),
; but that would exclude this function as a means to copy a string into a fixed-length array.
if (char_count && char_count < Length)
NumPut(0, Address+0, char_count++, "Char")
; else no space to null-terminate; or conversion failed.
}
; Return the number of characters copied.
return char_count
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Plain_English | Plain English | To run:
Start up.
Write "Creating an array of 100 numbers..." on the console.
Create a number array given 100.
Write "Putting 1 into the array at index 0." on the console.
Put 1 into the number array at 0.
Write "Putting 33 into the array at index 50." on the console.
Put 33 into the number array at 50.
Write "Retrieving value from array at index 0... " on the console without advancing.
Get a number from the number array at 0.
Write "" then the number on the console.
Write "Retrieving value from array at index 50... " on the console without advancing.
Get another number from the number array at 50.
Write "" then the other number on the console.
Write "Retrieving value from array at index 99... " on the console without advancing.
Get a third number from the number array at 99.
Write "" then the third number on the console.
Destroy the number array.
Wait for the escape key.
Shut down.
\\\\\\\\\\\\\\\\\\ Array implementation \\\\\\\\\\\\\\\\\\\\
A number array has a first element pointer.
A location is a number.
To create a number array given a count:
Put a number's magnitude times the count into a size.
Assign the number array's first element pointer given the size. \ allocate memory for the array
To destroy a number array:
Unassign the number array's first element pointer. \ free the array's memory
To get a number from a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number pointer's target into the number.
To put a number into a number array at a location:
Put the location times the number's magnitude into an offset.
Put the number array's first element pointer into a number pointer.
Add the offset to the number pointer.
Put the number into the number pointer's target. |
http://rosettacode.org/wiki/Y_combinator | Y combinator | In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.
This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.
The Y combinator is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.
The Y combinator is the simplest of the class of such functions, called fixed-point combinators.
Task
Define the stateless Y combinator and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.
Cf
Jim Weirich: Adventures in Functional Programming
| #zkl | zkl | fcn Y(f){ fcn(g){ g(g) }( 'wrap(h){ f( 'wrap(a){ h(h)(a) }) }) } |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Inform_7 | Inform 7 | Hallway is a room.
A toggle door is a kind of thing.
A toggle door can be open or closed. It is usually closed.
A toggle door has a number called the door number.
Understand the door number property as referring to a toggle door.
Rule for printing the name of a toggle door: say "door #[door number]".
There are 100 toggle doors.
When play begins (this is the initialize doors rule):
let the next door number be 1;
repeat with D running through toggle doors:
now the door number of D is the next door number;
increment the next door number.
To toggle (D - open toggle door): now D is closed.
To toggle (D - closed toggle door): now D is open.
When play begins (this is the solve puzzle rule):
let the door list be the list of toggle doors;
let the door count be the number of entries in the door list;
repeat with iteration running from 1 to 100:
let N be the iteration;
while N is less than the door count:
toggle entry N in the door list;
increase N by the iteration;
say "Doors left open: [list of open toggle doors].";
end the story. |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #AWK | AWK |
# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK
BEGIN {
write("INFORMATION",1,"Rosetta Code")
exit (errors == 0) ? 0 : 1
}
function write(type,id,description, cmd,esf) {
esf = errors # errors so far
cmd = sprintf("EVENTCREATE.EXE /T %s /ID %d /D \"%s\" >NUL",type,id,description)
printf("%s\n",cmd)
if (toupper(type) !~ /^(SUCCESS|ERROR|WARNING|INFORMATION)$/) { error("/T is invalid") }
if (id+0 < 1 || id+0 > 1000) { error("/ID is invalid") }
if (description == "") { error("/D is invalid") }
if (errors == esf) {
system(cmd)
}
return(errors)
}
function error(message) { printf("error: %s\n",message) ; errors++ }
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Batch_File | Batch File | @echo off
EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log."
EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log" |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Pony | Pony | use "assert" // due to the use of Fact
- - -
var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements
numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed
try
let x = numbers(0) // fetch the first element of array. index starts at 0
Fact(x == 10) // try block is needed, because both lines inside it can throw exception
end
var other: Array[U64] = [10, 20, 30] // array literal
let s = other.size() // return the number of elements in array
try
Fact(s == 3) // size of array 'other' is 3
other(1) = 40 // 'other' now is [10, 40, 30]
end |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Informix_4GL | Informix 4GL |
MAIN
DEFINE
i, pass SMALLINT,
doors ARRAY[100] OF SMALLINT
FOR i = 1 TO 100
LET doors[i] = FALSE
END FOR
FOR pass = 1 TO 100
FOR i = pass TO 100 STEP pass
LET doors[i] = NOT doors[i]
END FOR
END FOR
FOR i = 1 TO 100
IF doors[i]
THEN DISPLAY i USING "Door <<& is open"
ELSE DISPLAY i USING "Door <<& is closed"
END IF
END FOR
END MAIN
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"COMLIB"
PROC_cominitlcid(1033)
WshShell% = FN_createobject("WScript.Shell")
PROC_callmethod(WshShell%, "LogEvent(0, ""Test from BBC BASIC"")")
PROC_releaseobject(WshShell%)
PROC_comexit |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #C | C |
#include<stdlib.h>
#include<stdio.h>
int main(int argC,char* argV[])
{
char str[1000];
if(argC!=5)
printf("Usage : %s < Followed by level, id, source string and description>",argV[0]);
else{
sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]);
system(str);
}
return 0;
}
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PostScript | PostScript |
%Declaring array
/x [0 1] def
%Assigning value to an element, PostScript arrays are 0 based.
x 0 3 put
%Print array
x pstack
[3 1]
%Get an element
x 1 get
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Io | Io | doors := List clone
100 repeat(doors append(false))
for(i,1,100,
for(x,i,100, i, doors atPut(x - 1, doors at(x - 1) not))
)
doors foreach(i, x, if(x, "Door #{i + 1} is open" interpolate println)) |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #C.23 | C# | using System.Diagnostics;
namespace RC
{
internal class Program
{
public static void Main()
{
string sSource = "Sample App";
string sLog = "Application";
string sEvent = "Hello from RC!";
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);
}
}
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #C.2B.2B | C++ | #include <iostream>
#include <sstream>
int main(int argc, char *argv[]) {
using namespace std;
#if _WIN32
if (argc != 5) {
cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n";
cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n";
} else {
stringstream ss;
ss << "EventCreate /t " << argv[1] << " /id " << argv[2] << " /l APPLICATION /so " << argv[3] << " /d \"" << argv[4] << "\"";
system(ss.str().c_str());
}
#else
cout << "Not implemented for *nix, only windows.\n";
#endif
return 0;
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PowerShell | PowerShell | $a = @() |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Ioke | Ioke | NDoors = Origin mimic
NDoors Toggle = Origin mimic do(
initialize = method(toggled?, @toggled? = toggled?)
toggle! = method(@toggled? = !toggled?. self)
)
NDoors Doors = Origin mimic do(
initialize = method(n,
@n = n
@doors = {} addKeysAndValues(1..n, (1..n) map(_, NDoors Toggle mimic(false)))
)
numsToToggle = method(n, for(x <- (1..@n), (x % n) zero?, x))
toggleThese = method(nums, nums each(x, @doors[x] = @doors at(x) toggle))
show = method(@doors filter:dict(value toggled?) keys sort println)
)
; Test code
x = NDoors Doors mimic(100)
(1..100) each(n, x toggleThese(x numsToToggle(n)))
x show |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Clojure | Clojure | (use 'clojure.java.shell)
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example") |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #D | D | import std.process;
import std.stdio;
void main() {
auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`);
if (cmd.status == 0) {
writeln("Output: ", cmd.output);
} else {
writeln("Failed to execute command, status=", cmd.status);
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Prolog | Prolog |
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
% index of arguments start at 1
arg(1 ,Array,a), % put an a at position 1
arg(12,Array,b), % put an b at position 12
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl, % will print Value1 and therefore a followed by a newline
arg(4 ,Array,Value2), % get the value at position 4 which is a free Variable
print(Value2),nl. % will print that it is a free Variable followed by a newline
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Isabelle | Isabelle | theory Scratch
imports Main
begin
section‹100 Doors›
datatype doorstate = Open | Closed
fun toggle :: "doorstate ⇒ doorstate" where
"toggle Open = Closed"
| "toggle Closed = Open"
fun walk :: "('a ⇒ 'a) ⇒ nat ⇒ nat ⇒ 'a list ⇒ 'a list" where
"walk f _ _ [] = []"
| "walk f every 0 (x#xs) = (f x) # walk f every every xs"
| "walk f every (Suc n) (x#xs) = x # walk f every n xs"
text‹Example: \<^const>‹toggle› every second door. (second = 1, because of 0 indexing)›
lemma "walk toggle 1 1 [Open, Open, Open, Open, Open, Open] =
[Open, Closed, Open, Closed, Open, Closed]" by code_simp
text‹Example: \<^const>‹toggle› every third door.›
lemma "walk toggle 2 2 [Open, Open, Open, Open, Open, Open] =
[Open, Open, Closed, Open, Open, Closed]" by code_simp
text‹Walking each door is essentially the same as the common \<^const>‹map› function.›
lemma "walk f 0 0 xs = map f xs"
by(induction xs) (simp)+
lemma walk_beginning:
"walk f every n xs = (walk f every n (take (Suc n) xs)) @ (walk f every every (drop (Suc n) xs))"
by(induction f every n xs rule:walk.induct) (simp)+
text‹A convenience definition to take the off-by-one into account and setting the starting position.›
definition visit_every :: "('a ⇒ 'a) ⇒ nat ⇒ 'a list ⇒ 'a list" where
"visit_every f every xs ≡ walk f (every - 1) (every - 1) xs"
fun iterate :: "nat ⇒ (nat ⇒ 'a ⇒ 'a) ⇒ nat ⇒ 'a ⇒ 'a" where
"iterate 0 _ _ a = a"
| "iterate (Suc i) f n a = iterate i f (Suc n) (f n a)"
text‹The 100 doors problem.›
definition "onehundred_doors ≡ iterate 100 (visit_every toggle) 1 (replicate 100 Closed)"
lemma "onehundred_doors =
[Open, Closed, Closed, Open, Closed, Closed, Closed,
Closed, Open, Closed, Closed, Closed, Closed, Closed,
Closed, Open, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Open, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Open, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Open,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Open, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Open, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Closed, Closed, Closed, Closed, Closed, Closed,
Closed, Open]" by code_simp
text‹Filtering for the open doors, we get the same result as the Haskell implementation.›
lemma
"[(i, door) ← enumerate 1 onehundred_doors. door = Open] =
[(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]"
by code_simp
section‹Equivalence to Haskell Implementation›
text‹
We will now present an alternative implementation, which is similar to the Haskell implementation
on 🌐‹https://rosettacode.org/wiki/100_doors#Haskell›. We will prove, that the two behave the same;
in general, not just for a fixed set of 100 doors.
›
definition map_every_start :: "('a ⇒ 'a) ⇒ nat ⇒ nat ⇒ 'a list ⇒ 'a list" where
"map_every_start f every start xs ≡
map (λ(i, x). if i mod every = 0 then f x else x) (enumerate start xs)"
definition visit_every_alt :: "('a ⇒ 'a) ⇒ nat ⇒ 'a list ⇒ 'a list" where
"visit_every_alt f every xs ≡ map_every_start f every 1 xs"
text‹Essentially, \<^term>‹start› and \<^term>‹start mod every› behave the same.›
lemma map_every_start_cycle:
"map_every_start f every (start + k*every) xs = map_every_start f every start xs"
proof(induction xs arbitrary: start)
case Nil
show "map_every_start f every (start + k * every) [] = map_every_start f every start []"
by(simp add: map_every_start_def)
next
case (Cons x xs)
from Cons.IH[of "Suc start"]
show "map_every_start f every (start + k * every) (x # xs) =
map_every_start f every start (x # xs)"
by(simp add: map_every_start_def)
qed
corollary map_every_start_cycle_zero:
"map_every_start f every every xs = map_every_start f every 0 xs"
using map_every_start_cycle[where k=1 and start=0, simplified] by blast
lemma map_every_start_fst_zero:
"map_every_start f every 0 (x # xs) = f x # map_every_start f every (Suc 0) xs"
by(simp add: map_every_start_def)
text‹
The first \<^term>‹n› elements are not processed by \<^term>‹f›,
as long as \<^term>‹n› is less than the \<^term>‹every› cycle.
›
lemma map_every_start_skip_first: "Suc n < every ⟹
map_every_start f every (every - (Suc n)) (x # xs) =
x # map_every_start f every (every - n) xs"
by(simp add: map_every_start_def Suc_diff_Suc)
lemma map_every_start_append:
"map_every_start f n s (ds1 @ ds2) =
map_every_start f n s ds1 @ map_every_start f n (s + length ds1) ds2"
by(simp add: map_every_start_def enumerate_append_eq)
text‹
The \<^const>‹walk› function and \<^const>‹map_every_start› behave the same,
as long as the starting \<^term>‹n› is less than the \<^term>‹every› cycle,
because \<^const>‹walk› allows pushing the start arbitrarily far and
\<^const>‹map_every_start› only allows deferring the start within
the \<^term>‹every› cycle.
This generalization is needed to strengthen the induction hypothesis
for the proof.
›
lemma walk_eq_map_every_start:
"n ≤ every ⟹ walk f every n xs = map_every_start f (Suc every) (Suc every - n) xs"
proof(induction xs arbitrary: n)
case Nil
show "walk f every n [] = map_every_start f (Suc every) (Suc every - n) []"
by(simp add: map_every_start_def)
next
case (Cons x xs)
then show "walk f every n (x # xs) = map_every_start f (Suc every) (Suc every - n) (x # xs)"
proof(cases n)
case 0
with Cons.IH show ?thesis
by(simp add: map_every_start_cycle_zero map_every_start_fst_zero)
next
case (Suc n2)
with Cons.prems map_every_start_skip_first[of n2 "Suc every"] have
"map_every_start f (Suc every) (Suc every - Suc n2) (x # xs) =
x # map_every_start f (Suc every) (Suc every - n2) xs"
by fastforce
with Suc Cons show ?thesis
by(simp)
qed
qed
corollary walk_eq_visit_every_alt:
"walk f every every xs = visit_every_alt f (Suc every) xs"
unfolding visit_every_alt_def
using walk_eq_map_every_start by fastforce
text‹
Despite their very different implementations, our alternative visit function behaves the same
as our original visit function.
Text the theorem includes \<^term>‹Suc every› to express that we exclude \<^term>‹every = 0›.
›
theorem visit_every_eq_visit_every_alt:
"visit_every f (Suc every) xs = visit_every_alt f (Suc every) xs"
unfolding visit_every_def
using walk_eq_visit_every_alt by fastforce
text‹Also, the \<^const>‹iterate› function we implemented above can be implemented by a simple \<^const>‹fold›.›
lemma fold_upt_helper: assumes n_geq_1: "Suc 0 ≤ n"
shows "fold f [Suc s..<n + s] (f s xs) = fold f [s..<n + s] xs"
proof -
from n_geq_1 have "[s..<n + s] = s#[Suc s..<n + s]" by (simp add: Suc_le_lessD upt_rec)
from this have "fold f [s..<n + s] xs = fold f (s#[Suc s..<n + s]) xs" by simp
also have "fold f (s#[Suc s..<n + s]) xs = fold f [Suc s..<n + s] (f s xs)" by(simp)
ultimately show ?thesis by simp
qed
theorem iterate_eq_fold: "iterate n f s xs = fold f [s ..< n+s] xs"
proof(induction n arbitrary: s xs)
case 0
then show "iterate 0 f s xs = fold f [s..<0 + s] xs" by simp
next
case (Suc n)
from Suc show "iterate (Suc n) f s xs = fold f [s..<Suc n + s] xs"
by(simp add: fold_upt_helper not_less_eq_eq)
qed
section‹Efficient Implementation›
text ‹
As noted on this page, the only doors that remain open are those whose numbers are perfect squares.
Yet, rosettacode does not want us to take this shortcut, since we want to compare implementations
across programming languages. But we can prove that our code computes the same result as reporting
all doors with a perfect square number as open:
›
theorem "[(i, door) ← enumerate 1 onehundred_doors. door = Open] =
[(i*i, Open). i ← [1..<11]]"
by code_simp
end |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Delphi | Delphi | program WriteToEventLog;
{$APPTYPE CONSOLE}
uses Windows;
procedure WriteLog(aMsg: string);
var
lHandle: THandle;
lMessagePtr: Pointer;
begin
lMessagePtr := PChar(aMsg);
lHandle := RegisterEventSource(nil, 'Logger');
if lHandle > 0 then
begin
try
ReportEvent(lHandle, 4 {Information}, 0, 0, nil, 1, 0, @lMessagePtr, nil);
finally
DeregisterEventSource(lHandle);
end;
end;
end;
begin
WriteLog('Message to log.');
end. |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #F.23 | F# | use log = new System.Diagnostics.EventLog()
log.Source <- "Sample Application"
log.WriteEntry("Entered something in the Application Eventlog!") |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #PureBasic | PureBasic | ;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
MyArray(0) = 7
MyArray(1) = 11
MyArray(7) = 23 |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #J | J | ~:/ (100 $ - {. 1:)"0 >:i.100
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...
~:/ 0=|/~ >:i.100 NB. alternative
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ... |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Go | Go | package main
import (
"fmt"
"os/exec"
)
func main() {
command := "EventCreate"
args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Go", "/D", "\"Rosetta Code Example\""}
cmd := exec.Command(command, args...)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Java | Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class WriteToWindowsEventLog {
public static void main(String[] args) throws IOException, InterruptedException {
String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
if (!osName.startsWith("WINDOWS")) {
System.err.println("Not windows");
return;
}
Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
process.waitFor(10, TimeUnit.SECONDS);
int exitValue = process.exitValue();
System.out.printf("Process exited with value %d\n", exitValue);
if (exitValue != 0) {
InputStream errorStream = process.getErrorStream();
String result = new BufferedReader(new InputStreamReader(errorStream))
.lines()
.collect(Collectors.joining("\n"));
System.err.println(result);
}
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Python | Python | array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0] |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Janet | Janet |
(def doors (seq [_ :range [0 100]] false))
(loop [pass :range [0 100]
door :range [pass 100 (inc pass)]]
(put doors door (not (doors door))))
(print "open doors: " ;(seq [i :range [0 100] :when (doors i)] (string (inc i) " ")))
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Julia | Julia |
cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\""
Base.run(`$cmd`)
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Kotlin | Kotlin | // version 1.1.4-3
fun main(args: Array<String>) {
val command = "EventCreate" +
" /t INFORMATION" +
" /id 123" +
" /l APPLICATION" +
" /so Kotlin" +
" /d \"Rosetta Code Example\""
Runtime.getRuntime().exec(command)
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Lingo | Lingo | shell = xtra("Shell").new()
props = [:]
props["operation"] = "runas"
props["parameters"] = "/t INFORMATION /id 123 /l APPLICATION /so Lingo /d ""E&"Rosetta Code Example""E
shell.shell_exec("EventCreate", props) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #QB64 | QB64 |
'Task
'Show basic array syntax in your language.
'Basically, create an array, assign a value to sit, and retrieve an element (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it).
Rem DECLARATION PART
Rem QB64/QuickBasic/Qbasic array examples
'-----------
MyArray%(10) = 11 ' it creates an array integer of 11 elements from 0 to 11
Dim MyArray2%(0 To 10) ' it is equal to the previous line of code, it is its explicit way
'--------------
Option Base 1 ' from here all arrays have as default as index of first item 1
MyArray3%(10) = 14 'it creates array from 1 to 14
Dim Myarray4%(1 To 14) ' it is equal to the 2 previous lines of code
'-----------------
Dim Shared myArray$(-12 To 12) ' it creates a string array with 25 elements and SHARED makes it global array
'---------------------
'$dynamic
Dim MyArray1!(1 To 4) ' these two lines of code create a resizable array
ReDim myArray2!(1 To 4) ' it does the same of the 2 previous lines of code
'-------------------------
' alternatively at the place of suffix ! or $ or % or # or &
' you can use the explicit way "DIM namearray (start to end) AS TypeOfVariable"
Dim MyIntegerArray(1 To 10) As Integer
Dim MyStringArray(1 To 10) As String
Dim MySingleArray(1 To 10) As Single
Dim MyLongArray(1 To 10) As Long
Dim MyDoubleArray(1 To 10) As Double
'---------------------------
'it is possible defining an User Data Type and creating an array with that type
Type MyType
Name As String * 8 ' a fixed lenght string variable
ID As Integer
Position As Single
End Type
Dim Lists(1 To 10) As MyType
ReDim WhoIs(-19 To 10) As MyType
'------------------------------
' Number of dimensions of an array: QuickBasic vs QB64
' an array can have from 1 to until 60 dimensions in QuickBasic
' an array can have from 1 to RAM dimension of your machine
' you must think that in the dayly practice is rare to use more than 3 dimensions
Dim Calendar%(1 To 31, 1 To 56, 1 To 12) ' array calendar with days, week, mounths
ReDim Time(1 To 60, 1 To 60, 1 To 24) As Integer ' array Time with seconds, minutes and hours
Rem ONLY QB64 arrays
'--------
' QB64 introduces more TypeOfVariable all of them associated to a suffix
' so you can declare also these kind of data
' _BIT or `, _BYTE or %%, _INTEGER64 or &&, _FLOAT or ##, OFFSET or %&, _MEM (no suffix)
Dim MyByteArray%%(1 To 4)
Dim MyByteArray2(1 To 4) As _Byte
' are the same declaration of the array
'----------------
'QB64 lets you to use an alternative way to declare variables and array
'using the following syntax: DIM / REDIM AS Type of data Array1, Array2, Array3"
ReDim As _MEM Mem1(1 To 5), Mem2(6 To 10)
Dim As _Unsigned _Byte UByte(-3 To 25), Ubyte2(100 To 200)
Rem QB64 / QB PDS (7.1) arrays
ReDim MyPreservedArray(1 To 5) As Integer ' it creates a dynamic array
ReDim _Preserve MyPreservedArray(-3 To 100) As Integer ' it changes limit of dimension of array
Rem ASSIGNING PART
' at declaration point each array is initializated: 0 for digit arrays, "" for string arrays
' in the UDT arrays each variable is initializated following its type
' all types of array can be accessed using the index of item choice to change
' in the UDT array each item of UDT is reached using the "." while the item of array needs the index
Print MyPreservedArray(2)
MyPreservedArray(2) = 12345
Print MyPreservedArray(2)
Print WhoIs(-10).Name
WhoIs(-10).Name = "QB64"
Print WhoIs(-10).Name
WhoIs(10).Name = WhoIs(-10).Name
Print WhoIs(10).Name
Rem RETRIEVE AN ELEMENT
' basically the coder must use a loop for scanning the whole array for that value choosen
'-----------------
' static array
MySingleArray(4) = 4
MySingleArray(8) = 8
For n = 1 To 10
If MySingleArray(n) > 0 Then Print MySingleArray(n)
Next
'dynamic array
WhoIs(-10).Name = "QB64"
WhoIs(10).Name = "C#"
WhoIs(1).Name = "Java"
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
ReDim _Preserve WhoIs(-10 To 19) As MyType
Print
Print WhoIs(-10).Name, WhoIs(10).Name, WhoIs(1).Name
Print WhoIs(-1).Name, WhoIs(19).Name, WhoIs(10).Name
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Java | Java | class HundredDoors {
public static void main(String[] args) {
boolean[] doors = new boolean[101];
for (int i = 1; i < doors.length; i++) {
for (int j = i; j < doors.length; j += i) {
doors[j] = !doors[j];
}
}
for (int i = 1; i < doors.length; i++) {
if (doors[i]) {
System.out.printf("Door %d is open.%n", i);
}
}
}
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Perl | Perl |
use strict;
use warnings;
use Win32::EventLog;
my $handle = Win32::EventLog->new("Application");
my $event = {
Computer => $ENV{COMPUTERNAME},
Source => 'Rosettacode',
EventType => EVENTLOG_INFORMATION_TYPE,
Category => 'test',
EventID => 0,
Data => 'a test for rosettacode',
Strings => 'a string test for rosettacode',
};
$handle->Report($event);
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Quackery | Quackery | Welcome to Quackery.
Enter "leave" to leave the shell.
Building extensions.
/O> ( nests are dynamic arrays, zero indexed from the left, -1 indexed from the right )
...
Stack empty.
/O> [] ( create an empty nest )
... 23 join 24 join ( append two numbers )
... ' [ 33 34 ] ( create a nest of two numbers )
... join ( concatenate them )
... ' [ 45 46 ] ( create a nest of two numbers )
... nested join ( add that nest as an item of the nest )
...
Stack: [ 23 24 33 34 [ 45 46 ] ]
/O> ' [ 55 56 ] ( create a nest of two numbers )
... swap 2 stuff ( insert it into the previous nest as the 2nd item )
...
Stack: [ 23 24 [ 55 56 ] 33 34 [ 45 46 ] ]
/O> -3 pluck drop ( remove the third item from the end and dispose of it )
...
Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ]
/O> dup 0 peek ( copy the first item )
...
Stack: [ 23 24 [ 55 56 ] 34 [ 45 46 ] ] 23
/O> swap -1 poke ( ... and overwrite the last item with it )
...
Stack: [ 23 24 [ 55 56 ] 34 23 ]
/O> behead join ( remove the first item and append it to the end )
...
Stack: [ 24 [ 55 56 ] 34 23 23 ]
/O> -2 split nip ( split it two items from the end and dispose of the left hand side )
...
Stack: [ 23 23 ]
/O> ' ** join ( append the exponentiation word )
...
Stack: [ 23 23 ** ]
/O> do ( ... and perform the nest as Quackery code. )
...
Stack: 20880467999847912034355032910567 |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #JavaScript | JavaScript | var doors=[];
for (var i=0;i<100;i++)
doors[i]=false;
for (var i=1;i<=100;i++)
for (var i2=i-1,g;i2<100;i2+=i)
doors[i2]=!doors[i2];
for (var i=1;i<=100;i++)
console.log("Door %d is %s",i,doors[i-1]?"open":"closed") |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Phix | Phix | requires(WINDOWS) -- (as in this will not work on Linux or p2js, duh)
without js -- (as above, also prevent pointless attempts to transpile)
system(`eventcreate /T INFORMATION /ID 123 /D "Rosetta Code Write to Windows event log task example"`)
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #PicoLisp | PicoLisp | : (call 'logger "This is a test")
-> T
: (call 'logger "This" 'is "another" 'test)
-> T |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #PowerShell | PowerShell | # Create Event Log object
$EventLog=new-object System.Diagnostics.EventLog("Application")
#Declare Event Source; must be 'registered' with Windows
$EventLog.Source="Application" # It is possible to register a new source (see Note2)
# Setup the Event Types; you don't have to use them all, but I'm including all the possibilities for reference
$infoEvent=[System.Diagnostics.EventLogEntryType]::Information
$errorEvent=[System.Diagnostics.EventLogEntryType]::Error
$warningEvent=[System.Diagnostics.EventLogEntryType]::Warning
$successAuditEvent=[System.Diagnostics.EventLogEntryType]::SuccessAudit
$failureAuditEvent=[System.Diagnostics.EventLogEntryType]::FailureAudit
# Write the event in the format "Event test",EventType,EventID
$EventLog.WriteEntry("My Test Event",$infoevent,70) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #R | R | arr <- array(1)
arr <- append(arr,3)
arr[1] <- 2
print(arr[1]) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #jq | jq | # Solution for n doors:
def doors(n):
def print:
. as $doors
| range(1; length+1)
| if $doors[.] then "Door \(.) is open" else empty end;
[range(n+1)|null] as $doors
| reduce range(1; n+1) as $run
( $doors; reduce range($run; n+1; $run ) as $door
( .; .[$door] = (.[$door] | not) ) )
| print ;
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #PureBasic | PureBasic | Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)
Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result
Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$)
If lLogAPIRetVal
lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata
DeregisterEventSource_(lLogAPIRetVal)
Result=#True
EndIf
ProcedureReturn Result
EndProcedure |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Python | Python | import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
applicationName = "My Application"
eventID = 1
category = 5 # Shell
myType = win32evtlog.EVENTLOG_WARNING_TYPE
descr = ["A warning", "An even more dire warning"]
data = "Application\0Data".encode("ascii")
win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,
eventType=myType, strings=descr, data=data, sid=my_sid) |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #11l | 11l | File(filename, ‘w’).write(string) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Racket | Racket | #lang racket
;; import dynamic arrays
(require data/gvector)
(define v (vector 1 2 3 4)) ; array
(vector-ref v 0) ; 1
(vector-set! v 1 4) ; 2 -> 4
(define gv (gvector 1 2 3 4)) ; dynamic array
(gvector-ref gv 0) ; 1
(gvector-add! gv 5) ; increase size
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Julia | Julia | doors = falses(100)
for a in 1:100, b in a:a:100
doors[b] = !doors[b]
end
for a = 1:100
println("Door $a is " * (doors[a] ? "open." : "closed."))
end |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Racket | Racket |
#lang racket
(log-warning "Warning: nothing went wrong.")
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Raku | Raku | given $*DISTRO {
when .is-win {
my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
run($cmd);
}
default { # most POSIX environments
use Log::Syslog::Native;
my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);
$logger.info("[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.");
}
} |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program writeFile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessErreur: .asciz "Error open file.\n"
szMessErreur1: .asciz "Error close file.\n"
szMessErreur2: .asciz "Error write file.\n"
szMessWriteOK: .asciz "String write in file OK.\n"
szParamNom: .asciz "./fic1.txt" // file name
sZoneEcrit: .ascii "(Over)write a file so that it contains a string."
.equ LGZONEECRIT, . - sZoneEcrit
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
// file open
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszParamNom // filename
mov x2,O_CREAT|O_WRONLY // flags
ldr x3,oficmask1 // mode
mov x8,OPEN // Linux call system
svc 0 //
cmp x0,0 // error ?
ble erreur // yes
mov x28,x0 // save File Descriptor
// x0 = FD
ldr x1,qAdrsZoneEcrit // write string address
mov x2,LGZONEECRIT // string size
mov x8,WRITE // Linux call system
svc 0
cmp x0,0 // error ?
ble erreur2 // yes
// close file
mov x0,x28 // File Descriptor
mov x8,CLOSE // Linuc call system
svc 0
cmp x0,0 // error ?
blt erreur1
ldr x0,qAdrszMessWriteOK
bl affichageMess
mov x0,#0 // return code OK
b 100f
erreur:
ldr x1,qAdrszMessErreur
bl affichageMess // display error message
mov x0,#1
b 100f
erreur1:
ldr x1,qAdrszMessErreur1 // x0 <- adresse chaine
bl affichageMess // display error message
mov x0,#1 // return code error
b 100f
erreur2:
ldr x0,qAdrszMessErreur2
bl affichageMess // display error message
mov x0,#1 // return code error
b 100f
100: // program end
mov x8,EXIT
svc #0
qAdrszParamNom: .quad szParamNom
qAdrszMessErreur: .quad szMessErreur
qAdrszMessErreur1: .quad szMessErreur1
qAdrszMessErreur2: .quad szMessErreur2
qAdrszMessWriteOK: .quad szMessWriteOK
qAdrsZoneEcrit: .quad sZoneEcrit
oficmask1: .quad 0644 // this zone is Octal number (0 before)
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Action.21 | Action! | proc MAIN()
open (1,"D:FILE.TXT",8,0)
printde(1,"My string")
close(1)
return
|
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Write_Whole_File is
File_Name : constant String := "the_file.txt";
F : File_Type;
begin
begin
Open (F, Mode => Out_File, Name => File_Name);
exception
when Name_Error => Create (F, Mode => Out_File, Name => File_Name);
end;
Put (F, "(Over)write a file so that it contains a string. " &
"The reverse of Read entire file—for when you want to update or " &
"create a file which you would read in its entirety all at once.");
Close (F);
end Write_Whole_File;
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Raku | Raku | my @arr;
push @arr, 1;
push @arr, 3;
@arr[0] = 2;
say @arr[0]; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #K | K | `closed `open ![ ; 2 ] @ #:' 1 _ = ,/ &:' 0 = t !\:/: t : ! 101 |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #REXX | REXX | /*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */
eCMD = 'EVENTCREATE' /*name of the command that'll be used. */
type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */
id = 234 /*in range: 1 ───► 1000 (inclusive).*/
logName = 'APPLICATION' /*information about what this is. */
source = 'REXX' /* " " who's doing this. */
desc = 'attempting to add an entry for a Rosetta Code demonstration.'
desc = '"' || desc || '"' /*enclose description in double quotes.*/
eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Ruby | Ruby | require 'win32/eventlog'
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry") |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Rust | Rust |
#[cfg(windows)]
mod bindings {
::windows::include_bindings!();
}
#[cfg(windows)]
use bindings::{
Windows::Win32::Security::{
GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,
TOKEN_USER,
},
Windows::Win32::SystemServices::{
GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,
},
};
#[cfg(windows)]
fn main() -> windows::Result<()> {
let ph = unsafe { GetCurrentProcess() };
let mut th: HANDLE = HANDLE(0);
unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?;
// Determine the required buffer size, ignore ERROR_INSUFFICIENT_BUFFER
let mut length = 0_u32;
unsafe {
GetTokenInformation(
th,
TOKEN_INFORMATION_CLASS::TokenUser,
std::ptr::null_mut(),
0,
&mut length,
)
}
.ok()
.unwrap_err();
// Retrieve the user token.
let mut token_user_bytes = vec![0u8; length as usize];
unsafe {
GetTokenInformation(
th,
TOKEN_INFORMATION_CLASS::TokenUser,
token_user_bytes.as_mut_ptr().cast(),
length,
&mut length,
)
}
.ok()?;
// Extract the pointer to the user SID.
let user_sid: PSID = unsafe { (*token_user_bytes.as_ptr().cast::<TOKEN_USER>()).User.Sid };
// use the Application event log
let event_log_handle = unsafe { OpenEventLogA(PSTR::default(), "Application") };
let mut event_msg = PSTR(b"Hello in the event log\0".as_ptr() as _);
unsafe {
ReportEventA(
HANDLE(event_log_handle.0), //h_event_log: T0__,
ReportEvent_wType::EVENTLOG_WARNING_TYPE, // for type use EVENTLOG_WARNING_TYPE w_type: u16,
5, // for category use "Shell" w_category: u16,
1, // for ID use 1 dw_event_id: u32,
user_sid, // lp_user_sid: *mut c_void,
1, // w_num_strings: u16,
0, // dw_data_size: u32,
&mut event_msg, // lp_strings: *mut PSTR,
std::ptr::null_mut(), // lp_raw_data: *mut c_void,
)
}
.ok()?;
Ok(())
}
#[cfg(not(windows))]
fn main() {
println!("Not implemented");
}
|
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #ALGOL_68 | ALGOL 68 | IF FILE output;
STRING output file name = "output.txt";
open( output, output file name, stand out channel ) = 0
THEN
# file opened OK #
put( output, ( "line 1", newline, "line 2", newline ) );
close( output )
ELSE
# unable to open the output file #
print( ( "Cannot open ", output file name, newline ) )
FI |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Arturo | Arturo | contents: "Hello World!"
write "output.txt" contents |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #REBOL | REBOL |
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.