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/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #C.23 | C# | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public... | Give a code snippet in #C.23
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of... | 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.
| #zkl | zkl | zkl: Network.TCPClientSocket.addrInfo("www.kame.net")
L("orange.kame.net",L("203.178.141.194","2001:200:dff:fff1:216:3eff:feb1:44d7")) | Give a code snippet in #zkl
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/Parametric_polymorphism | Parametric polymorphism | Parametric Polymorphism
type variables
Task
Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it.
A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ... | #Raku | Raku | role BinaryTree[::T] {
has T $.value;
has BinaryTree[T] $.left;
has BinaryTree[T] $.right;
method replace-all(T $value) {
$!value = $value;
$!left.replace-all($value) if $!left.defined;
$!right.replace-all($value) if $!right.defined;
}
}
class IntTree does BinaryTree[Int]... | Give a code snippet in #Raku
Parametric Polymorphism
type variables
Task
Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it.
A good example is a container type, let's say a binary tree, together with some func... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Gecho | Gecho | Give a code snippet in #Gecho
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Array_length | Array length | Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I befo... | #Jsish | Jsish | /* Array length, in jsish */
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr[1]); | Give a code snippet in #Jsish
Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #PowerShell | PowerShell | # Calculate best possible shuffle score for a given string
# (Split out into separate function so we can use it separately in our output)
function Get-BestScore ( [string]$String )
{
# Convert to array of characters, group identical characters,
# sort by frequecy, get size of first group
$MostRepeat... | Give a code snippet in #PowerShell
Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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)
Task
Write a function to compute the arithmetic-geomet... | #Julia | Julia | function agm(x, y, e::Real = 5)
(x ≤ 0 || y ≤ 0 || e ≤ 0) && throw(DomainError("x, y must be strictly positive"))
g, a = minmax(x, y)
while e * eps(x) < a - g
a, g = (a + g) / 2, sqrt(a * g)
end
a
end
x, y = 1.0, 1 / √2
println("# Using literal-precision float numbers:")
@show agm(x, y)
... | Give a code snippet in #Julia
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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)
Task
Write a function t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). 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)
Snake is a game where the player maneuvers a line which grows i... | #Rust | Rust | /* add to file Cargo.toml:
[dependencies]
winsafe = "0.0.8"
rand = "0.8.4"
*/
#![windows_subsystem = "windows"]
use rand::Rng;
use std::{cell::RefCell, rc::Rc};
use winsafe::{co, gui, prelude::*, COLORREF, HBRUSH, HPEN, SIZE};
const STEP: i32 = 3; // px, motion per frame. STEP and FPS determine the smoothness and... | Give a code snippet in #Rust
This page uses content from Wikipedia. The original article was at Snake_(video_game). 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)
Snake is a game where the player ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #BlitzMax | BlitzMax | local a:int = 0, b:int = 1, c:int = 1, n:int
n = int(input( "Enter n: "))
if n = 0 then
print 0
end
else if n = 1
print 1
end
end if
while n>2
a = b
b = c
c = a + b
n = n - 1
wend
print c | Give a code snippet in #BlitzMax
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SHA-256 | SHA-256 | SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
| #OS_X_sha256sum | OS X sha256sum | echo -n 'Rosetta code' | sha256sum | Give a code snippet in #OS_X_sha256sum
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.
Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542... | 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 |... | #Python | Python | #!/usr/bin/env python
a = input('Enter value of a: ')
b = input('Enter value of b: ')
if a < b:
print 'a is less than b'
elif a > b:
print 'a is greater than b'
elif a == b:
print 'a is equal to b' | Give a code snippet in #Python
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/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Go | Go | // Outline for a try/catch-like exception mechanism in Go
//
// As all Go programmers should know, the Go authors are sharply critical of
// the try/catch idiom and consider it bad practice in general.
// See http://golang.org/doc/go_faq.html#exceptions
package main
import (
"fmt"
"runtime"
"strings"
)
... | Give a code snippet in #Go
Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #bc | bc | for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) "*"
"
"
}
quit | Give a code snippet in #bc
“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Ruby | Ruby | grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c|
sumaabb, ab = a*a + b*b, a*b
case c*c
when sumaabb then 90
when sumaabb - ab then 60
when sumaabb + ab then 120
end
end
grouped.delete(nil)
res = grouped.transform_values{|v| v.map(&:sort).uniq }
res.each do |k,v|
puts "For... | Give a code snippet in #Ruby
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #XPL0 | XPL0 | func LeapYear(Y); \Return 'true' if Y is a leap year
int Y;
[if rem(Y/100)=0 then return rem(Y/400)=0;
return rem(Y/4)=0;
]; | Give a code snippet in #XPL0
Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.41421356... | #IDL | IDL | ; the data:
x = [1,2,3,1e11]
y=sqrt(x)
xprecision=3
yprecision=5
; NOT how one would do things in IDL, but in the spirit of the task - the output format:
form = string(xprecision,yprecision,format='("(G0.",I0.0,",1x,G0.",I0.0,")")')
; file I/O:
openw,unit,"datafile.txt",/get
for i = 1L, n_elements(x) do printf, u... | Give a code snippet in #IDL
Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Ruby | Ruby | def chowla(n)
sum = 0
i = 2
while i * i <= n do
if n % i == 0 then
sum = sum + i
j = n / i
if i != j then
sum = sum + j
end
end
i = i + 1
end
return sum
end
def main
for n in 1 .. 37 do
puts "chowla... | Give a code snippet in #Ruby
Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
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
... | #Fortran | Fortran | module sorts_with_custom_comparator
implicit none
contains
subroutine a_sort(a, cc)
character(len=*), dimension(:), intent(inout) :: a
interface
integer function cc(a, b)
character(len=*), intent(in) :: a, b
end function cc
end interface
integer :: i, j, increment
charac... | Give a code snippet in #Fortran
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
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 |... | #Pascal | Pascal | program pointerDemo;
type
{
A new pointer data type is declared by `↑` followed by a data type name,
the domain.
The domain data type may not have been declared yet, but must be
declared within the current `type` section.
Most compilers do not support the reference token `↑` as specified in
the ISO s... | Give a code snippet in #Pascal
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/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Numerics;
namespace PierpontPrimes {
public static class Helper {
private static readonly Random rand = new Random();
private static readonly List<int> primeList = new List<int>() {
2, 3, 5, 7, 11, 13, 17, 19, 23... | Give a code snippet in #C.23
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
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
... | #True_BASIC | True BASIC |
OPTION BASE 1
LET max = 10
DIM dat(10), res(10)
FOR i = 1 TO max
READ dat(i)
NEXT i
DATA 1, 2, 1, 4, 5, 2, 15, 1, 3, 4
LET res(1) = dat(1)
LET count = 1
LET posic = 1
DO WHILE posic < max
LET posic = posic + 1
LET esnuevo = 1
LET indice = 1
DO WHILE (indice <= count) AND esnuevo = 1
IF dat(p... | Give a code snippet in #True_BASIC
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 |
Qui... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Median | Averages/Median | Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values.
There are several approaches ... | #Factor | Factor | USING: arrays kernel locals math math.functions random sequences ;
IN: median
: pivot ( seq -- pivot ) random ;
: split ( seq pivot -- {lt,eq,gt} )
[ [ < ] curry partition ] keep
[ = ] curry partition
3array ;
DEFER: nth-in-order
:: nth-in-order-recur ( seq ind -- elt )
seq dup pivot split
dup [ length ... | Give a code snippet in #Factor
Task[edit]
Write a program to find the median value of a vector of floating-point numbers.
The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements. In that case, return the average of the two middle values... | 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... | #Liberty_BASIC | Liberty BASIC |
q$ = q$( 1 , 2 , 3 , 4 )
q1$ = q$( 2 , 3 , 4 , 5 )
q2$ = q$( 3 , 4 , 5 , 6 )
real = 7
print "q = " ; q$
print "q1 = " ; q1$
print "q2 = " ; q2$
print "real = " ; real
print "length /norm q = " ; length( q$ ) ' =norm norm of q
print "negative (-q1) = " ; negative$... | Give a code snippet in #Liberty_BASIC
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of thi... | #Vala | Vala | string s = " word ";
string s_chug = s.chug(); | Give a code snippet in #Vala
Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace rem... | 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.
| #AutoHotkey | AutoHotkey | ; Input [, OutputVar, Options, EndKeys, MatchList]
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds | Give a code snippet in #AutoHotkey
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/Selectively_replace_multiple_instances_of_a_character_within_a_string | Selectively replace multiple instances of a character within a string | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fifth 'a' with 'D'
the first 'b... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub transmogrify {
my($str, %sub) = @_;
for my $l (keys %sub) {
$str =~ s/$l/$_/ for split '', $sub{$l};
$str =~ s/_/$l/g;
}
$str
}
my $word = 'abracadabra';
say "$word -> " . transmogrify $word, 'a' => 'AB_CD', 'r' => '_F', 'b' => 'E'; | Give a code snippet in #Perl
Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
the first 'a' with 'A'
the second 'a' with 'B'
the fourth 'a' with 'C'
the fi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jensen%27s_Device | Jensen's Device | Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report.
The following pr... | #C.23 | C# | using System;
class JensensDevice
{
public static double Sum(ref int i, int lo, int hi, Func<double> term)
{
double temp = 0.0;
for (i = lo; i <= hi; i++)
{
temp += term();
}
return temp;
}
static void Main()
{
int i = 0;
Co... | Give a code snippet in #C.23
Jensen's Device
You are encouraged to solve this task according to the task description, using any language you may know.
This task is an exercise in call by name.
Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGO... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. 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)
In algebra, polynomial long division is an algorithm for d... | #Ursala | Ursala | #import std
#import flo
polydiv =
zeroid~-l~~; leql?rlX\~&NlX ^H\(@rNrNSPXlHDlS |\ :/0.) @NlX //=> ?(
@lrrPX ==!| zipp0.; @x not zeroid+ ==@h->hr ~&t,
(^lryPX/~&lrrl2C minus^*p/~&rrr times*lrlPD)^/div@bzPrrPlXO ~&,
@r ^|\~& ~&i&& :/0.) | Give a code snippet in #Ursala
This page uses content from Wikipedia. The original article was at Polynomial long division. 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)
In algebra, polynomial lon... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #MAXScript | MAXScript | fn multiply a b =
(
a * b
) | Give a code snippet in #MAXScript
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #BASIC | BASIC | DECLARE FUNCTION life$ (lastGen$)
DECLARE FUNCTION getNeighbors! (group$)
CLS
start$ = "_###_##_#_#_#_#__#__"
numGens = 10
FOR i = 0 TO numGens - 1
PRINT "Generation"; i; ": "; start$
start$ = life$(start$)
NEXT i
FUNCTION getNeighbors (group$)
ans = 0
IF (MID$(group$, 1, 1) = "#") THEN ans = ans + 1
IF (MID$... | Give a code snippet in #BASIC
Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the defin... | #Phix | Phix | with javascript_semantics
sequence strong = {}, weak = {}
for i=2 to get_maxprime(1e14) do -- (ie idx of primes < (sqrt(1e14)==1e7), bar 1st)
integer p = get_prime(i),
c = compare(p,(get_prime(i-1)+get_prime(i+1))/2)
if c=+1 then strong &= p end if
if c=-1 then weak &= p end if
end for
printf(1,"The f... | Give a code snippet in #Phix
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #JavaScript | JavaScript | (() => {
'use strict';
// allDigitSquare :: Int -> Int
const allDigitSquare = base => {
const bools = replicate(base, false);
return untilSucc(
allDigitsUsedAtBase(base, bools),
ceil(sqrt(parseInt(
'10' + '0123456789abcdef'.slice(2, base),
... | Give a code snippet in #JavaScript
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Free_Pascal | Free Pascal |
' FreeBASIC v1.05.0 win64
Print "a - > "; Asc("a")
Print "98 -> "; Chr(98)
Print
Print "Press any key to exit the program"
Sleep
End
| Give a code snippet in #Free_Pascal
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in... | #Wren | Wren | var narc = Fn.new { |n|
var power = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var limit = 10
var result = []
var x = 0
while (result.count < n) {
if (x >= limit) {
for (i in 0..9) power[i] = power[i] * i
limit = limit * 10
}
var sum = 0
var xx = x
... | Give a code snippet in #Wren
A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Clojure | Clojure | (let [crc (new java.util.zip.CRC32)
str "The quick brown fox jumps over the lazy dog"]
(. crc update (. str getBytes))
(printf "CRC-32('%s') = %s\n" str (Long/toHexString (. crc getValue)))) | Give a code snippet in #Clojure
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X | Isqrt (integer square root) of X | Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer programming language, assume... | #11l | 11l | F commatize(number, step = 3, sep = ‘,’)
V s = reversed(String(number))
String r = s[0]
L(i) 1 .< s.len
I i % step == 0
r ‘’= sep
r ‘’= s[i]
R reversed(r)
F isqrt(BigInt x)
assert(x >= 0)
V q = BigInt(1)
L q <= x
q *= 4
V z = x
V r = BigInt(0)
L q > 1
... | Give a code snippet in #11l
Sometimes a function is needed to find the integer square root of X, where X can be a
real non─negative number.
Often X is actually a non─negative integer.
For the purposes of this task, X can be an integer or a real number, but if it
simplifies things in your computer p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification | Ramer-Douglas-Peucker line simplification | Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–P... | #J | J | mp=: +/ .* NB. matrix product
norm=: +/&.:*: NB. vector norm
normalize=: (% norm)^:(0 < norm)
dxy=. normalize@({: - {.)
pv=. -"1 {.
NB.*perpDist v Calculate perpendicular distance of points from a line
perpDist=: norm"1@(pv ([ -"1 mp"1~ */ ]) dxy) f.
rdp=: verb define
1 rdp y
:
points=. ,:^:(2... | Give a code snippet in #J
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #X86_Assembly | X86 Assembly | section .text
global _start
_print:
mov ebx, 1
mov eax, 4
int 0x80
ret
_get_input:
mov edx, 4
mov ebx, 0
mov eax, 3
int 0x80
ret
_start:
mov edx, in_val_len
mov ecx, in_val_msg
call _print
mov ecx, a
call _get_input
;make 'a' an actual number rather than a char.
sub dword [a], ... | Give a code snippet in #X86_Assembly
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Action.21 | Action! | BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
CHAR ARRAY line(255)
CARD curr
BYTE status,dev=[1]
Close(dev)
Open(dev,fname,4)
curr=1 status=1
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF curr=index THEN
SCopy(result,line)
status=0
EXIT
FI
curr==+1
OD... | Give a code snippet in #Action.21
Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_search | Word search | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may ... | #Perl | Perl | #!/usr/bin/perl
use strict; # http://www.rosettacode.org/wiki/Word_search
use warnings;
use Path::Tiny;
use List::Util qw( shuffle );
my $size = 10;
my $s1 = $size + 1;
$_ = <<END;
.....R....
......O...
.......S..
........E.
T........T
.A........
..C.......
...O......
....D.....
.....E....
END
my @words = shuffle... | Give a code snippet in #Perl
A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spel... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Jsish | Jsish | prompt$ jsish
Jsish interactive: see 'help [cmd]'
# function f(a:string, b:string, s:string):string { return a+s+s+b; }
# f('Rosetta', 'Code', 1)
warn: type mismatch for argument arg 3 's': expected "string" but got "number", in call to 'f' <1>. (at or near "Code")
"Rosetta11Code"
# f('Rosetta', 'Code', ':')
"Roset... | Give a code snippet in #Jsish
Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Red | Red | Red []
repeat yy 114 [
d: to-date reduce [25 12 (2007 + yy )]
if 7 = d/weekday [ print d ] ;; 7 = sunday
]
;; or
print "version 2"
d: to-date [25 12 2008]
while [d <= 25/12/2121 ] [
if 7 = d/weekday [
print rejoin [d/day '. d/month '. d/year ]
]
d/year: d/year + 1
]
| Give a code snippet in #Red
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 20... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #Ada | Ada | with Ada.Text_IO;
procedure Main is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is
Value : Natural := N;
Result : Float := 0.0;
Exponent : Positive := 1;
begin
while Value > 0 loop
Res... | Give a code snippet in #Ada
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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
... | #PowerShell | PowerShell |
function countingSort($array) {
$minmax = $array | Measure-Object -Minimum -Maximum
$min, $max = $minmax.Minimum, $minmax.Maximum
$count = @(0) * ($max - $min + 1)
foreach ($number in $array) {
$count[$number - $min] = $count[$number - $min] + 1
}
$z = 0
foreach ($i in $min..$max... | Give a code snippet in #PowerShell
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 |
Qui... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #PARI.2FGP | PARI/GP | hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x]))); | Give a code snippet in #PARI.2FGP
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| 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.... | #R | R | foo <- function()
{
bar <- function()
{
sys.calls()
}
bar()
}
foo() | Give a code snippet in #R
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 platfo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #Sidef | Sidef | var days = <first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth>;
var gifts = <<'EOT'.lines;
And a partridge in a pear tree.
Two turtle doves,
Three french hens,
Four calling birds,
Five golden rings,
Six geese a-laying,
Seven swans a-swimming,
Eight maids a-milking,
Ni... | Give a code snippet in #Sidef
Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #F.23 | F# | open System.IO
open System.Net
open System.Net.Sockets
let service (client:TcpClient) =
use stream = client.GetStream()
use out = new StreamWriter(stream, AutoFlush = true)
use inp = new StreamReader(stream)
while not inp.EndOfStream do
match inp.ReadLine() with
| line -> printfn "< %s... | Give a code snippet in #F.23
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Racket | Racket |
#lang racket
(for/list ([i 1000])
(add1 (* (sqrt (* -2 (log (random)))) (cos (* 2 pi (random))) 0.5)))
| Give a code snippet in #Racket
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Relate... | 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 ... | #Tcl | Tcl | package require Tcl 8.6
oo::class create Flip {
variable board target s
constructor {size} {
set s $size
set target [my RandomConfiguration]
set board $target
while {$board eq $target} {
for {set i 0} {$i < $s} {incr i} {
if {rand()<.5} {
my SwapRow $i
}
if {rand()<.5} {
my SwapColu... | Give a code snippet in #Tcl
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/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Arturo | Arturo | hq9: function [source][
acc: 0
loop split source 'ch [
case [(lower ch)=]
when? ["h"]-> print "Hello, world!"
when? ["q"]-> print source
when? ["9"]-> print "99 bottles here ..."
when? ["+"]-> acc: acc+1
else []
]
return acc
]
... | Give a code snippet in #Arturo
Task
Implement a HQ9+ interpreter or compiler.
| 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 ... | #Arturo | Arturo | munchausen?: function [n][
n = sum map split to :string n 'digit [
d: to :integer digit
d^d
]
]
loop 1..5000 'x [
if munchausen? x ->
print x
] | Give a code snippet in #Arturo
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/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #XQuery | XQuery | declare function local:fib($n as xs:integer) as xs:integer {
if($n < 2)
then $n
else local:fib($n - 1) + local:fib($n - 2)
}; | Give a code snippet in #XQuery
The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions ar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Maximum_triangle_path_sum | Maximum triangle path sum | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | nums={{55},{94,48},{95,30,96},{77,71,26,67},{97,13,76,38,45},{7,36,79,16,37,68},{48,7,9,18,70,26,6},{18,72,79,46,59,79,29,90},{20,76,87,11,32,7,7,49,18},{27,83,58,35,71,11,25,57,29,85},{14,64,36,96,27,11,58,56,92,18,55},{2,90,3,60,48,49,41,46,33,36,47,23},{92,50,48,2,36,59,42,79,72,20,82,77,42},{56,78,38,80,39,75,2,71,... | Give a code snippet in #Mathematica.2FWolfram_Language
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #Arturo | Arturo | solvePell: function [n][
x: to :integer sqrt n
[y, z, r]: @[x, 1, shl x 1]
[e1, e2]: [1, 0]
[f1, f2]: [0, 1]
while [true][
y: (r * z) - y
z: (n - y * y) / z
r: (x + y) / z
[e1, e2]: @[e2, e1 + e2 * r]
[f1, f2]: @[f2, f1 + f2 * r]
[a, b]: @[e2 + f2 ... | Give a code snippet in #Arturo
Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive... | 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, ... ... | #Crystal | Crystal | require "set"
require "big"
def add_reverse(num, max_iter=1000)
num = num.to_big_i
nums = [] of BigInt
(1..max_iter).each_with_object(Set.new([num])) do |_, nums|
num += reverse_int(num)
nums << num
return nums if palindrome?(num)
end
end
def palindrome?(num)
num == reverse_int(num)
end
def ... | Give a code snippet in #Crystal
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 mos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Fortran | Fortran | program guess_the_number
implicit none
integer :: guess
real :: r
integer :: i, clock, count, n
integer,dimension(:),allocatable :: seed
real,parameter :: rmax = 10
!initialize random number generator:
call random_seed(size=n)
... | Give a code snippet in #Fortran
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/URL_parser | URL parser | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
According to the standards, t... | #Phix | Phix | with javascript_semantics
include builtins/url.e
procedure show_url_details(string uri)
?uri
sequence r = parse_url(uri)
for i=1 to length(r) do
if r[i]!=0 then
string desc = url_element_desc(i)
printf(1,"%s : %v\n",{desc,r[i]})
end if
end for
puts(1,"\n")
e... | Give a code snippet in #Phix
URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
Task
Parse a well-formed URL to retrieve the relevant information: scheme, domain, path, ...
Note: this task has nothing to do with URL encoding or URL decoding.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #mIRC_Scripting_Language | mIRC Scripting Language | alias ttt {
if ($2 isin %ttt) || (!%ttt) {
var %ttt~ = $remove($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X,O)
var %ttt~~ = $replace($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X)
set %ttt $replace(%ttt~~,$iif(($regex(%ttt~~,/(?:O . . (?:(?:. O .|O) . . (\d)|(?:. (\d) .|(\d)) . . O)|(\d) . . (?:. O .|O) . . O|. . (?:O... | Give a code snippet in #mIRC_Scripting_Language
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks | Rosetta Code/Find unimplemented tasks | Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media... | #J | J | require 'strings web/gethttp'
findUnimpTasks=: ('Programming_Tasks' -.&getCategoryMembers ,&'/Omit') ([ #~ -.@e.) getCategoryMembers
getTagContents=: dyad define
'starttag endtag'=. x
('\' -.~ endtag&taketo)&.>@(starttag&E. <@((#starttag)&}.);.1 ]) y
)
NB. RosettaCode Utilities
parseTitles=: ('"title":"';'"')... | Give a code snippet in #J
Task
Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language.
Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.
You'll need to use the Media Wiki API, which you can find out about... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #Red | Red | Red []
m: make map! [] 25000
maxx: 0
foreach word read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt [
sword: sort copy word ;; sorted characters of word
either find m sword [
append m/:sword word
maxx: max maxx length? m/:sword
] [
put m sword append copy [] word
]
]... | Give a code snippet in #Red
When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #Red | Red | Red[]
nth: function [n][
d: n % 10
suffix: either any [d < 1 d > 4 1 = to-integer n / 10] [4] [d]
rejoin [n pick ["st" "nd" "rd" "th"] suffix]
]
test: function [low high][
repeat i high - low + 1 [
prin [nth i + low - 1 ""]
]
prin newline
]
test 0 25
test 250 265
test 1000 1025 | Give a code snippet in #Red
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #OCaml | OCaml | let div_mod n d = (n / d, n mod d)
let join = String.concat ", " ;;
let rec nonzero = function
| _, 0 -> ""
| c, n -> c ^ (spell_integer n)
and tens n =
[| ""; ""; "twenty"; "thirty"; "forty"; "fifty";
"sixty"; "seventy"; "eighty"; "ninety" |].(n)
and small n =
[| "zero"; "one"; "two"; "three... | Give a code snippet in #OCaml
Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than posi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Tcl | Tcl | proc entropy {str} {
set log2 [expr log(2)]
foreach char [split $str ""] {dict incr counts $char}
set entropy 0.0
foreach count [dict values $counts] {
set freq [expr {$count / double([string length $str])}]
set entropy [expr {$entropy - $freq * log($freq)/$log2}]
}
return $entropy
}
puts [f... | Give a code snippet in #Tcl
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Ramanujan%27s_constant | Ramanujan's constant | Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
| #Python | Python | from mpmath import mp
heegner = [19,43,67,163]
mp.dps = 50
x = mp.exp(mp.pi*mp.sqrt(163))
print("calculated Ramanujan's constant: {}".format(x))
print("Heegner numbers yielding 'almost' integers:")
for i in heegner:
print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt... | Give a code snippet in #Python
Calculate Ramanujan's constant (as described on the OEIS site) with at least
32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach,
show that when evaluated with the last four Heegner numbers
the result is almost an integer.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified... | #Perl | Perl | use SOAP::Lite;
print SOAP::Lite
-> service('http://example.com/soap/wsdl')
-> soapFunc("hello");
print SOAP::Lite
-> service('http://example.com/soap/wsdl')
-> anotherSoapFunc(34234); | Give a code snippet in #Perl
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect onc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #REXX | REXX | /*REXX pgm finds integer sided triangles that satisfy Law of cosines for 60º, 90º, 120º.*/
parse arg os1 os2 os3 os4 . /*obtain optional arguments from the CL*/
if os1=='' | os1=="," then os1= 13; s1=abs(os1) /*Not specified? Then use the default.*/
if os2=='' | os2=="," then os2= 13; s2=abs(os2... | Give a code snippet in #REXX
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Java | Java | public static boolean inCarpet(long x, long y) {
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
public static void carpet(final int n) {
final double power = Math.pow(3,n);
for(long i = 0; i < power; i++) {
... | Give a code snippet in #Java
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## ... | 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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Simulates one_of_n_lines a 1000000 times.
local
t: INTEGER
simulator: ARRAY [INTEGER]
do
create simulator.make_filled (0, 1, 10)
create one.make
across
1 |..| 1000000 as c
loop
t := one.one_of_n_lines (10)
simulator [t] := sim... | Give a code snippet in #Eiffel
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 li... | 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... | #Racket | Racket |
#lang racket
(define (get-last-door a b) ; assumes a != b
(vector-ref '#(- 2 1
2 - 0
1 0 -)
(+ a (* 3 b))))
(define (run-game strategy)
(define car-door (random 3))
(define first-choice (random 3))
(define revealed-goat
(if (= car-door first-choice)
... | Give a code snippet in #Racket
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 th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Nim | Nim | var x = ""
if x == "":
echo "empty"
if x != "":
echo "not empty"
# Alternatively:
if x.len == 0:
echo "empty"
if x.len > 0:
echo "not empty" | Give a code snippet in #Nim
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greyscale_bars/Display | Greyscale bars/Display | The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha... | #Raku | Raku | my ($width,$height) = 1280,768;
my $PGM = open "Greyscale-bars-perl6.pgm", :w orelse die "Can't create Greyscale-bars-perl6.pgm: $_";
$PGM.print: qq:to/EOH/;
P2
# Greyscale-bars-perl6.pgm
$width $height
65535
EOH
my ($h1,$h2,$h3,$h4) = divvy($height,4);
my @nums = ((0/7,1/7...7/7) X* 65535)»... | Give a code snippet in #Raku
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we ha... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: line is 0;
var integer: column is 0;
begin
writeln("<table style=\"text-align:center; border: 1px solid\">");
writeln("<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>");
for line range 1 to 3 do
write("<tr><th>" <& li... | Give a code snippet in #Seed7
Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_length | Array length | Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I befo... | #Dragon | Dragon | select "std"
a = ["apple","orange"]
b = length(a)
show b
| Give a code snippet in #Dragon
Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter freq... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Humble_numbers | Humble numbers | Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above is:
humble = 2i × 3j × 5k... | #ALGOL_W | ALGOL W | begin % find some Humble numbers - numbers with no prime factors above 7 %
% returns the minimum of a and b %
integer procedure min ( integer value a, b ) ; if a < b then a else b;
% find and print Humble Numbers %
integer MAX_HUMB... | Give a code snippet in #ALGOL_W
Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the abo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:moveDisc %B !B %C !C %A !A %n !n { n A C B }
$n [
$n 1 - $A $B $C moveDisc
( "Move disc " $n " from pole " $A " to pole " $C ) lprint nl
$n 1 - $B $C $A moveDisc
] if
;
{ Move disc 3 from pole 1 to pole 3, with pole 2 as spare }
3 1 3 2 moveDisc
" " input | Give a code snippet in #Klingphix
Task
Solve the Towers of Hanoi problem with recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha... | #jq | jq | # Input: a non-negative integer, $n
# Output: an array of size $n + 1 such that the nth-mobius number is .[$n]
# i.e. $n|mobius_array[-1]
# For example, the first mobius number could be evaluated by 1|mobius_array[-1].
def mobius_array:
. as $n
| ($n|sqrt) as $sqrt
| reduce range(2; 1 + $sqrt) as $i ([range(0; $n... | Give a code snippet in #jq
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of ... | 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 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Iterator Function Leonardo(Optional L0 = 1, Optional L1 = 1, Optional add = 1) As IEnumerable(Of Integer)
While True
Yield L0
Dim t = L0 + L1 + add
L0 = L1
L1 = t
End While
End Function
Sub Main()
Console.WriteLine(St... | Give a code snippet in #Visual_Basic_.NET
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]
... | 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 ... | #Go | Go | package main
import (
"fmt"
"math"
"math/cmplx"
)
func deg2rad(d float64) float64 { return d * math.Pi / 180 }
func rad2deg(r float64) float64 { return r * 180 / math.Pi }
func mean_angle(deg []float64) float64 {
sum := 0i
for _, x := range deg {
sum += cmplx.Rect(1, deg2rad(x))
}
return rad2deg(cmplx.Ph... | Give a code snippet in #Go
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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
... | #zkl | zkl | fcn countingSort(array, min, max){ // modifies array
count:=(max - min + 1).pump(List().write,0); // array of (max - min + 1) zeros
foreach number in (array){
count[number - min] += 1;
}
z:=-1;
foreach i in ([min .. max]){
do(count[i - min]){ array[z += 1] = i }
}
array
} | Give a code snippet in #zkl
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Subleq | Subleq | Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers... | #CLU | CLU | % Read numbers from a stream
read_nums = iter (s: stream) yields (int)
while true do
c: char := stream$getc(s)
while c~='-' & ~(c>='0' & c<='9') do
c := stream$getc(s)
end
acc: int := 0
neg: bool
if c='-' then
neg := true
c := strea... | Give a code snippet in #CLU
Subleq is an example of a One-Instruction Set Computer (OISC).
It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero.
Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of sign... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #J | J | splitChars=: (1 ,~ 2 ~:/\ ]) <;.2 ]
delimitChars=: ', ' joinstring splitChars | Give a code snippet in #J
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The sa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #Fish | Fish | 0>:n1+v
^o" "< | Give a code snippet in #Fish
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations lim... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Icon_and_Unicon | Icon and Unicon | procedure main()
every writes(lfact(0 | !10)," ")
write()
write()
every write(lfact(20 to 110 by 10))
write()
every writes(*lfact(1000 to 10000 by 1000)," ")
write()
end
procedure lfact(n)
r := 0
f := 1
every (i := !n, r +:= .f, f *:= .i)
return r
end | Give a code snippet in #Icon_and_Unicon
Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n` ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Ring | Ring |
# Project : Rate counter
see "method 1: calculate reciprocal of elapsed time:" + nl
for trial = 1 to 3
start = clock()
tasktomeasure()
finish = clock()
see "rate = " + 100 / (finish-start) + " per second" + nl
next
see "method 2: count completed tasks in one second:" + nl
for trial = 1 to 3
r... | Give a code snippet in #Ring
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish thes... | 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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program jarodist.s */
/* Constantes */
.equ BUFFERSIZE, 100
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 ... | Give a code snippet in #ARM_Assembly
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Swift | Swift | import Foundation
func feigenbaum(iterations: Int = 13) {
var a = 0.0
var a1 = 1.0
var a2 = 0.0
var d = 0.0
var d1 = 3.2
print(" i d")
for i in 2...iterations {
a = a1 + (a1 - a2) / d1
for _ in 1...10 {
var x = 0.0
var y = 0.0
for _ in 1...1<<i {
y = 1.0 -... | Give a code snippet in #Swift
Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Short-circuit_evaluation | Short-circuit evaluation | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, an... | #PARI.2FGP | PARI/GP | a(n)={
print(a"("n")");
a
};
b(n)={
print("b("n")");
n
};
or(A,B)={
a(A) || b(B)
};
and(A,B)={
a(A) && b(B)
}; | Give a code snippet in #PARI.2FGP
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Assume functions a and b return boolean values, and further, the execution of function b takes considerable... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
var MaxIters = 300
var Zoom = 1
var MoveX = 0
var MoveY = 0
var CX = -0.7
var CY = 0.27015
class JuliaSet {
construct new(width, height) {
Window.title = "Julia Set"
Window.resize(width, height)
Canvas.resize(width, height)
... | Give a code snippet in #Wren
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Julia | Julia | isdisarium(n) = sum(last(p)^first(p) for p in enumerate(reverse(digits(n)))) == n
function disariums(numberwanted)
n, ret = 0, Int[]
while length(ret) < numberwanted
isdisarium(n) && push!(ret, n)
n += 1
end
return ret
end
println(disariums(19))
@time disariums(19)
| Give a code snippet in #Julia
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Introspection | Introspection | Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
Extra credit
Repor... | #TI-89_BASIC | TI-89 BASIC | ()
Prgm
Local l, i, vers
getConfg() → l
For i,1,dim(l),2
If l[i] = "OS Version" or l[i] = "Version" Then
l[i + 1] → vers
Disp "Version: " & vers
If expr(right(vers, 4)) < 2005 Then © Lousy parsing strategy
Disp vers & " is too old"
Stop
EndIf
EndIf
EndFor
If ... | Give a code snippet in #TI-89_BASIC
Task
verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Oz | Oz | declare
Inf = 1.0e234 * 1.0e234
MinusInf = 1.0e234 * ~1.0e234
Zero = 1.0 / Inf
MinusZero = 1.0 / MinusInf
NaN = 0.0 / 0.0
{System.showInfo "infinite: "#Inf}
{System.showInfo "-infinite: "#MinusInf}
{System.showInfo "0: "#Zero}
{System.showInfo "-0: "#MinusZero} %% seems to be identical to Zero
{System.showInfo "NaN:... | Give a code snippet in #Oz
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_Chess960_starting_position | Generate Chess960 starting position | Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
W... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var string: start is "RKR";
var char: piece is ' ';
var integer: pos is 0;
begin
for piece range "QNN" do
pos := rand(1, succ(length(start)));
start := start[.. pred(pos)] & str(piece) & start[pos ..];
end for;
pos := ran... | Give a code snippet in #Seed7
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/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 |... | #Befunge | Befunge | &&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="< | Give a code snippet in #Befunge
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 Operation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Search_a_list | Search a list | Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in ... | #Burlesque | Burlesque | blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3 | Give a code snippet in #Burlesque
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #min | min | 1024 :n (n 0 >) (n puts 2 div @n) while | Give a code snippet in #min
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Web_scraping | Web scraping | Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.
If possible,... | #Microsoft_Small_Basic | Microsoft Small Basic |
'Entered by AykayayCiti -- Earl L. Montgomery
url_name = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
url_data = Network.GetWebPageContents(url_name)
find = "UTC"
' the length from the UTC to the time is -18 so we need
' to subtract from the UTC position
pos = Text.GetIndexOf(url_data,find)-18
result = Text.GetSubT... | Give a code snippet in #Microsoft_Small_Basic
Task
Create a program that downloads the time from this URL: http://tycho.usno.navy.mil/cgi-bin/timer.pl and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basic... | #Julia | Julia | // version 1.2.31
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true // would normally be set to false
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.fil... | Give a code snippet in #Julia
Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #MATLAB | MATLAB | mu = 1; sd = 0.5;
x = randn(1000,1) * sd + mu;
| Give a code snippet in #MATLAB
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Relate... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #BASIC | BASIC |
SCREEN 9
H=.5
P=300
FOR I=1 TO 9^6
N=RND
IF N > 2/3 THEN
X=H+X*H:Y=Y*H
ELSEIF N > 1/3 THEN
X=H^2+X*H:Y=H+Y*H
ELSE
X=X*H:Y=Y*H
END IF
PSET(P-X*P,P-Y*P)
NEXT
| Give a code snippet in #BASIC
Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.