task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #E | E | def makeColor(name :String) {
def color {
to colorize(thing :String) {
return `$name $thing`
}
}
return color
} |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #EchoLisp | EchoLisp |
(lib 'gloops) ; load oo library
(define-class Person null (name (age :initform 66)))
(define-method tostring (Person) (lambda (p) ( format "🚶 %a " p.name)))
(define-method mailto (Person Person) (lambda( p o) (printf "From %a to️ %a : ..." p o)))
;; define a sub-class of Person with same methods
(define-class ... |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Ruby | Ruby | def initN
n = Array.new(15){Array.new(11, ' ')}
for i in 1..15
n[i - 1][5] = 'x'
end
return n
end
def horiz(n, c1, c2, r)
for c in c1..c2
n[r][c] = 'x'
end
end
def verti(n, r1, r2, c)
for r in r1..r2
n[r][c] = 'x'
end
end
def diagd(n, c1, c2, r)
for c in... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Haskell | Haskell | import Data.List (minimumBy, tails, unfoldr, foldl1') --'
import System.Random (newStdGen, randomRs)
import Control.Arrow ((&&&))
import Data.Ord (comparing)
vecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2
findClosestPair =
foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) .
conc... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Objective-C | Objective-C | NSMutableArray *funcs = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[funcs addObject:[^ { return i * i; } copy]];
}
int (^foo)(void) = funcs[3];
NSLog(@"%d", foo()); // logs "9"
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #OCaml | OCaml | let () =
let cls = Array.init 10 (fun i -> (function () -> i * i)) in
Random.self_init ();
for i = 1 to 6 do
let x = Random.int 9 in
Printf.printf " fun.(%d) = %d\n" x (cls.(x) ());
done |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Sidef | Sidef | func is_circular_prime(n) {
n.is_prime || return false
var circular = n.digits
circular.min < circular.tail && return false
for k in (1 ..^ circular.len) {
with (circular.rotate(k).digits2num) {|p|
(p.is_prime && (p >= n)) || return false
}
}
return true
}
say... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #C.23 | C# | using System;
public class CirclesOfGivenRadiusThroughTwoPoints
{
public static void Main()
{
double[][] values = new double[][] {
new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 },
new [] { 0.0, 2.0, 0.0, 0.0, 1 },
new [] { 0.1234, 0.9876, 0.1234, 0.9876, ... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #BASIC256 | BASIC256 |
# Chinese zodiac
elementos = {"Wood", "Fire", "Earth", "Metal", "Water"}
animales = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}
aspectos = {"Yang","Yin"}
tallo_celestial = {'甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'}
rama_terrestre = {'子','丑','寅','卯'... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #Befunge | Befunge | 0" :raeY">:#,_55+"< /8"&>+:66+%00p:55+v
v"Aspect: "0++88*5%2\0\+1%"<":p01++66/2%<
>00g5g7-0" :laminA"10g5g"<"+0" :tnemelE"v
v!:,+55$_v#!-*84,:g+5/< >:#,_$.,,.,@ >0#<
_>>:#,_$>>1+::"("%\"("^ ^"Cycle: " <<<<
$'-4;AGLS[_ %*06yang yin Rat Ox Tiger R |
abbit Dragon Snake Horse Goat Monkey Roo |
ster Dog Pig Wood F... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program verifFic64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Action.21 | Action! | BYTE lastError
PROC MyError(BYTE errCode)
lastError=errCode
RETURN
BYTE FUNC FileExists(CHAR ARRAY fname)
DEFINE PTR="CARD"
PTR old
BYTE dev=[1]
lastError=0
old=Error
Error=MyError ;replace error handling to capture I/O error
Close(dev)
Open(dev,fname,4)
Close(dev)
Error=old ;restore the... |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Factor | Factor |
IN: scratchpad USE: unix.ffi
IN: scratchpad 1 isatty
--- Data stack:
1
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #FreeBASIC | FreeBASIC |
Open Cons For Output As #1
' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar
' de la consola para leer o escribir.
If Err > 0 Then
Print #1, "stdout is not a tty."
Else
Print #1, "stdout is a tty."
End If
Close #1
Sleep
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Go | Go | package main
import (
"os"
"fmt"
)
func main() {
if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal")
}
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Haskell | Haskell | module Main where
-- requires the unix package
-- https://hackage.haskell.org/package/unix
import System.Posix.Terminal (queryTerminal)
import System.Posix.IO (stdOutput)
main :: IO ()
main = do
istty <- queryTerminal stdOutput
putStrLn
(if istty
then "stdout is tty"
else "stdout is not tty") |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Clojure | Clojure | (defn cholesky
[matrix]
(let [n (count matrix)
A (to-array-2d matrix)
L (make-array Double/TYPE n n)]
(doseq [i (range n) j (range (inc i))]
(let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))]
(aset L i j (if (= i j)
(Math/sqrt (- (aget A i i... |
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
| #FreeBASIC | FreeBASIC |
Open Cons For Input As #1
' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar
' de la consola para leer o escribir.
If Err Then
Print "Input doesn't come from tt."
Else
Print "Input comes from tty."
End If
Close #1
Sleep
|
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
| #Go | Go | package main
import (
"golang.org/x/crypto/ssh/terminal"
"fmt"
"os"
)
func main() {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
} |
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
| #Haskell | Haskell | module Main (main) where
import System.Posix.IO (stdInput)
import System.Posix.Terminal (queryTerminal)
main :: IO ()
main = do
isTTY <- queryTerminal stdInput
putStrLn $ if isTTY
then "stdin is TTY"
else "stdin is not TTY" |
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
| #Jsish | Jsish | /* Check input device is a terminal, in Jsish */
;Interp.conf().subOpts.istty;
/*
=!EXPECTSTART!=
Interp.conf().subOpts.istty ==> false
=!EXPECTEND!=
*/ |
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
| #Julia | Julia |
if isa(STDIN, Base.TTY)
println("This program sees STDIN as a TTY.")
else
println("This program does not see STDIN as a TTY.")
end
|
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #AutoHotkey | AutoHotkey | oDates:= {"May" : [ 15, 16, 19]
,"Jun" : [ 17, 18]
,"Jul" : [14, 16]
,"Aug" : [14, 15, 17]}
filter1(oDates)
filter2(oDates)
filter3(oDates)
MsgBox % result := checkAnswer(oDates)
return
filter1(ByRef oDates){ ... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #D | D | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
// This could be written more concis... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #E | E | /** A flagSet solves this problem: There are N things, each in a true or false
* state, and we want to know whether they are all true (or all false), and be
* able to bulk-change all of them, and all this without allowing double-
* counting -- setting a flag twice is idempotent.
*/
def makeFlagSet() {
# Each ... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Fancy | Fancy |
# creating an empty array and adding values
a = [] # => []
a[0]: 1 # => [1]
a[3]: 2 # => [1, nil, nil, 2]
# creating an array with the constructor
a = Array new # => []
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Lua | Lua |
function map(f, a, ...) if a then return f(a), map(f, ...) end end
function incr(k) return function(a) return k > a and a or a+1 end end
function combs(m, n)
if m * n == 0 then return {{}} end
local ret, old = {}, combs(m-1, n-1)
for i = 1, n do
for k, v in ipairs(old) do ret[#ret+1] = {i, map(incr(i), unpa... |
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 ... | #QB64 | QB64 |
Print "QB64/Qbasic conditional structures"
Dim k As String
Menu 1
View Print 13 To 23
Print "A menu example using the many options of IF statement"
k = " "
12: While k <> ""
k = UCase$(Input$(1))
If k = "O" GoTo O
If k = "F" Then 22
If k = "S" Then GoSub S: GoTo 12
If k = "C" Then GoSub 4: GoTo ... |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #C.23 | C# | using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Prolog | Prolog |
?- use_module(library(primality)).
u(3, M, A * B * C) :-
A is 6*M + 1, B is 12*M + 1, C is 18*M + 1, !.
u(N, M, U0 * D) :-
succ(Pn, N), u(Pn, M, U0),
D is 9*(1 << (N - 2))*M + 1.
prime_factorization(A*B) :- prime(B), prime_factorization(A), !.
prime_factorization(A) :- prime(A).
step(N, 1) :- N < 5,... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #EasyLang | EasyLang | func chowla n . sum .
sum = 0
i = 2
while i * i <= n
if n mod i = 0
j = n div i
if i = j
sum += i
else
sum += i + j
.
.
i += 1
.
.
func sieve . c[] .
i = 3
while i * 3 < len c[]
if c[i] = 0
call chowla i h
if h = 0
j = 3 * i
... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Factor | Factor | USING: formatting fry grouping.extras io kernel math
math.primes.factors math.ranges math.statistics sequences
tools.memory.private ;
IN: rosetta-code.chowla-numbers
: chowla ( n -- m )
dup 1 = [ 1 - ] [ [ divisors sum ] [ - 1 - ] bi ] if ;
: show-chowla ( n -- )
[1,b] [ dup chowla "chowla(%02d) = %d\n" pri... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Lua | Lua |
function churchZero()
return function(x) return x end
end
function churchSucc(c)
return function(f)
return function(x)
return f(c(f)(x))
end
end
end
function churchAdd(c, d)
return function(f)
return function(x)
return c(f)(d(f)(x))
end
end
end
function churchMul... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Eiffel | Eiffel |
class MY_CLASS
end
|
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Elena | Elena | import extensions;
class MyClass
{
prop int Variable;
someMethod()
{
Variable := 1
}
constructor()
{
}
}
public program()
{
// instantiate the class
var instance := new MyClass();
// invoke the method
instance.someMethod();
// get the variable
... |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Wren | Wren | import "/fmt" for Fmt
var n
var init = Fn.new {
n = List.filled(15, null)
for (i in 0..14) {
n[i] = List.filled(11, " ")
n[i][5] = "x"
}
}
var horiz = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r][c] = "x" } }
var verti = Fn.new { |r1, r2, c| (r1..r2).each { |r| n[r][c] = "x" } }
var... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Icon_and_Unicon | Icon and Unicon | record point(x,y)
procedure main()
minDist := 0
minPair := &null
every (points := [],p1 := readPoint()) do {
if *points == 1 then minDist := dSquared(p1,points[1])
every minDist >=:= dSquared(p1,p2 := !points) do minPair := [p1,p2]
push(points, p1)
}
if \minPair then ... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Oforth | Oforth | : newClosure(i) #[ i sq ] ;
10 seq map(#newClosure) at(7) perform . |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #PARI.2FGP | PARI/GP | vector(10,i,()->i^2)[5]() |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Wren | Wren | import "/math" for Int
import "/big" for BigInt
import "/str" for Str
var circs = []
var isCircular = Fn.new { |n|
var nn = n
var pow = 1 // will eventually contain 10 ^ d where d is number of digits in n
while (nn > 0) {
pow = pow * 10
nn = (nn/10).floor
}
nn = n
while (true... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #C.2B.2B | C++ |
#include <iostream>
#include <cmath>
#include <tuple>
struct point { double x, y; };
bool operator==(const point& lhs, const point& rhs)
{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }
enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };
using result_t = std::tuple<result_c... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #C | C | #include <math.h>
#include <stdio.h>
const char* animals[] = { "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" };
const char* elements[] = { "Wood","Fire","Earth","Metal","Water" };
const char* getElement(int year) {
int element = (int)floor((year - 4) % 10 / 2);
r... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure File_Exists is
function Does_File_Exist (Name : String) return Boolean is
The_File : Ada.Text_IO.File_Type;
begin
Open (The_File, In_File, Name);
Close (The_File);
return True;
exception
when Name_Error =>
return False;
en... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Aikido | Aikido |
function exists (filename) {
return stat (filename) != null
}
exists ("input.txt")
exists ("/input.txt")
exists ("docs")
exists ("/docs")
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #J | J | 3=nc<'wd' |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Javascript.2FNodeJS | Javascript/NodeJS | node -p -e "Boolean(process.stdout.isTTY)"
true |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Julia | Julia |
if isa(STDOUT, Base.TTY)
println("This program sees STDOUT as a TTY.")
else
println("This program does not see STDOUT as a TTY.")
end
|
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Kotlin | Kotlin | // Kotlin Native version 0.5
import platform.posix.*
fun main(args: Array<String>) {
if (isatty(STDOUT_FILENO) != 0)
println("stdout is a terminal")
else
println("stdout is not a terminal")
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Lua | Lua | local function isTTY ( fd )
fd = tonumber( fd ) or 1
local ok, exit, signal = os.execute( string.format( "test -t %d", fd ) )
return (ok and exit == "exit") and signal == 0 or false
end
print( "stdin", isTTY( 0 ) )
print( "stdout", isTTY( 1 ) )
print( "stderr", isTTY( 2 ) ) |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Common_Lisp | Common Lisp | ;; Calculates the Cholesky decomposition matrix L
;; for a positive-definite, symmetric nxn matrix A.
(defun chol (A)
(let* ((n (car (array-dimensions A)))
(L (make-array `(,n ,n) :initial-element 0)))
(do ((k 0 (incf k))) ((> k (- n 1)) nil)
;; First, calculate diagonal elements L_kk.
... |
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
| #Kotlin | Kotlin | // Kotlin Native version 0.5
import platform.posix.*
fun main(args: Array<String>) {
if (isatty(STDIN_FILENO) != 0)
println("stdin is a terminal")
else
println("stdin is not a terminal")
}
|
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
| #Nemerle | Nemerle | def isTerm = System.Console.IsInputRedirected; |
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
| #Nim | Nim | import terminal
echo if stdin.isatty: "stdin is a terminal" else: "stdin is not a terminal" |
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
| #OCaml | OCaml | let () =
print_endline (
if Unix.isatty Unix.stdin
then "Input comes from tty."
else "Input doesn't come from tty."
) |
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
| #Ol | Ol |
(define (isatty? fd) (syscall 16 fd 19))
(print (if (isatty? stdin)
"Input comes from tty."
"Input doesn't come from tty."))
|
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
| #Perl | Perl | use strict;
use warnings;
use 5.010;
if (-t) {
say "Input comes from tty.";
}
else {
say "Input doesn't come from tty.";
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #AWK | AWK |
# syntax: GAWK -f CHERYLS_BIRTHDAY.AWK [-v debug={0|1}]
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
debug += 0
PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1
n = split("05/15,05/16,05/19,06/17,06/18,07/14,07/16,08/14,08/15,08/1... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Erlang | Erlang |
-module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Com... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Forth | Forth | include ffl/car.fs
10 car-create ar \ create a dynamic array with initial size 10
2 0 ar car-set \ ar[0] = 2
3 1 ar car-set \ ar[1] = 3
1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 3
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Global a$
Document a$
Module Combinations (m as long, n as long){
Module Level (n, s, h) {
If n=1 then {
while Len(s) {
Print h, car(s)
ToClipBoard()
... |
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 ... | #Quackery | Quackery | /O> say "23 is greater than 42 is "
... 23 42 > not if [ say "not " ]
... say "true." cr
...
23 is greater than 42 is not true.
Stack empty.
/O> say "23 is less than 42 is "
... 23 42 < not if [ say "not " ]
... say "true." cr
...
23 is less than 42 is true.
Stack empty.
/O> 23 42 = iff
... [ say "23 is equal t... |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #C.2B.2B | C++ | // Requires C++17
#include <iostream>
#include <numeric>
#include <vector>
#include <execution>
template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
_Ty b0 = b;
_Ty x0 = 0;
_Ty x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
_Ty q = a / b;
_Ty amb = a % b;
a = b;
b = amb;
_Ty xqx = x1 - q * x0;... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Python | Python |
"""
Python implementation of
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
"""
# use sympy for prime test
from sympy import isprime
# based on C version
def primality_pretest(k):
if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) o... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #FreeBASIC | FreeBASIC |
' Chowla_numbers
#include "string.bi"
Dim Shared As Long limite
limite = 10000000
Dim Shared As Boolean c(limite)
Dim As Long count, topenumprimo, a
count = 1
topenumprimo = 100
Dim As Longint p, k, kk, limitenumperfect
limitenumperfect = 35000000
k = 2: kk = 3
Declare Function chowla(Byval n As Longint) As Lon... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Nim | Nim | import macros, sugar
type
Fn = proc(p: pointer): pointer{.noSideEffect.}
Church = proc(f: Fn): Fn{.noSideEffect.}
MetaChurch = proc(c: Church): Church{.noSideEffect.}
#helpers:
template λfλx(exp): untyped = (f: Fn){.closure.}=>((x: pointer){.closure.}=>exp)
template λcλf(exp): untyped = (c: Church){.closure.}=>... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #OCaml | OCaml | (* Using type as suggested in https://stackoverflow.com/questions/43426709/does-ocamls-type-system-prevent-it-from-modeling-church-numerals
This is an explicitly polymorphic type : it says that f must be of type ('a -> 'a) -> 'a -> 'a for any possible a "at same time".
*)
type church_num = { f : 'a. ('a -> 'a) ->... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #ERRE | ERRE | PROGRAM CLASS2_DEMO
CLASS QUADRATO
LOCAL LATO
PROCEDURE GETLATO(L)
LATO=L
END PROCEDURE
PROCEDURE AREA(->A)
A=LATO*LATO
END PROCEDURE
PROCEDURE PERIMETRO(->P)
P=4*LATO
END PROCEDURE
END CLASS
NEW P:QUADRATO,Q:QUADRATO
BEGIN
P_GETLATO(10)
P_AREA(->... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #F.23 | F# | type MyClass(init) = // constructor with one argument: init
let mutable var = init // a private instance variable
member x.Method() = // a simple method
var <- var + 1
printfn "%d" var
// create an instance and use it
let myObject = new MyClass(42)
myObject.Method() |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Closestp.bas"
110 NUMERIC X(1 TO 10),Y(1 TO 10)
120 FOR I=1 TO 10
130 READ X(I),Y(I)
140 PRINT X(I),Y(I)
150 NEXT
160 LET MN=INF
170 FOR I=1 TO 9
180 FOR J=I+1 TO 10
190 LET DSQ=(X(I)-X(J))^2+(Y(I)-Y(J))^2
200 IF DSQ<MN THEN LET MN=DSQ:LET MINI=I:LET MINJ=J
210 NEXT
220 NEXT
230 PRINT "C... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Perl | Perl | my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs
print $f[$_](), "\n" for (0 .. 8); # call and print all but last |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Phix | Phix | with javascript_semantics
-- First some generic handling stuff, handles partial_args
-- of any mixture of any length and element types.
sequence closures = {}
function add_closure(integer rid, sequence partial_args)
closures = append(closures,{rid,partial_args})
return length(closures) -- (return an integer id)... |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N > 2 is a prime number
int N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func CircPrime(N0); \Return 'true' if N0 is a circular prime
int N0, N, Digits, Rotation,... |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Zig | Zig |
const std = @import("std");
const math = std.math;
const heap = std.heap;
const stdout = std.io.getStdOut().writer();
pub fn main() !void {
var arena = heap.ArenaAllocator.init(heap.page_allocator);
defer arena.deinit();
var candidates = std.PriorityQueue(u32).init(&arena.allocator, u32cmp);
defer... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #D | D | import std.stdio, std.typecons, std.math;
class ValueException : Exception {
this(string msg_) pure { super(msg_); }
}
struct V2 { double x, y; }
struct Circle { double x, y, r; }
/**Following explanation at:
http://mathforum.org/library/drmath/view/53027.html
*/
Tuple!(Circle, Circle)
circlesFromTwoPointsAnd... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #C.23 | C# | using System;
namespace ChineseZodiac {
class Program {
static string[] animals = { "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig" };
static string[] elements = { "Wood", "Fire", "Earth", "Metal", "Water" };
static string[] animalChars... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #ALGOL_68 | ALGOL 68 | # Check files and directories exist #
# check a file exists by attempting to open it for input #
# returns TRUE if the file exists, FALSE otherwise #
PROC file exists = ( STRING file name )BOOL:
IF FILE f;
open( f, file name, stand in channel ) = 0
... |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Nemerle | Nemerle | def isTerm = System.Console.IsOutputRedirected; |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Nim | Nim | import terminal
stderr.write if stdout.isatty: "stdout is a terminal\n" else: "stdout is not a terminal\n" |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #OCaml | OCaml | let () =
print_endline (
if Unix.isatty Unix.stdout
then "Output goes to tty."
else "Output doesn't go to tty."
) |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Ol | Ol |
(define (isatty? fd) (syscall 16 fd 19))
(print (if (isatty? stdout)
"stdout is a tty."
"stdout is not a tty."))
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #11l | 11l | print(‘a’.code) // prints "97"
print(Char(code' 97)) // prints "a" |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #D | D | import std.stdio, std.math, std.numeric;
T[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ {
auto L = new T[][](A.length, A.length);
foreach (immutable r, row; L)
row[r + 1 .. $] = 0;
foreach (immutable i; 0 .. A.length)
foreach (immutable j; 0 .. i + 1) {
auto t = dotProduc... |
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
| #Phix | Phix | without js -- (no input redirection in a browser!)
printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
|
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
| #Pike | Pike | void main()
{
if(Stdio.Terminfo.is_tty())
write("Input comes from tty.\n");
else
write("Input doesn't come from tty.\n");
} |
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
| #Python | Python | from sys import stdin
if stdin.isatty():
print("Input comes from tty.")
else:
print("Input doesn't come from tty.") |
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
| #Quackery | Quackery | [ $ |from sys import stdin
to_stack( 1 if stdin.isatty() else 0)|
python ] is ttyin ( --> b )
ttyin if
[ say "Looks like a teletype." ]
else
[ say "Not a teletype." ] |
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
| #Racket | Racket |
(terminal-port? (current-input-port))
|
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
| #Raku | Raku | say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty."; |
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
| #REXX | REXX | /*REXX program determines if input comes from terminal or standard input*/
if queued() then say 'input comes from the terminal.'
else say 'input comes from the (stacked) terminal queue.'
/*stick a fork in it, we're done.*/
|
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #C | C | #include <stdbool.h>
#include <stdio.h>
char *months[] = {
"ERR", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
struct Date {
int month, day;
bool active;
} dates[] = {
{5,15,true}, {5,16,true}, {5,19,true},
{6,17,true}, {6,18,true},
{7,14,true}, {7,16... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #FreeBASIC | FreeBASIC | #include "ontimer.bi"
Randomize Timer
Dim Shared As Uinteger nWorkers = 3
Dim Shared As Uinteger tID(nWorkers)
Dim Shared As Integer cnt(nWorkers)
Dim Shared As Integer checked = 0
Sub checkpoint()
Dim As Boolean sync
If checked = 0 Then sync = False
checked += 1
If (sync = False) And (checked = n... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Fortran | Fortran | REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36)
A(1) = 1 !Assigns a value to the first element.
A(2) = 3*A(1) + 5 !The second element gets 8. |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #M4 | M4 | divert(-1)
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,
incr($2),shift(shift(shift($@))))')')
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')'... |
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 ... | #R | R | x <- 0
if(x == 0) print("foo")
x <- 1
if(x == 0) print("foo")
if(x == 0) print("foo") else print("bar") |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Clojure | Clojure | (ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn extended-gcd
"The extended Euclidean algorithm
Returns a list containing the GCD and the Bézout coefficients
corresponding to the inputs. "
[a b]
(cond (zero? a) [(math/abs b) 0 1]
(zero? b) [(math/abs a) 1 0]
:else (l... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Raku | Raku | use Inline::Perl5;
use ntheory:from<Perl5> <:all>;
sub chernick-factors ($n, $m) {
6×$m + 1, 12×$m + 1, |((1 .. $n-2).map: { (1 +< $_) × 9×$m + 1 } )
}
sub chernick-carmichael-number ($n) {
my $multiplier = 1 +< (($n-4) max 0);
my $iterator = $n < 5 ?? (1 .. *) !! (1 .. *).map: * × 5;
$multipl... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Go | Go | package main
import "fmt"
func chowla(n int) int {
if n < 1 {
panic("argument must be a positive integer")
}
sum := 0
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
if i == j {
sum += i
} else {
sum += i + j
... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Octave | Octave |
zero = @(f) @(x) x;
succ = @(n) @(f) @(x) f(n(f)(x));
add = @(m, n) @(f) @(x) m(f)(n(f)(x));
mul = @(m, n) @(f) @(x) m(n(f))(x);
pow = @(b, e) e(b);
% Need a short-circuiting ternary
iif = @(varargin) varargin{3 - varargin{1}}();
% Helper for anonymous recursion
% The branches are thunked to prevent infinite recu... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Factor | Factor | TUPLE: my-class foo bar baz ;
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
10 20 30 <my-class> quux ! result: 30
TUPLE: my-child-class < my-class quxx ;
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30 |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Falcon | Falcon | class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ]
[ static block ]
[ properties declaration ]
[init block]
[method list]
end |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.