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 | response_seed stringclasses 1
value | instruction_seed stringlengths 27 14.4k | _source stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Lua | Lua | -- Table to store values
local values = {}
-- Read in the first number from stdin
local new_val = io.read"*n"
-- Append all numbers passed in
-- until there are no more numbers (io.read'*n' = nil)
while new_val do
values[#values+1] = new_val
new_val = io.read"*n"
end
-- Print the max
print(math.max(unpack(values... | Give a code snippet in #Lua
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #F.23 | F# | open System
let main _ =
Console.WriteLine(Math.E); // e
Console.WriteLine(Math.PI); // Pi
Console.WriteLine(Math.Sqrt(10.0)); // Square Root
Console.WriteLine(Math.Log(10.0)); // Logarithm
Console.WriteLine(Math.Log10(10.0)); // Base 10 Logarithm
Console.WriteL... | Give a code snippet in #F.23
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "ma... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM First we draw the clock face
20 FOR n=1 TO 12
30 PRINT AT 10-10*COS (n/6*PI),16+10*SIN (n/6*PI);n
40 NEXT n
50 DEF FN t()=INT (65536*PEEK 23674+256*PEEK 23673+PEEK 23672)/50: REM number of seconds since start
100 REM Now we start the clock
110 LET t1=FN t()
120 LET a=t1/30*PI: REM a is the angle of the second ha... | Give a code snippet in #ZX_Spectrum_Basic
Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #SPL | SPL | myLabel ->
...
:myLabel | Give a code snippet in #SPL
Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Keyboard_input/Keypress_check | Keyboard input/Keypress check |
Determine if a key has been pressed and store this in a variable.
If no key has been pressed, the program should continue without waiting.
| #Lingo | Lingo | -- in some movie script
-- event handler
on keyDown
pressedKey = _key.key
put "A key was pressed:" && pressedKey
end | Give a code snippet in #Lingo
Determine if a key has been pressed and store this in a variable.
If no key has been pressed, the program should continue without waiting.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #XBS | XBS | func nthRoot(x,a){
send x^(1/a);
}{a=2};
log(nthRoot(8,3)); | Give a code snippet in #XBS
Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #AutoIt | AutoIt | ;AutoIt Version: 3.2.10.0
$num = 45
MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num))
consolewrite ("Factors of " & $num & " are: " & factors($num))
Func factors($intg)
$ls_factors=""
For $i = 1 to $intg/2
if ($intg/$i - int($intg/$i))=0 Then
$ls_factors=$ls_factors&$i &", "
EndI... | Give a code snippet in #AutoIt
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Prolog | Prolog | permutation_sort(L,S) :- permutation(L,S), sorted(S).
sorted([]).
sorted([_]).
sorted([X,Y|ZS]) :- X =< Y, sorted([Y|ZS]).
permutation([],[]).
permutation([X|XS],YS) :- permutation(XS,ZS), select(X,YS,ZS). | Give a code snippet in #Prolog
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Show_the_epoch | Show the epoch | Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), b... | #Sidef | Sidef | say Time.new(0).gmtime.ctime; | Give a code snippet in #Sidef
Task
Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as t... | #Tailspin | Tailspin |
// matcher testing if the array contains anything not equal to the first element
templates allEqual
when <[](..1)> do 1 !
when <[<~=$(1)>]> do 0 !
otherwise 1 !
end allEqual
templates strictAscending
def a: $;
1 -> #
when <$a::length..> do 1 !
when <?($a($) <..~$a($+1)>)> do $ + 1 -> #
otherwise 0 !... | Give a code snippet in #Tailspin
Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or fal... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Run_BASIC | Run BASIC | ' adapted from BASIC solution
input "Number of tries;";tries ' gimme the number of iterations
FOR plays = 1 TO tries
winner = INT(RND(1) * 3) + 1
doors(winner) = 1 'put a winner in a random door
choice = INT(RND(1) * 3) + 1 'pick a door please
[DO] shown = INT(RND(1) * 3) + 1
' --------------------... | Give a code snippet in #Run_BASIC
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #JavaScript | JavaScript | var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)]; | Give a code snippet in #JavaScript
Demonstrate how to pick a random element from a list.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Common_Lisp | Common Lisp | (defconstant +alphabet+
'(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P
#\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z))
(defun rot13 (s)
(map 'string
(lambda (c &aux (n (position (char-upcase c) +alphabet+)))
(if n
(funcall
(if (lower-case-p c) #'char-downcase #'identity)
... | Give a code snippet in #Common_Lisp
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #J | J |
NB. Use, linux.
NB. $ /usr/local/j64-801/bin/jconsole j.ijs 8 meter
UNIT2MULT =: /:~ _ ".&.>@:{:@:]`1:`]}"1<;._2@:(,&':');._2 'arshin:0.7112,centimeter:0.01,diuym:0.0254,fut:0.3048,kilometer:1000.0,liniya:0.00254,meter:1.0,milia:7467.6,piad:0.1778,sazhen:2.1336,tochka:0.000254,vershok:0.04445,versta:1066.8,'
exit... | Give a code snippet in #J
Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and retu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Prolog | Prolog | powerset(X,Y) :- bagof( S, subseq(S,X), Y).
subseq( [], []).
subseq( [], [_|_]).
subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys).
subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs).
| Give a code snippet in #Prolog
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Give... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #Scilab | Scilab | Init_board=[...
5 3 0 0 7 0 0 0 0;...
6 0 0 1 9 5 0 0 0;...
0 9 8 0 0 0 0 6 0;...
8 0 0 0 6 0 0 0 3;...
4 0 0 8 0 3 0 0 1;...
7 0 0 0 2 0 0 0 6;...
0 6 0 0 0 0 2 8 0;...
0 0 0 4 1 9 0 0 5;...
0 0 0 0 8 0 0 7 9];
break_point=1.0d5; //if 0 there will be no break
function []=disp_board(board)
StringBoard=string(bo... | Give a code snippet in #Scilab
Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val proc = Runtime.getRuntime().exec("cmd /C dir") // testing on Windows 10
Scanner(proc.inputStream).use {
while (it.hasNextLine()) println(it.nextLine())
}
} | Give a code snippet in #Kotlin
Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.... | #PicoLisp | PicoLisp | (off "Stack")
(de $$ "Prg"
(let "Stack" (cons (cons (car "Prg") (env)) "Stack") # Build stack frame
(set "Stack"
(delq (asoq '"Stack" (car "Stack")) # Remove self-created entries
(delq (asoq '"Prg" (car "Stack"))
(car "Stack") ) ) )
(run (cdr "Prg")) ) ) # Run bod... | Give a code snippet in #PicoLisp
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Vampire_number | Vampire number | A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original number
together they consist of exactl... | #Icon_and_Unicon | Icon and Unicon | procedure main()
write("First 25 vampire numbers and their fangs:")
every fangs := vampire(n := seq())\25 do write(right(n,20),":",fangs)
write("\nOther numbers:")
every n := 16758243290880 | 24959017348650 | 14593825548650 do
write(right(n,20),": ",vampire(n)|"toothless")
end
procedure vampir... | Give a code snippet in #Icon_and_Unicon
A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers.
These two factors are called the fangs, and must have the following properties:
they each contain half the number of the decimal digits of the original ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #360_Assembly | 360 Assembly | FALSE DC X'00'
TRUE DC X'FF' | Give a code snippet in #360_Assembly
Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #Sidef | Sidef | func bxor(a, b) {
(~a & b) | (a & ~b)
}
func half_adder(a, b) {
return (bxor(a, b), a & b)
}
func full_adder(a, b, c) {
var (s1, c1) = half_adder(a, c)
var (s2, c2) = half_adder(s1, b)
return (s2, c1 | c2)
}
func four_bit_adder(a, b) {
var (s0, c0) = full_adder(a[0], b[0], 0)
var (s1, c1) = full_add... | Give a code snippet in #Sidef
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Handle_a_signal | Handle a signal | Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defi... | #D | D | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
/*
* Signal safety: It is not safe to call clock(), printf(),
* or exit() inside a signal handler. ... | Give a code snippet in #D
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the pro... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #ACL2 | ACL2 | (defun fizzbuzz-r (i)
(declare (xargs :measure (nfix (- 100 i))))
(prog2$
(cond ((= (mod i 15) 0) (cw "FizzBuzz~%"))
((= (mod i 5) 0) (cw "Buzz~%"))
((= (mod i 3) 0) (cw "Fizz~%"))
(t (cw "~x0~%" i)))
(if (zp (- 100 i))
nil
(fizzbuzz-r (1+ i)))))
(defun fizz... | Give a code snippet in #ACL2
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Futhark | Futhark |
fun ackermann(m: int, n: int): int =
if m == 0 then n + 1
else if n == 0 then ackermann(m-1, 1)
else ackermann(m - 1, ackermann(m, n-1))
| Give a code snippet in #Futhark
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions | GUI/Maximum window dimensions | The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an... | #Processing | Processing |
//Aamrun, 26th June 2022
fullScreen();
fill(0);
textSize(50);
text("Screen Height : " + str(height), 100, 100);
text("Screen Width : " + str(width), 100, 200);
| Give a code snippet in #Processing
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #Groovy | Groovy | def i = 0
do {
i++
println i
} while (i % 6 != 0) | Give a code snippet in #Groovy
Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #Unlambda | Unlambda | ``s`ksk
| Give a code snippet in #Unlambda
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for ... | #11l | 11l | #!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 #
MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 #
MODE UNICODE = FLEX[0]UNICHAR;
OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out);
OP INI... | Give a code snippet in #11l
As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is y... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #Ursala | Ursala | #import std
#import nat
balanced = @NiX ~&irB->ilZB ~&rh?/~&lbtPB ~&NlCrtPX
#cast %bm
main = ^(2-$'[]'*,balanced)* eql@ZFiFX*~ iota64 | Give a code snippet in #Ursala
Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, o... | #11l | 11l | V txt = ‘Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$j... | Give a code snippet in #11l
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
... | #Kotlin | Kotlin | // version 1.1.3
typealias C = Complex
typealias Vector = Array<C>
typealias Matrix = Array<Vector>
class Complex(val real: Double, val imag: Double) {
operator fun plus(other: Complex) =
Complex(this.real + other.real, this.imag + other.imag)
operator fun times(other: Complex) =
Complex... | Give a code snippet in #Kotlin
Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Wilson_primes_of_order_n | Wilson primes of order n | Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
Task
Calculate and show on thi... | #Raku | Raku | # Factorial
sub postfix:<!> (Int $n) { (constant f = 1, |[\×] 1..*)[$n] }
# Invisible times
sub infix:<> is tighter(&infix:<**>) { $^a * $^b };
# Prime the iterator for thread safety
sink 11000!;
my @primes = ^1.1e4 .grep: *.is-prime;
say
' n: Wilson primes
────────────────────';
.say for (1..40).hyper(:1ba... | Give a code snippet in #Raku
Definition
A Wilson prime of order n is a prime number p such that p2 exactly divides:
(n − 1)! × (p − n)! − (− 1)n
If n is 1, the latter formula reduces to the more familiar: (p - n)! + 1 where the only known examples for p are 5, 13, and 563.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/RPG_attributes_generator | RPG attributes generator | RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three... | #R | R | genStats <- function()
{
stats <- c(STR = 0, DEX = 0, CON = 0, INT = 0, WIS = 0, CHA = 0)
for(i in seq_along(stats))
{
results <- sample(6, 4, replace = TRUE)
stats[i] <- sum(results[-which.min(results)])
}
if(sum(stats >= 15) < 2 || (stats["TOT"] <- sum(stats)) < 75) Recall() else stats
}
print(genS... | Give a code snippet in #R
RPG = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #PHP | PHP | function is_perfect($number)
{
$sum = 0;
for($i = 1; $i < $number; $i++)
{
if($number % $i == 0)
$sum += $i;
}
return $sum == $number;
}
echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
if(is_perfect($num))
echo $num . P... | Give a code snippet in #PHP
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #Vedit_macro_language | Vedit macro language | for (#1 = 1; #1 < 10; #1 += 2) {
Num_Type(#1)
} | Give a code snippet in #Vedit_macro_language
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Forea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... ... | #Java | Java | import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
... | Give a code snippet in #Java
Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Nim | Nim | import sequtils, strformat
type
Piece {.pure.} = enum Empty, Black, White
Position = tuple[x, y: int]
func isAttacking(queen, pos: Position): bool =
queen.x == pos.x or queen.y == pos.y or abs(queen.x - pos.x) == abs(queen.y - pos.y)
func place(m, n: int; blackQueens, whiteQueens: var seq[Position]): ... | Give a code snippet in #Nim
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m bla... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_comparison | String comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #PicoLisp | PicoLisp | (setq
str= =
str< <
str> > )
(println
(str= (lowc "Foo") (lowc "foo") (lowc "fOO"))
(str= "f" "foo")
(str= "foo" "foo" "foo")
(str= "" "") )
(println
(str< "abc" "def")
(str> "abc" "def")
(str< "" "")
(str< "12" "45") )
(bye) | Give a code snippet in #PicoLisp
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operatio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Ring | Ring |
# Project: Primorial numbers
load "bignumber.ring"
decimals(0)
num = 0
prim = 0
limit = 10000000
see "working..." + nl
see "wait for done..." + nl
while num < 100001
prim = prim + 1
prime = []
primorial(prim)
end
see "done..." + nl
func primorial(pr)
n = 1
n2 = 0
flag = 1
while... | Give a code snippet in #Ring
Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/Floating_point | Literals/Floating point | Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo... | #Nim | Nim | var x: float
x = 2.3
x = 2.0
x = 0.3
x = 123_456_789.000_000_1
x = 2e10
x = 2.5e10
x = 2.523_123E10
x = 5.2e-10
var y = 2'f32 # Automatically a float32
var z = 2'f64 # Automatically a float64
| Give a code snippet in #Nim
Programming languages have different ways of expressing floating-point literals.
Task
Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.
You may want to include a regular expression or BNF/AB... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #PureBasic | PureBasic | Define.f ref=49.0, mea
NewList argV.f()
Macro put
Print(~"\n["+StrF(ref)+"]"+#TAB$)
ForEach argV() : Print(StrF(argV())+#TAB$) : Next
PrintN(~"\nAverage Error : "+StrF(vari(argV(),ref),5))
PrintN("Crowd Error : "+StrF((ref-mea)*(ref-mea),5))
PrintN("Diversity : "+StrF(vari(argV(),mea),5))
EndMacro
... | Give a code snippet in #PureBasic
The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Juggler_sequence | Juggler sequence | Background of the juggler sequence:
Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the hands of a juggler.
Descrip... | #11l | 11l | F juggler(n)
V a = Int64(n)
V r_count = 0
V r_max = a
V r_maxidx = 0
L a != 1
V f = Float(a)
a = Int64(I a [&] 1 == 0 {sqrt(f)} E f * sqrt(f))
r_count++
I a > r_max
r_max = a
r_maxidx = r_count
R (r_count, r_max, r_maxidx)
print(‘n l[n] h[n] i[... | Give a code snippet in #11l
Background of the juggler sequence:
Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Enable FileExists() function to be used
#include "file.bi"
' Use Win32 function to check if directory exists on Windows 10
Declare Function GetFileAttributes Lib "kernel32.dll" Alias "GetFileAttributesA" _
(ByVal lpFileName As ZString Ptr) As ULong
Const InvalidFileAttributes As ULong = -1UL
C... | Give a code snippet in #FreeBASIC
Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variables | Variables | Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | set MyStr = "A string"
set MyInt = 4
set MyFloat = 1.3 | Give a code snippet in #Cach.C3.A9_ObjectScript
Task
Demonstrate a language's methods of:
variable declaration
initialization
assignment
datatypes
scope
referencing, and
other variable related facilities
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #AppleScript | AppleScript | if myVar is "ok" then return true
set i to 0
if i is 0 then
return "zero"
else if i mod 2 is 0 then
return "even"
else
return "odd"
end if | Give a code snippet in #AppleScript
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values;... | #11l | 11l | F middle_three_digits(i)
V s = String(abs(i))
assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’)
R s[s.len I/ 2 - 1 .+ 3]
V passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
V failing = [1, 2, -1, -10, 2002, -2002, 0]
L(x) passing [+] failing
X.try
V ans... | Give a code snippet in #11l
Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be test... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #EchoLisp | EchoLisp |
(lib 'compile) ;; for (compile)
(lib 'bigint) ;; integer results > 32 bits
(lib 'hash) ;; hash table
;; h-table
(define Hcoins (make-hash))
;; the function to memoize
(define (sumways cents coins)
(+ (ways cents (cdr coins)) (ways (- cents (car coins)) coins)))
;; accelerator : ways (cents, coins) = ways (... | Give a code snippet in #EchoLisp
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels an... | christopher/rosetta-code | |
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,... | #Slate | Slate | slate[1]> #x := ##(1 2 3).
{1. 2. 3}
slate[2]> x
{1. 2. 3}
slate[3]> #y := {1 + 2. 3 + 4. 5}.
{3. 7. 5}
slate[4]> y at: 2 put: 99.
99
slate[5]> y
{3. 7. 99}
slate[6]> x first
1
slate[7]> x at: 0.
1 | Give a code snippet in #Slate
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 retri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #Groovy | Groovy | def string = 'Scooby-doo-bee-doo' // assigns string object to a variable reference
def stringRef = string // assigns another variable reference to the same object
def stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference | Give a code snippet in #Groovy
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Lua | Lua | -- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
local cipher, rnd = {plain = {}, encoded = {}}
for ascii = 65, 122 do
table.insert(cipher.plain, string.char(ascii))
table.insert(cipher.encoded, string.char(ascii))
end
for i = 1, #cipher.en... | Give a code snippet in #Lua
Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then agai... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_comparison | Integer comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Oz | Oz | functor
import
Application(exit)
Open(text file)
define
Txt = class from Open.file Open.text end
Stdout = {New Open.file init(name:stdout)}
Stdin = {New Txt init(name:stdin)}
proc{Print Msg}
{Stdout write(vs:Msg)}
end
fun{GetInt Prompt}
{Print Prompt}
{StringToInt {Stdin getS($)}}
end
Int1 = {GetI... | Give a code snippet in #Oz
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Con... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Gema | Gema | \L<G> <U>=@{$2} $1 | Give a code snippet in #Gema
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by space... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mean_angle | Averages/Mean angle | When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ... | #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 18:07:59
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
! -7.80250048E-06 350 10
! 90.0000000 90 1... | Give a code snippet in #Fortran
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.
If one wanted an average direction of the wind over two readings where the first re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #APL | APL | #!/usr/local/bin/apl -s --
∇r←b FlipRow ix ⍝ Flip a row
r←b
r[ix;]←~r[ix;]
∇
∇r←b FlipCol ix ⍝ Flip a column
r←b
r[;ix]←~r[;ix]
∇
∇r←RandFlip b;ix ⍝ Flip a random row or column
ix←?↑⍴b
→(2|?2)/col
r←b FlipRow ix ⋄ →0
col: ... | Give a code snippet in #APL
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move)... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #PowerShell | PowerShell |
function Get-OneOfN ([int]$Number)
{
$current = 1
for ($i = 2; $i -le $Number; $i++)
{
$limit = 1 / $i
if ((Get-Random -Minimum 0.0 -Maximum 1.0) -lt $limit)
{
$current = $i
}
}
$current
}
$table = [ordered]@{}
for ($i = 1; $i -lt 11; $i++)
... | Give a code snippet in #PowerShell
A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the secon... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #M2000_Interpreter | M2000 Interpreter |
Module CatalanNumbers {
Def Integer count, t_row, size=31
Dim triangle(1 to size, 1 to size)
\\ call sub
pascal_triangle(size, &triangle())
Print "The first 15 Catalan numbers are"
count = 1% : t_row = 2%
Do {
Print Format$("{0:0:-3}:{1:0:-15}", count, tr... | Give a code snippet in #M2000_Interpreter
Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triang... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #LFE | LFE |
(defun partial
"The partial function is arity 2 where the first parameter must be a
function and the second parameter may either be a single item or a list of
items.
When funcall is called against the result of the partial call, a second
parameter is applied to the partial function. This parameter too may... | Give a code snippet in #LFE
Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #PL.2FI | PL/I | threeor5: procedure options (main); /* 8 June 2014 */
declare (i, n) fixed(10), sum fixed (31) static initial (0);
get (n);
put ('The number of multiples of 3 or 5 below ' || trim(n) || ' is');
do i = 1 to n-1;
if mod(i, 3) = 0 | mod(i, 5) = 0 then sum = sum + i;
end;
put edit ( trim(... | Give a code snippet in #PL.2FI
Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #Fortran | Fortran | sudo apt-get install gfortran
| Give a code snippet in #Fortran
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the langua... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #Elixir | Elixir | iex(1)> defmodule Point do
...(1)> defstruct x: 0, y: 0
...(1)> end
{:module, Point, <<70, 79, 82, ...>>, %Point{x: 0, y: 0}}
iex(2)> origin = %Point{}
%Point{x: 0, y: 0}
iex(3)> pa = %Point{x: 10, y: 20}
%Point{x: 10, y: 20}
iex(4)> pa.x
10
iex(5)> %Point{pa | y: 30}
%Point{x: 10, y: 30}
iex(6)> %Point{x: px, y: py}... | Give a code snippet in #Elixir
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/History_variables | History variables | Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are variables in a programming la... | #Java | Java | import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* A class for an "Integer with a history".
* <p>
* Note that it is not possible to create an empty Variable (so there is no "null") with this type. This is a design
* choice, because if "empty" variables were allowed, reading of... | Give a code snippet in #Java
Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.
History variables are... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Kosaraju | Kosaraju |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a lin... | #Julia | Julia | function korasaju(g::Vector{Vector{T}}) where T<:Integer
# 1. For each vertex u of the graph, mark u as unvisited. Let L be empty.
vis = falses(length(g))
L = Vector{T}(length(g))
x = length(L) + 1
t = collect(T[] for _ in eachindex(g))
# Recursive
function visit(u::T)
if !vi... | Give a code snippet in #Julia
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Kosaraju's algorithm (also known as the Kosa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one dow... | #Aime | Aime | integer bottles;
bottles = 99;
do {
o_(bottles, " bottles of beer on the wall\n");
o_(bottles, " bottles of beer\n");
o_("Take one down, pass it around\n");
o_(bottles -= 1, " bottles of beer on the wall\n\n");
} while (bottles); | Give a code snippet in #Aime
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols
say stripchars("She was a soul stripper. She took my heart!", "aei")
return
method stripchars(haystack, chs) public static
loop c_ = 1 to chs.length
needle = chs.substr(c_, 1)
haystack = haystack.changestr(needle, '')
en... | Give a code snippet in #NetRexx
Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #K | K | comb:{[n;k]
f:{:[k=#x; :,x; :,/_f' x,'(1+*|x) _ !n]}
:,/f' !n
} | Give a code snippet in #K
Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Untouchable_numbers | Untouchable numbers | Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also known as the aliquot sum.
A... | #F.23 | F# |
// Applied dendrology. Nigel Galloway: February 15., 2021
let uT a=let N,G=Array.create(a+1) true, [|yield! primes64()|>Seq.takeWhile((>)(int64 a))|]
let fN n i e=let mutable p=e-1 in (fun()->p<-p+1; if p<G.Length && (n+i)*(1L+G.[p])-n*G.[p]<=(int64 a) then Some(n,i,p) else None)
let fG n i e=let ... | Give a code snippet in #F.23
Definitions
Untouchable numbers are also known as nonaliquot numbers.
An untouchable number is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. (From Wikipedia)
The sum of all the proper divisors is also know... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mouse_position | Mouse position | Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| #Rust | Rust | // rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)
use std::libc::{BOOL, HANDLE, LONG};
use std::ptr::mut_null;
type HWND = HANDLE;
#[deriving(Eq)]
struct POINT {
x: LONG,
y: LONG
}
#[link_name = "user32"]
extern "system" {
fn GetCursorPos(lpPoint:&mut POINT) -> BOOL;
fn GetForegroundWindow() -> H... | Give a code snippet in #Rust
Task
Get the current location of the mouse cursor relative to the active window.
Please specify if the window may be externally created.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Ruby | Ruby | File.rename('input.txt', 'output.txt')
File.rename('/input.txt', '/output.txt')
File.rename('docs', 'mydocs')
File.rename('/docs', '/mydocs') | Give a code snippet in #Ruby
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rig... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_conspiracy | Prime conspiracy | A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of ... | #VBA | VBA |
Option Explicit
Sub Main()
Dim Dict As Object, L() As Long
Dim t As Single
Init Dict
L = ListPrimes(100000000)
t = Timer
PrimeConspiracy L, Dict, 1000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
Debug.Print ""
Init Dict
t = Timer
Prim... | Give a code snippet in #VBA
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preference... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Delphi | Delphi |
unit uSettings;
interface
uses
System.SysUtils, System.IoUtils, System.Generics.Collections, System.Variants;
type
TVariable = record
value: variant;
function ToString: string;
class operator Implicit(a: variant): TVariable;
class operator Implicit(a: TVariable): TArray<string>;
class op... | Give a code snippet in #Delphi
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Crystal | Crystal | require "set"
UNIXDICT = File.read("unixdict.txt").lines
def word?(word : String)
UNIXDICT.includes?(word)
end
# is it a word and is it a word backwards?
semordnilap = UNIXDICT.select { |word| word?(word) && word?(word.reverse) }
# consolidate pairs like [bad, dab] == [dab, bad]
final_results = semordnilap.ma... | Give a code snippet in #Crystal
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #langur | langur | for .i of 100 {
writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i)
} | Give a code snippet in #langur
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuz... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #X86_Assembly | X86 Assembly |
; linux x86_64
struc block
free: resb 1 ; whether or not this block is free
size: resb 2 ; size of the chunk of memory
next: resb 8 ; the next chunk after this one
mem:
endstruc
section .data
hStart: dq 0 ; the beginning of our heap space
break: dq 0 ; the current end of our heap space
section .text
Allocat... | Give a code snippet in #X86_Assembly
Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Handle_a_signal | Handle a signal | Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defi... | #Go | Go | package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
// not busy waiting, this blocks until one of the two
// channel o... | Give a code snippet in #Go
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the pr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The ... | #Phix | Phix | with javascript_semantics
constant powers = sq_power(tagset(9,0),tagset(9,0))
function munchausen(integer n)
integer n0 = n
atom total = 0
while n!=0 do
total += powers[remainder(n,10)+1]
n = floor(n/10)
end while
return (total==n0)
end function
for i=1 to 5000 do
if munchaus... | Give a code snippet in #Phix
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, ... | #Fortran | Fortran |
program zero
double precision :: i, j
double complex :: z1, z2
i = 0.0D0
j = 0.0D0
z1 = (0.0D0,0.0D0)
z2 = (0.0D0,0.0D0)
write(*,*) 'When integers are used, we have 0^0 = ', 0**0
write(*,*) 'When double precision numbers are used, we have 0.0^0.0 = ', i**j
write(*,*) 'When complex numbers are used, we have (0.0+0.0i)... | Give a code snippet in #Fortran
Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #Elm | Elm |
--Compound Data type can hold multiple independent values
--In Elm data can be compounded using List, Tuple, Record
--In a List
point = [2,5]
--This creates a list having x and y which are independent and can be accessed by List functions
--Note that x and y must be of same data type
--Tuple is another useful data ... | Give a code snippet in #Elm
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Rel... | christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling ... | #Go | Go | package main
import (
"encoding/xml"
"fmt"
)
// Function required by task description.
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
// Task description allows the function to take "a single mapping..."
// This data structure... | Give a code snippet in #Go
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> eleme... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pe... | #Fortran | Fortran | program pernicious
implicit none
integer :: i, n
i = 1
n = 0
do
if(isprime(popcnt(i))) then
write(*, "(i0, 1x)", advance = "no") i
n = n + 1
if(n == 25) exit
end if
i = i + 1
end do
write(*,*)
do i = 888888877, 888888888
if(isprime(popcnt(i))) write(*, "(i0, 1x)",... | Give a code snippet in #Fortran
A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is pri... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case... | #Ring | Ring |
# Project : Euler's sum of powers conjecture
max=250
for w = 1 to max
for x = 1 to w
for y = 1 to x
for z = 1 to y
sum = pow(w,5) + pow(x,5) + pow(y,5) + pow(z,5)
s1 = floor(pow(sum,0.2))
if sum = pow(s1,5)
... | Give a code snippet in #Ring
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Lua | Lua | local permute, tablex = require("pl.permute"), require("pl.tablex")
local permList, pStr = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
}
for perm in permute.iter({"A",... | Give a code snippet in #Lua
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Quite_BASIC | Quite BASIC | Give a code snippet in #Quite_BASIC
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Processing | Processing | void setup() {
size(500, 500, P3D);
}
void draw() {
background(192);
translate(width/2, height/2);
// optional color and lighting style
stroke(200);
fill(255);
lights();
// draw sphere
sphere(200);
} | Give a code snippet in #Processing
Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Factor | Factor | USING: fry io kernel math prettyprint sequences ;
IN: rosetta-code.leonardo-numbers
: first25-leonardo ( vector add -- seq )
23 swap '[ dup 2 tail* sum _ + over push ] times ;
: print-leo ( seq -- ) [ pprint bl ] each nl ;
"First 25 Leonardo numbers:" print
V{ 1 1 } 1 first25-leonardo print-leo
"First 25 Le... | Give a code snippet in #Factor
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles... | #Rust | Rust |
fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) {
if x == 0 || y == 0 || x == w || y == h {
*count += 1;
return;
}
vis[y][x] = true;
vis[h - y][w - x] = true;
if x != 0 && ! vis[y][x - 1] {
cwalk(&mut vis, coun... | Give a code snippet in #Rust
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Ursala | Ursala | #import std
#import nat
x = <89,36,13,15,41,39,21,3,15,92,16,59,52,88,33,65,54,88,93,43>
#cast %nL
y = (not remainder\2)*~ x | Give a code snippet in #Ursala
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| christopher/rosetta-code | |
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,... | #Wren | Wren | var arr = []
arr.add(1)
arr.add(2)
arr.count // 2
arr.clear()
arr.add(0)
arr.add(arr[0])
arr.add(1)
arr.add(arr[-1]) // [0, 0, 1, 1]
arr[-1] = 0
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.removeAt(2) // [0, 0, 0, 0] | Give a code snippet in #Wren
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 retrie... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(... | #Rust | Rust | fn multifactorial(n: i32, deg: i32) -> i32 {
if n < 1 {
1
} else {
n * multifactorial(n - deg, deg)
}
}
fn main() {
for i in 1..6 {
for j in 1..11 {
print!("{} ", multifactorial(j, i));
}
println!("");
}
} | Give a code snippet in #Rust
The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\disp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quaternion_type | Quaternion type | Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
wher... | #PARI.2FGP | PARI/GP | q.norm={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
sqrt(q[1]^2+q[2]^2+q[3]^2+q[4]^2)
};
q.conj={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
-[-q[1],q[2],q[3],q[4]]
};
q.add={
if(type(q) != "t_VEC" || #q != 4, error("incorrect type"));
x->if(type(x) == "t_INT" || type(x) == t_REA... | Give a code snippet in #PARI.2FGP
Quaternions are an extension of the idea of complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #Latitude | Latitude | foo (1, 2, 3). ; (1) Ordinary call
foo (). ; (2) No arguments
foo. ; (3) Equivalent to (2)
foo (1). ; (4) Single-argument function
foo 1. ; (5) Equivalent to (4)
foo (bar). ; (6) Parentheses necessary here since bar is not a literal
foo: 1, 2, 3. ; (7) Alternative syntax, equivalent ... | Give a code snippet in #Latitude
Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Host_introspection | Host introspection | Print the word size and endianness of the host machine.
See also: Variable size/Get
| #MATLAB_.2F_Octave | MATLAB / Octave | function [endian]=endian()
fid=tmpfile();
fwrite(fid,1:8,'uint8');
fseek(fid,0,'bof');
t=fread(fid,8,'int8');
i8=sprintf('%02X',t);
fseek(fid,0,'bof');
t=fread(fid,4,'int16');
i16=sprintf('%04X',t);
fclose(fid);
if strcmp(i8,i16) endian='big';
else endian='little';
... | Give a code snippet in #MATLAB_.2F_Octave
Print the word size and endianness of the host machine.
See also: Variable size/Get
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Jaro_similarity | Jaro similarity | The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an exact match.
Definition
The... | #Raku | Raku | sub jaro ($s, $t) {
return 1 if $s eq $t;
my $s_len = + my @s = $s.comb;
my $t_len = + my @t = $t.comb;
my $match_distance = ($s_len max $t_len) div 2 - 1;
my ($matches, @s_matches, @t_matches);
for ^@s -> $i {
my $start = 0 max $i - $match_distance;
my $end = $i + $match_d... | Give a code snippet in #Raku
The Jaro distance is a measure of edit distance between two strings; its inverse, called the Jaro similarity, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that 0 equates to no similarities and 1 is an ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for ... | #langur | langur | q:any"any code points here" | Give a code snippet in #langur
As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared i... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multifactorial | Multifactorial | The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(... | #Java | Java | public class MultiFact {
private static long multiFact(long n, int deg){
long ans = 1;
for(long i = n; i > 0; i -= deg){
ans *= i;
}
return ans;
}
public static void main(String[] args){
for(int deg = 1; deg <= 5; deg++){
System.out.print("degree " + deg + ":");
for(long n = 1; n <= 10; n++){
... | Give a code snippet in #Java
The factorial of a number, written as
n
!
{\displaystyle n!}
, is defined as
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle n!=n(n-1)(n-2)...(2)(1)}
.
Multifactorials generalize factorials as follows:
n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\disp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Long_literals,_with_continuations | Long literals, with continuations | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form ... | #FreeBASIC | FreeBASIC |
Dim As String ultimaRevision = "2021-11-12"
Dim As String elemento(0 to ...) => { _
"hydrogen", "helium", "lithium", "beryllium", "boron", "carbon", "nitrogen", _
"oxygen", "fluorine", "neon", "sodium", "magnesium", "aluminum", "silicon", _
"phosphorous", "sulfur", "chlorine", "argon", "potassium", "calcium", _
"scan... | Give a code snippet in #FreeBASIC
This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Pascal | Pascal | program SemiPrime;
{$IFDEF FPC}
{$Mode objfpc}// compiler switch to use result
{$ELSE}
{$APPTYPE CONSOLE} // for Delphi
{$ENDIF}
uses
primTrial;
function isSemiprime(n: longWord;doWrite:boolean): boolean;
var
fac1 : LongWord;
begin
//a simple isAlmostPrime(n,2) would do without output;
fac1 := SmallFactor... | Give a code snippet in #Pascal
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was ch... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Groovy | Groovy | def assertConformable = { a, b ->
assert a instanceof List
assert b instanceof List
assert a.every { it instanceof List && it.size() == b.size() }
assert b.every { it instanceof List && it.size() == b[0].size() }
}
def matmulWOIL = { a, b ->
assertConformable(a, b)
def bt = b.transpose()
... | Give a code snippet in #Groovy
Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Icon_and_Unicon | Icon and Unicon | procedure main() # validate against the RFC test strings and more
testMD5("The quick brown fox jumps over the lazy dog", 16r9e107d9d372bb6826bd81d3542a419d6)
testMD5("The quick brown fox jumps over the lazy dog.", 16re4d909c290d0fb1ca068ffaddf22cbd0)
testMD5("", 16rd41d8cd98f00b204e9800998ecf8427e)
end
... | Give a code snippet in #Icon_and_Unicon
Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm... | christopher/rosetta-code | |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #OCaml | OCaml | let dns_query ~host ~ai_family =
let opts = [
Unix.AI_FAMILY ai_family;
Unix.AI_SOCKTYPE Unix.SOCK_DGRAM;
] in
let addr_infos = Unix.getaddrinfo host "" opts in
match addr_infos with
| [] -> failwith "dns_query"
| ai :: _ ->
match ai.Unix.ai_addr with
| Unix.ADDR_INET (addr, _) -> (Unix.stri... | Give a code snippet in #OCaml
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_composition | Function composition | Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose... | #jq | jq |
# apply g first and then f
def compose(f; g): g | f;
| Give a code snippet in #jq
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g t... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.