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/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:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Sidef | Sidef | var c = ['##']
3.times {
c = (c.map{|x| x * 3 } +
c.map{|x| x + ' '*x.len + x } +
c.map{|x| x * 3 })
}
say c.join("\n") | Give a code snippet in #Sidef
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/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... | #Futhark | Futhark |
fun main(n: int): [n]int = iota n
| Give a code snippet in #Futhark
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/XML/XPath | XML/XPath | Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store #45x10^3">
<section name="heal... | #Delphi | Delphi | program XMLXPath;
{$APPTYPE CONSOLE}
uses ActiveX, MSXML;
const
XML =
'<inventory title="OmniCorp Store #45x10^3">' +
' <section name="health">' +
' <item upc="123456789" stock="12">' +
' <name>Invisibility Cream</name>' +
' <price>14.50</price>' +
' <description>Makes... | Give a code snippet in #Delphi
Perform the following three XPath queries on the XML Document below:
//item[1]: Retrieve the first "item" element
//price/text(): Perform an action on each "price" element (print it out)
//name: Get an array of all the "name" elements
XML Document:
<inventory title="OmniCorp Store ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #GAP | GAP | LookAndSay := function(s)
local c, r, cur, ncur, v;
v := "123";
r := "";
cur := 0;
ncur := 0;
for c in s do
if c = cur then
ncur := ncur + 1;
else
if ncur > 0 then
Add(r, v[ncur]);
Add(r, cur);
fi;
cur := c;
ncur := 1;
fi;
od;
Add(r, v[ncur]);
... | Give a code snippet in #GAP
The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Vector | Vector | Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (length)
The four operations to... | #PL.2FI | PL/I | *process source attributes xref or(!);
vectors: Proc Options(main);
Dcl (v,w,x,y,z) Dec Float(9) Complex;
real(v)=12; imag(v)=-3; Put Edit(pp(v))(Skip,a);
real(v)=6-1; imag(v)=4-1; Put Edit(pp(v))(Skip,a);
real(v)=2*cosd(45);
imag(v)=2*sind(45); Put Edit(pp(v))(Skip,a);
w=v+v; Put Ed... | Give a code snippet in #PL.2FI
Task
Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented.
The Vector may be initialized in any reasonable way.
Start and end points, and direction
Angular coefficient and value (... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never gener... | #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main()
' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).
Dim rand As New Random(0)
Do
Dim first = rand.Next(20) ' Upper bound is exclusive.
Console.Write(first & " ")
If first = 10 Then Exi... | Give a code snippet in #Visual_Basic_.NET
Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #VBScript | VBScript |
option explicit
const tlcr=3, tlcc=3
const maxdim=15
dim a(15,15)
dim b(15,15)
dim ans0:ans0=chr(27)&"["
dim gen,n
erase a
'glider
a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true
'blinker
a(3,13)=true:a(4,13)=true:a(5,13)=true
'beacon
a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true
a(13,3)=true:a... | Give a code snippet in #VBScript
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f... | #Ada | Ada |
generic
type Number is digits <>;
package Euler is
type Waveform is array (Integer range <>) of Number;
function Solve
( F : not null access function (T, Y : Number) return Number;
Y0 : Number;
T0, T1 : Number;
N : Positive
)... | Give a code snippet in #Ada
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Never | Never |
func KtoC(k : float) -> float { k - 273.15 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
func KtoR(k : float) -> float { k * 1.8 }
func convertK(k : float) -> int {
prints("K " + k + "\n");
prints("C " + KtoC(k) + "\n");
prints("F " + KtoF(k) + "\n");
prints("R " + KtoR(k) + "\n");
0
}
... | Give a code snippet in #Never
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_random_chess_position | Generate random chess position | Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squares;
there can not be any p... | #R | R |
place_kings <- function(brd){
###
# Function that puts the two kings on the board
# and makes sure that they are not adjacent
###
while (TRUE) {
# generate positions for white and black kings
rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1)
rank_black <- sample(1:8, 1) ; file_black ... | Give a code snippet in #R
Task
Generate a random chess position in FEN format.
The position does not have to be realistic or even balanced, but it must comply to the following rules:
there is one and only one king of each color (one black king and one white king);
the kings must not be placed on adjacent squar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Kotlin | Kotlin | import java.awt.*
import javax.swing.*
fun main(args: Array<String>) {
JOptionPane.showMessageDialog(null, "Goodbye, World!") // in alert box
with(JFrame("Goodbye, World!")) { // on title bar
layout = FlowLayout()
add(JButton("Goodbye, World!")) // on bu... | Give a code snippet in #Kotlin
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Luca... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | PerfectQ[i_Integer] := Total[Divisors[i]] == 2 i | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #PicoLisp | PicoLisp | (for (N 1 (> 10 N) (+ N 2))
(printsp N) ) | Give a code snippet in #PicoLisp
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Josephus_problem | Josephus problem | Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\displaystyle 0}
,
removing eve... | #Swift | Swift | class Josephus {
class func lineUp(#numberOfPeople:Int) -> [Int] {
var people = [Int]()
for (var i = 0; i < numberOfPeople; i++) {
people.append(i)
}
return people
}
class func execute(#numberOfPeople:Int, spacing:Int) -> Int {
var killIndex = 0
... | Give a code snippet in #Swift
Josephus problem is a math puzzle with a grim description:
n
{\displaystyle n}
prisoners are standing on a circle, sequentially numbered from
0
{\displaystyle 0}
to
n
−
1
{\displaystyle n-1}
.
An executioner walks along the circle, starting from prisoner
0
{\... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abbreviations,_automatic | Abbreviations, automatic | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbrevia... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::... | Give a code snippet in #C.2B.2B
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters... | #Fortran | Fortran |
Crunches a set of hourly data. Starts with a date, then 24 pairs of value,indicator for that day, on one line.
INTEGER Y,M,D !Year, month, and day.
INTEGER GOOD(24,2) !The indicators.
REAL*8 V(24,2) !The grist.
CHARACTER*10 DATE(2) !Along with the starting date.
INTEGER IT,TI !A fl... | Give a code snippet in #Fortran
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be on... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaini... | #Emacs_Lisp | Emacs Lisp | (defun reverse-sep (words sep)
(mapconcat 'identity (reverse (split-string words sep)) sep))
(defun reverse-chars (line)
(reverse-sep line ""))
(defun reverse-words (line)
(reverse-sep line " "))
(defvar line "rosetta code phrase reversal")
(with-output-to-temp-buffer "*reversals*"
(princ (reverse-chars... | Give a code snippet in #Emacs_Lisp
Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.... | #Lua | Lua | -- Returns a boolean indicating whether n is prime
function isPrime (n)
if n < 2 then return false end
if n < 4 then return true end
if n % 2 == 0 then return false end
for d = 3, math.sqrt(n), 2 do
if n % d == 0 then return false end
end
return true
end
-- Returns a table of the prime... | Give a code snippet in #Lua
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are al... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Scratch | Scratch |
when flag clicked # when program is run
set counter to "0" # initialize counter object to zero
set message to "There have been no clicks"
show variable message # show the message object
when this sprite clicked # when button clicked
hide message # hide the initial message
chang... | Give a code snippet in #Scratch
Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_common_substring | Longest common substring | Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string.... | #Ada | Ada | with Ada.Text_Io;
procedure Longest_Common_Substring is
function Common (Left, Right: String) return String is
Com : array (Left'Range, Right'Range) of Natural := (others => (others => 0));
Longest : Natural := 0;
Last : Natural := 0;
begin
for L in Left'Range loop
for R in... | Give a code snippet in #Ada
Task
Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutiv... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Non-decimal_radices/Input | Non-decimal radices/Input | It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing of such a string (which may be ass... | #ALGOL_68 | ALGOL 68 | main:
(
FILE fbuf; STRING sbuf;
OP FBUF = (STRING in sbuf)REF FILE: (
sbuf := in sbuf;
associate(fbuf, sbuf);
fbuf
);
BITS num;
getf(FBUF("0123459"), ($10r7d$, num));
printf(($gl$, ABS num)); # prints 123459 #
getf(FBUF("abcf123"), ($16r7d$, num));
printf(($gl$, ABS num)); # prints... | Give a code snippet in #ALGOL_68
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.)
This task requires parsing ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_Eck_sequence | Van Eck sequence | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
Example
Using ... | #Picat | Picat | main =>
Limit = 1000,
A = new_array(Limit+1),
bind_vars(A,0),
foreach(N in 1..Limit-1)
M = find_last_of(A[1..N],A[N+1]),
if M > 0 then
A[N+2] := N-M+1
end
end,
println(A[1..10]),
println(A[991..1000]),
nl. | Give a code snippet in #Picat
The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Sparkling | Sparkling | function call_me(func, arg) {
return func(arg);
}
let answer = call_me(function(x) { return 6 * x; }, 7);
print(answer); | Give a code snippet in #Sparkling
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Bioinformatics/base_count | Bioinformatics/base count | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTG... | #C | C |
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct genome{
char* strand;
int length;
struct genome* next;
}genome;
genome* genomeData;
int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;
int numDigits(int num){
int len = 1;
while(num>10){
n... | Give a code snippet in #C
Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGAT... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #DWScript | DWScript | function IsMersennePrime(p : Integer) : Boolean;
var
i, s, m_p : Integer;
begin
if p=2 then
Result:=True
else begin
m_p := (1 shl p)-1;
s := 4;
for i:=3 to p do
s:=(s*s-2) mod m_p;
Result:=(s=0);
end;
end;
const upperBound = Round(Log2(High(Integer))/2);
PrintLn('F... | Give a code snippet in #DWScript
Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Kotlin | Kotlin | // version 1.1.2
/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin */
fun isExactPalindrome(s: String) = (s == s.reversed())
fun isInexactPalindrome(s: String): Boolean {
var t = ""
for (c in s) if (c.isLetterOrDigit()) t += c
t = t.toLowerCase()
return... | Give a code snippet in #Kotlin
A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Icon_and_Unicon | Icon and Unicon | #
# piped.icn, Get system command output
#
# Dedicated to the public domain
#
procedure main()
# start with an empty list
directory := []
# ls for UNIX, dir for other, assume Windows
command := if &features == "UNIX" then "ls" else "dir"
# open command in pipe mode
p := open(command, "p") | ... | Give a code snippet in #Icon_and_Unicon
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Objeck | Objeck | interface Thingable {
method : virtual : public : Thing() ~ String;
}
class Delegator {
@delegate : Thingable;
New() {
}
method : public : SetDelegate(delegate : Thingable) ~ Nil {
@delegate := delegate;
}
method : public : Operation() ~ String {
if(@delegate = Nil) {
return "defa... | Give a code snippet in #Objeck
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #Commodore_BASIC | Commodore BASIC | 100 NV=0: REM NUMBER OF VERTICES
110 READ N$:IF N$<>"" THEN NV=NV+1:GOTO 110
120 NE=0: REM NUMBER OF EDGES
130 READ N1:IF N1 >= 0 THEN READ N2,W:NE=NE+1:GOTO 130
140 DIM VN$(NV-1),VD(NV-1,2): REM VERTEX NAMES AND DATA
150 DIM ED(NE-1,2): REM EDGE DATA
160 RESTORE
170 FOR I=0 TO NV-1
180 : READ VN$(I): REM VERTEX NAME
... | Give a code snippet in #Commodore_BASIC
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sid... | #Delphi | Delphi | program ABC;
{$APPTYPE CONSOLE}
uses SysUtils;
type
TBlock = set of char;
const
TheBlocks : array [0..19] of TBlock =
(
[ 'B', 'O' ], [ 'X', 'K' ], [ 'D', 'Q' ], [ 'C', 'P' ], [ 'N', 'A' ],
[ 'G', 'T' ], [ 'R', 'E' ], [ 'T', 'G' ], [ 'Q', 'D' ], [ 'F', 'S' ],
[ 'J', 'W' ]... | Give a code snippet in #Delphi
ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphab... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #AppleScript | AppleScript | ----------------------- DOT PRODUCT -----------------------
-- dotProduct :: [Number] -> [Number] -> Number
on dotProduct(xs, ys)
if length of xs = length of ys then
sum(zipWith(my mul, xs, ys))
else
missing value -- arrays of differing dimension
end if
end dotProduct
-----------------... | Give a code snippet in #AppleScript
Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Perl | Perl | use ntheory qw/factor vecmax/;
use threads;
use threads::shared;
my @results :shared;
my $tnum = 0;
$_->join() for
map { threads->create('tfactor', $tnum++, $_) }
(qw/576460752303423487 576460752303423487 576460752303423487 112272537195293
115284584522153 115280098190773 115797840077099 112582718962171 29986611... | Give a code snippet in #Perl
Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Rust | Rust | /* Uses C library interface */
extern crate libc;
fn main() {
let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0;
if istty {
println!("stdout is tty");
} else {
println!("stdout is not tty");
}
} | Give a code snippet in #Rust
Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett... | #Haskell | Haskell | import Data.List (sortBy, groupBy)
import Text.Printf (printf)
import Data.Ord (comparing)
import Data.Function (on)
type ID = Int
type DEP = String
type NAME = String
type SALARY = Double
data Employee = Employee
{ nr :: ID
, dep :: DEP
, name :: NAME
, sal :: SALARY
}
employees :: [Employe... | Give a code snippet in #Haskell
Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee I... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection | Factorial base numbers indexing permutations of a collection | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.... | #Haskell | Haskell | import Data.List (unfoldr, intercalate)
newtype Fact = Fact [Int]
-- smart constructor
fact :: [Int] -> Fact
fact = Fact . zipWith min [0..] . reverse
instance Show Fact where
show (Fact ds) = intercalate "." $ show <$> reverse ds
toFact :: Integer -> Fact
toFact 0 = Fact [0]
toFact n = Fact $ unfoldr f (1, n... | Give a code snippet in #Haskell
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Apply_a_callback_to_an_array | Apply a callback to an array | Task
Take a combined set of elements and apply a function to each element.
| #Oforth | Oforth | 0 #+ [ 1, 2, 3, 4, 5 ] apply | Give a code snippet in #Oforth
Task
Take a combined set of elements and apply a function to each element.
| 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... | #M4 | M4 | $ m4
define(`f',`$1`'$3`'$3`'$2')
==>
f(`Rosetta',`Code',`:')
==>Rosetta::Code
m4exit | Give a code snippet in #M4
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/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Seed7 | Seed7 | repeat with each item of [True, False, Yes, No, On, Off, ""]
put it & " is " & (it is true)
end repeat
| Give a code snippet in #Seed7
Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Processing | Processing | println("Hello world!"); | Give a code snippet in #Processing
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard er... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #PureBasic | PureBasic | Procedure PrintFactors(n)
Protected i, lim=Round(sqr(n),#PB_Round_Up)
NewList F.i()
For i=1 To lim
If n%i=0
AddElement(F()): F()=i
AddElement(F()): F()=n/i
EndIf
Next
;- Present the result
SortList(F(),#PB_Sort_Ascending)
ForEach F()
Print(str(F())+" ")
Next
EndProcedure
If Ope... | Give a code snippet in #PureBasic
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 Operati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Euler_Math_Toolbox | Euler Math Toolbox |
>ggt(123456795,1234567851)
33
>function myggt (n:index, m:index) ...
$ if n<m then {n,m}={m,n}; endif;
$ repeat
$ k=mod(n,m);
$ if k==0 then return m; endif;
$ if k==1 then return 1; endif;
$ {n,m}={m,k};
$ end;
$ endfunction
>myggt(123456795,1234567851)
33
| Give a code snippet in #Euler_Math_Toolbox
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #Liberty_BASIC | Liberty BASIC |
dim info$( 50, 50) ' NB pre-dimension before calling file-exists
' needed for file-exists function
open "test.dat" for output as #1 'create file
for i = 1 to 10000
#1 chr$( int( 256 *rnd( 1)));
next
close #1
call truncateFile, "test.dat", 5000
wait
sub trunca... | Give a code snippet in #Liberty_BASIC
Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Scala | Scala |
object NQueens {
private implicit class RichPair[T](
pair: (T,T))(
implicit num: Numeric[T]
) {
import num._
def safe(x: T, y: T): Boolean =
pair._1 - pair._2 != abs(x - y)
}
def solve(n: Int): Iterator[Seq[Int]] = {
(0 to n-1)
.permutations
.filter { v =>
(... | Give a code snippet in #Scala
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #Applesoft_BASIC | Applesoft BASIC | 100 S = 5
110 S2 = S ^ 2 : REM SQUARED
120 H = S2 / 2 : REM HALFWAY
130 S2 = S2 - 1
140 DX = 1 : REM INITIAL
150 DY = 0 : REM DIRECTION
160 N = S - 1
170 DIM A%(N, N)
200 FOR I = 0 TO H
210 A%(X, Y) = I
220 A%(N - X, N - Y) = S2 - I
230 X = X + DX
240 Y = Y + DY
250 IF Y = 0 THEN DY = DY + 1 : IF ... | Give a code snippet in #Applesoft_BASIC
Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneous... | #AutoHotkey | AutoHotkey | #SingleInstance, Force
#NoEnv
SetBatchLines, -1
File := "Wireworld.txt"
CellSize := 20
CellSize2 := CellSize - 2
C1 := 0xff000000
C2 := 0xff0066ff
C3 := 0xffd40055
C4 := 0xffffcc00
if (!FileExist(File)) {
MsgBox, % "File(" File ") is not present."
ExitApp
}
; Uncomment if Gdip.ahk is not in your standard library
... | Give a code snippet in #AutoHotkey
Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #JavaScript | JavaScript | var s = "hello"
print(s + " there!") | Give a code snippet in #JavaScript
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another strin... | 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... | #Lhogho | Lhogho | make "str " ;make null-string word
print empty? :str ;prints 'true'
print not empty? :str ;prints 'false'
| Give a code snippet in #Lhogho
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.
Ot... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #PARI.2FGP | PARI/GP | vector(100,X,numdiv(X)) | Give a code snippet in #PARI.2FGP
Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum pos... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[B10]
B10[n_Integer] := Module[{i, out},
i = 1;
While[! Divisible[FromDigits[IntegerDigits[i, 2], 10], n],
i++;
];
out = FromDigits[IntegerDigits[i, 2], 10];
Row@{n, " x ", out/n, " = ", out}
]
Table[B10[i], {i, Range[10]}] // Column
Table[B10[i], {i, 95, 105}] // Column
B10[297]
B10[576]
B10[594... | Give a code snippet in #Mathematica.2FWolfram_Language
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case... | #VBScript | VBScript | Max=250
For X0=1 To Max
For X1=1 To X0
For X2=1 To X1
For X3=1 To X2
Sum=fnP5(X0)+fnP5(X1)+fnP5(X2)+fnP5(X3)
S1=Int(Sum^0.2)
If Sum=fnP5(S1) Then
WScript.StdOut.Write X0 & " " & X1 & " " & X2 & " " & X3 & " " & S1
WScript.Quit
End If
Next
Next
Next
Next
Function fnP5(n)
fnP5 =... | Give a code snippet in #VBScript
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth powe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Kotlin | Kotlin | // Kotlin JS version 1.1.4-3
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
} | Give a code snippet in #Kotlin
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #Oberon-2 | Oberon-2 |
MODULE DigitsSquaring;
IMPORT
Out;
VAR
i,hits89: LONGINT;
PROCEDURE Squaring(n: LONGINT): LONGINT;
VAR
d, sum: LONGINT;
BEGIN
LOOP
sum := 0;
WHILE n > 0 DO
d := n MOD 10;
INC(sum,d * d);
n := n DIV 10
END;
IF (sum = 1) OR (sum = 89) THEN EXIT END;
... | Give a code snippet in #Oberon-2
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural n... | #uBasic.2F4tH | uBasic/4tH | Dim @y(30)
@y(0) = 1
@y(1) = 2
@y(2) = 3
For i = 3 To 29
k = 3
Do
k = k + 1
If (FUNC(_gcd(k, @y(i-2))) = 1) + (FUNC(_gcd(k, @y(i-1))) > 1) Then
Continue
EndIf
For j = 0 To i - 1
If @y(j) = k Then Unloop : Continue
Next
@y(i) = k : Break
Loop
Next
For i = 0 To 29
Pri... | Give a code snippet in #uBasic.2F4tH
The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Java | Java | import java.util.Stack;
public class PostfixToInfix {
public static void main(String[] args) {
for (String e : new String[]{"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^"}) {
System.out.printf("Postfix : %s%n", e);
System.out.printf("Infix : %s%n", postfixToInfi... | Give a code snippet in #Java
Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #Metal | Metal | void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end);
void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end)
{
int x = int(start.x);
int y = int(start.y);
int dx = abs(x - int(end.x));
int dy = abs(y - int(end.y));
int sx = start.x ... | Give a code snippet in #Metal
Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #C.2B.2B | C++ | template<typename T> void swap(T& left, T& right)
{
T tmp(left);
left = right;
right = tmp;
} | Give a code snippet in #C.2B.2B
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides generic... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters | Idiomatically determine all the lowercase and uppercase letters |
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
Task requirements
Display the set of... | #Common_Lisp | Common Lisp |
(flet ((do-case (converter)
;; A = 10, B = 11, ... Z = 35
(loop for radix from 10 to 35
for char = (funcall converter (digit-char radix 36)) do
(format t "~&~8D #\\~24A ~S"
;; The codes and names vary across systems
(char-code c... | Give a code snippet in #Common_Lisp
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to... | #Phix | Phix | with javascript_semantics
sequence alpha_b = repeat(0,255)
alpha_b['A'..'Z'] = 'A'
alpha_b['a'..'z'] = 'a'
function caesar(string s, integer key)
integer ch, base
for i=1 to length(s) do
ch = s[i]
base = alpha_b[ch]
if base then
s[i] = base+remainder(ch-base+k... | Give a code snippet in #Phix
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Wart | Wart | a <- '(1 2 3)
b <- '(4 5 6)
a+b
# => (1 2 3 4 5 6) | Give a code snippet in #Wart
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not u... | #ALGOL_68 | ALGOL 68 | BEGIN # find Duffinian numbers: non-primes relatively prime to their divisor count #
INT max number := 500 000; # largest number we will consider #
# iterative Greatest Common Divisor routine, returns the gcd of m and n #
PROC gcd = ( INT m, n )INT:
BEGIN
INT a ... | Give a code snippet in #ALGOL_68
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
... | #Fortran | Fortran | program Pancake_Demo
implicit none
integer :: list(8) = (/ 1, 4, 7, 2, 5, 8, 3, 6 /)
call Pancake_sort(list)
contains
subroutine Pancake_sort(a)
integer, intent(in out) :: a(:)
integer :: i, maxpos
write(*,*) a
do i = size(a), 2, -1
! Find position of max number between index 1 and i
max... | 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/Sorting_algorithms/Cocktail_sort_with_shifting_bounds | Sorting algorithms/Cocktail sort with shifting bounds |
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
... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub cocktail_sort {
my @a = @_;
my ($min, $max) = (0, $#a-1);
while (1) {
my $swapped_forward = 0;
for my $i ($min .. $max) {
if ($a[$i] gt $a[$i+1]) {
@a[$i, $i+1] = @a[$i+1, $i];
$swapped_forward = 1... | Give a code snippet in #Perl
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 sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Pike | Pike | int main(){
mv("input.txt", "output.txt");
mv("/input.txt", "/output.txt");
mv("docs", "mydocs");
mv("/docs", "/mydocs");
} | Give a code snippet in #Pike
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rig... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polynomial_regression | Polynomial regression | Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is i... | #Maple | Maple | with(CurveFitting);
PolynomialInterpolation([[0, 1], [1, 6], [2, 17], [3, 34], [4, 57], [5, 86], [6, 121], [7, 162], [8, 209], [9, 262], [10, 321]], 'x');
| Give a code snippet in #Maple
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #PHP | PHP | <?php
class CatalanNumbersSerie
{
private static $cache = array(0 => 1);
private function fill_cache($i)
{
$accum = 0;
$n = $i-1;
for($k = 0; $k <= $n; $k++)
{
$accum += $this->item($k)*$this->item($n-$k);
}
self::$cache[$i] = $accum;
}
function item($i)
{
if (!isset(s... | Give a code snippet in #PHP
Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
fo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #SIMPOL | SIMPOL | if x == 1
foo()
else if x == 2
bar()
else
foobar()
end if | Give a code snippet in #SIMPOL
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k... | #zkl | zkl | foreach p in (10){
faulhaberFormula(p).apply("%7s".fmt).concat().println();
}
// each term of faulhaberFormula is BigInt/BigInt
[1..].zipWith(fcn(n,rat){ rat*BN(1000).pow(n) }, faulhaberFormula(17))
.walk() // -->(0, -3617/60 * 1000^2, 0, 595/3 * 1000^4 ...)
.reduce('+) // rat + rat + ...
.println(); | Give a code snippet in #zkl
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #R | R | cat("Hello world!\n") | Give a code snippet in #R
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
He... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. rot-13.
DATA DIVISION.
LOCAL-STORAGE SECTION.
78 STR-LENGTH VALUE 100.
78 normal-lower VALUE "abcdefghijklmnopqrstuvwxyz".
78 rot13-lower VALUE "nopqrstuvwxyzabcdefghijklm".
78 normal-upper VALUE "ABCDEFGHIJKLMNOPQ... | Give a code snippet in #COBOL
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Factor | Factor | USING: arrays formatting kernel math math.text.utils sequences ;
IN: rosetta-code.digital-root
: digital-root ( n -- persistence root )
0 swap [ 1 digit-groups dup length 1 > ] [ sum [ 1 + ] dip ]
while first ;
: print-root ( n -- )
dup digital-root
"%-12d has additive persistence %d and digital roo... | Give a code snippet in #Factor
The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #SETL | SETL | program life;
const
initialMatrix =
[".....",
"..#..",
"...#.",
".###.",
"....."];
loop
init
s := initialLiveSet();
do
output(s);
nm := {[[x+dx, y+dy], [x, y]]: [x, y] in s, dx in {-1..1}, dy in {-1..1}};
s := {c: t = nm{c} | 3 in {#t, #(t less c)}};
end;
proc output(s);
system... | Give a code snippet in #SETL
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Octave | Octave | a = [1, 3, -5]
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
disp( a * b' ) % ' means transpose | Give a code snippet in #Octave
Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #LabVIEW | LabVIEW |
{def mean
{lambda {:s}
{if {S.empty? :s}
then 0
else {/ {+ :s} {S.length :s}}}}}
{mean {S.serie 0 1000}}
-> 500
| Give a code snippet in #LabVIEW
Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an es... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Common_Lisp | Common Lisp | (expt (expt 5 3) 2)
(expt 5 (expt 3 2)) | Give a code snippet in #Common_Lisp
This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the random... | #Julia | Julia | function cowsbulls()
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
You get one bull for every right number in the right position.\n
You get one cow for every right number, but in the wrong position.\n
Enter 'n' to pick a new number and 'q... | Give a code snippet in #Julia
Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Num... | #F.23 | F# |
(*
Encode and Decode using StraddlingCheckerboard
Nigel Galloway May 15th., 2017
*)
type G={n:char;i:char;g:System.Collections.Generic.Dictionary<(char*char),string>;e:System.Collections.Generic.Dictionary<char,string>}
member G.encode n=n|>Seq.map(fun n->if (n='/') then G.e.['/']+string n else match (G.e.TryG... | Give a code snippet in #F.23
Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #C.2B.2B | C++ | #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>
std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
const auto maximum = std::max_element(numbers, numbers + num);
const auto minimum = std::min_element(numbers, numbers + num);
return std::mak... | Give a code snippet in #C.2B.2B
Task
Show how to return more than one value from a function.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
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
... | #Ring | Ring | aArray = [2,4,3,1,2]
see sort(aArray) | Give a code snippet in #Ring
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 sor... | 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... | #FreeBASIC | FreeBASIC | function mobius( n as uinteger ) as integer
if n = 1 then return 1
for d as uinteger = 2 to int(sqr(n))
if n mod d = 0 then
if n mod (d*d) = 0 then return 0
return -mobius(n/d)
end if
next d
return -1
end function
dim as string outstr = " . "
for i as uinte... | Give a code snippet in #FreeBASIC
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #REXX | REXX | /*REXX program adds and multiplies N elements of a (populated) array @. */
numeric digits 200 /*200 decimal digit #s (default is 9).*/
parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/
do j=1 for N /*build array of N elements (or 20... | Give a code snippet in #REXX
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Rust | Rust | // [dependencies]
// primal = "0.3"
fn main() {
let limit = 1000;
let mut sum = 0;
println!("count prime sum");
for (n, p) in primal::Sieve::new(limit)
.primes_from(2)
.take_while(|x| *x < limit)
.enumerate()
{
sum += p;
if primal::is_prime(sum as u64)... | Give a code snippet in #Rust
Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Lisaac | Lisaac | { "SPAM\n".print; }.endless_loop;
| Give a code snippet in #Lisaac
Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked ... | #Delphi | Delphi | uses system ;
type
// declare the list pointer type
plist = ^List ;
// declare the list type, a generic data pointer prev and next pointers
List = record
data : pointer ;
next : pList ;
end;
// since this task is just showing the traversal I am not allocating the memory and setting up... | Give a code snippet in #Delphi
Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Defini... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Continuous | Knapsack problem/Continuous |
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after... | #D | D | import std.stdio, std.algorithm, std.string;
struct Item {
string name;
real amount, value;
@property real valuePerKG() @safe const pure nothrow @nogc {
return value / amount;
}
string toString() const pure /*nothrow*/ @safe {
return format("%10s %7.2f %7.2f %7.2f",
... | Give a code snippet in #D
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the ite... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis | Vigenère cipher/Cryptanalysis | Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS... | #Python | Python | from string import uppercase
from operator import itemgetter
def vigenere_decrypt(target_freqs, input):
nchars = len(uppercase)
ordA = ord('A')
sorted_targets = sorted(target_freqs)
def frequency(input):
result = [[c, 0.0] for c in uppercase]
for c in input:
result[c - or... | Give a code snippet in #Python
Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUX... | 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
| #Phix | Phix | without js -- command_line, file i/o
function entropy(sequence s)
sequence symbols = {},
counts = {}
integer N = length(s)
for i=1 to N do
object si = s[i]
integer k = find(si,symbols)
if k=0 then
symbols = append(symbols,si)
counts = append(count... | Give a code snippet in #Phix
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Four_bit_adder | Four bit adder | Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands ... | #UNIX_Shell | UNIX Shell | xor() {
typeset -i a=$1 b=$2
printf '%d\n' $(( (a || b) && ! (a && b) ))
}
half_adder() {
typeset -i a=$1 b=$2
printf '%d %d\n' $(xor $a $b) $(( a && b ))
}
full_adder() {
typeset -i a=$1 b=$2 c=$3
typeset -i ha0_s ha0_c ha1_s ha1_c
read ha0_s ha0_c < <(half_adder "$c" "$a")
read ha1_s ha1_c < <(h... | Give a code snippet in #UNIX_Shell
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Go | Go | package main
import (
"fmt"
"strings"
)
// R1: representation is a slice of int8 digits of -1, 0, or 1.
// digit at index 0 is least significant. zero value of type is
// representation of the number 0.
type bt []int8
// R2: string conversion:
// btString is a constructor. valid input is a string of a... | Give a code snippet in #Go
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semordnilap | Semordnilap | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap ... | #Oforth | Oforth | : semordnilap
| w wr wrds |
ListBuffer new ->wrds
ListBuffer new
File new("unixdict.txt") forEach: w [
wrds include(w reverse dup ->wr) ifTrue: [ [wr, w] over add ]
w wr < ifTrue: [ wrds add(w) ]
] ; | Give a code snippet in #Oforth
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: lager and regal
Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the tot... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to... | #F.23 | F# | module caesar =
open System
let private cipher n s =
let shift c =
if Char.IsLetter c then
let a = (if Char.IsLower c then 'a' else 'A') |> int
(int c - a + n) % 26 + a |> char
else c
String.map shift s
let encrypt n = cipher n
... | Give a code snippet in #F.23
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #jq | jq | (t|flatten) == (s|flatten) | Give a code snippet in #jq
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Break | Loops/Break | Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never gener... | #Arturo | Arturo | while ø [
a: random 0 19
prints [a ""]
if a=10 -> break
b: random 0 19
print b
]
print "" | Give a code snippet in #Arturo
Task
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Archimedean_spiral | Archimedean spiral |
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| #Java | Java | import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class ArchimedeanSpiral extends JPanel {
public ArchimedeanSpiral() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
void drawGrid(Graphics2D g) {
g.setColor(new Color(0xEE... | Give a code snippet in #Java
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
r
=
a
+
b
θ
{\displaystyle \,r=a+b\theta }
with real numbers a and b.
Task
Draw an Archimedean spiral.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #6502_Assembly | 6502 Assembly | CMP_Double .macro ;NESASM3 syntax
; input:
; \1 = first condition. Valid addressing modes: immediate, zero page, or absolute.
; \2 = second condition. Valid addressing modes: immediate, zero page, or absolute.
; \3 = branch here if both are true
; \4 = branch here if only first condition is true
; \5 = branch here i... | Give a code snippet in #6502_Assembly
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languag... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #Scala | Scala | import scala.actors.Actor.{actor, loop, reactWithin, exit}
import scala.actors.TIMEOUT
import scala.swing.{SimpleSwingApplication, MainFrame, Label}
import scala.swing.event.MouseClicked
case object Revert
object BasicAnimation extends SimpleSwingApplication {
val label = new Label("Hello World! ")
val rotator ... | Give a code snippet in #Scala
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment... | #Ursala | Ursala | #import std
#import nat
#import flo
treatment_group = <85,88,75,66,25,29,83,39,97>
control_group = <68,41,10,49,16,65,32,92,28,98>
f = # returns the fractions of alternative mean differences above and below the actual
float~*; -+
vid^~G(plus,~&)+ (not fleq@rlX)*|@htX; ~~ float+ length,
minus*+ mean^~*C/~&... | Give a code snippet in #Ursala
Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[optim, aux]
optim[a_List] := Module[{u, v, n, c, r, s},
n = Length[a] - 1;
u = ConstantArray[0, {n, n}];
v = ConstantArray[\[Infinity], {n, n}];
u[[All, 1]] = -1;
v[[All, 1]] = 0;
Do[
Do[
Do[
c =
v[[i, k]] + v[[i + k, j - k]] + a[[i]] a[[i + k]] a[[i + j]];
If[c < v[[i, j]]... | Give a code snippet in #Mathematica_.2F_Wolfram_Language
Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An de... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin primality test or Rabin–Miller prima... | #FreeBASIC | FreeBASIC | ' version 29-11-2016
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt
' retur... | Give a code snippet in #FreeBASIC
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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)
The Miller–Rabin p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Jsish | Jsish | /* Determine if only one instance, in Jsish */
var sock;
try {
sock = new Socket({client:false, port:54321});
puts('\nApplication running for 30 seconds, from', strftime());
update(30000);
puts('\nApplication ended at', strftime());
} catch (err) {
puts('Applicaion already running');
exit(1);
... | Give a code snippet in #Jsish
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #BQN | BQN | Uniq ← ⍷
•Show uniq {𝕎𝕩} 5‿6‿7‿5 | Give a code snippet in #BQN
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.