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/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...
#J
J
vecl =: +/"1&.:*: NB. length of each vector dist =: <@:vecl@:({: -"1 }:)\ NB. calculate all distances among vectors minpair=: ({~ > {.@($ #: I.@,)@:= <./@;)dist NB. find one pair of the closest points closestpairbf =: (; vecl@:-/)@minpair NB. the pair and their distance
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...
#Phixmonti
Phixmonti
def power2 dup * enddef   getid power2 10 repeat   len for dup rot swap get rot swap exec print " " print endfor   nl   /# Another mode #/ len for var i i get i swap exec print " " print endfor
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...
#PHP
PHP
<?php $funcs = array(); for ($i = 0; $i < 10; $i++) { $funcs[] = function () use ($i) { return $i * $i; }; } echo $funcs[3](), "\n"; // prints 9 ?>
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...
#Delphi
Delphi
  program Circles_of_given_radius_through_two_points;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Types, System.Math;   const Cases: array[0..9] of TPointF = (( x: 0.1234; y: 0.9876 ), ( x: 0.8765; y: 0.2345 ), ( x: 0.0000; y: 2.0000 ), ( x: 0.0000; y: 0.0000 ), (...
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.2B.2B
C++
#include <iostream> #include <cmath>   using namespace std;   const string animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}; const string elements[]={"Wood","Fire","Earth","Metal","Water"};   string getElement(int year) { int element = floor((year-4)%10/2); ...
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 ...
#Amazing_Hopper
Amazing Hopper
  #include <flow.h>   DEF-MAIN(argv, argc) WHEN( IS-FILE?("hopper") ){ MEM("File \"hopper\" exist!\n") } WHEN( IS-DIR?("fl") ){ MEM("Directory \"fl\" exist!\n") } IF( IS-DIR?("noExisDir"), "Directory \"noExistDir\" exist!\n", \ "Directory \"noExistDir\" does NOT e...
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 ...
#APL
APL
  h ← ⎕fio['fopen'] 'input.txt' h 7 ⎕fio['fstat'] h 66311 803134 33188 1 1000 1000 0 11634 4096 24 1642047105 1642047105 1642047105 ⎕fio['fclose'] h 0 h ← ⎕fio['fopen'] 'docs/' h 7 ⎕fio['fstat'] h 66311 3296858 16877 2 1000 1000 0 4096 4096 8 1642047108 1642047108 164204710...
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
#Perl
Perl
$ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'" Terminal $ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'" > x.tmp Other  
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
#Phix
Phix
without js -- (no input or output redirection in a browser!) printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
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
#PHP
PHP
  if(posix_isatty(STDOUT)) { echo "The output device is a terminal".PHP_EOL; } else { echo "The output device is NOT a terminal".PHP_EOL; }  
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
#Python
Python
from sys import stdout if stdout.isatty(): print 'The output device is a teletype. Or something like a teletype.' else: print 'The output device isn\'t like a teletype.'
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
#Quackery
Quackery
[ $ |from sys import stdout to_stack( 1 if stdout.isatty() else 0)| python ] is ttyout ( --> b )   ttyout if [ say "Looks like a teletype." ] else [ say "Not a teletype." ]
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#Clojure
Clojure
(ns tanevaulator (:gen-class))   ;; Notation: [a b c] -> a x arctan(a/b) (def test-cases [ [[1, 1, 2], [1, 1, 3]], [[2, 1, 3], [1, 1, 7]], [[4, 1, 5], [-1, 1, 239]], [[5, 1, 7], [2, 3, 79]], ...
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...
#360_Assembly
360 Assembly
* Character codes EBCDIC 15/02/2017 CHARCODE CSECT USING CHARCODE,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
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...
#68000_Assembly
68000 Assembly
JSR ResetCoords ;RESET TYPING CURSOR   MOVE.B #'A',D1 MOVE.W #25,D2 MOVE.B #0,(softCarriageReturn) ;new line takes the cursor to left edge of screen. jsr PrintAllTheCodes   jsr ResetCoords MOVE.B #8,(Cursor_X) MOVE.B #'a',D1 MOVE.W #25,D2 MOVE.B #8,(softCarriageReturn) ;set the writing cursor to ...
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...
#Delphi
Delphi
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if ...
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
#Ring
Ring
  # Project  : Check input device is a terminal   load "stdlib.ring"   if isWindows() write("mycmd.bat"," @echo off timeout 1 2>nul >nul if errorlevel 1 ( echo input redirected ) else ( echo input is console ) ") see SystemCmd("mycmd.bat") ok  
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
#Ruby
Ruby
File.new("testfile").isatty #=> false File.new("/dev/tty").isatty #=> true
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"); } }
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
#Scala
Scala
import org.fusesource.jansi.internal.CLibrary._   object IsATty extends App {   var enabled = true   def apply(enabled: Boolean): Boolean = { // We must be on some unix variant.. try { enabled && isatty(STDIN_FILENO) == 1 } catch { case ignore: Throwable => ignore.printStackTrac...
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
#Standard_ML
Standard ML
val stdinRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdin
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
#Tcl
Tcl
if {[catch {fconfigure stdin -mode}]} { puts "Input doesn't come from tty." } else { puts "Input comes 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, ...
#C.23
C#
public static class CherylsBirthday { public static void Main() { var dates = new HashSet<(string month, int day)> { ("May", 15), ("May", 16), ("May", 19), ("June", 17), ("June", 18), ("July", 14), ("July", 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...
#Go
Go
package main   import ( "log" "math/rand" "sync" "time" )   func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() }   var ( partList = []string{"A", "B", "C", "D"} nAs...
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...
#Haskell
Haskell
import Control.Parallel   data Task a = Idle | Make a type TaskList a = [a] type Results a = [a] type TaskGroups a = [TaskList a] type WorkerList a = [Worker a] type Worker a = [Task a]   -- run tasks in parallel and collect their results -- the function doesn't return until all tasks are done, therefore -- finished th...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   'create fixed size array of integers Dim a(1 To 5) As Integer = {1, 2, 3, 4, 5} Print a(2), a(4)   'create empty dynamic array of doubles Dim b() As Double ' add two elements by first redimensioning the array to hold this number of elements Redim b(0 To 1) b(0) = 3.5 : b(1) = 7.1 Print b(0), b(1)  ...
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 ...
#Maple
Maple
> combinat:-choose( 5, 3 ); [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5],   [2, 4, 5], [3, 4, 5]]  
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 ...
#Racket
Racket
  (if (< x 10) "small" "big")  
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 ...
#Coffeescript
Coffeescript
crt = (n,a) -> sum = 0 prod = n.reduce (a,c) -> a*c for [ni,ai] in _.zip n,a p = prod // ni sum += ai * p * mulInv p,ni sum % prod   mulInv = (a,b) -> b0 = b [x0,x1] = [0,1] if b==1 then return 1 while a > 1 q = a // b [a,b] = [b, a % b] [x0,x1] = [x1-q*x0, x0] if x1 < 0 then x1 += b0 x1   print crt...
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)...
#Sidef
Sidef
func chernick_carmichael_factors (n, m) { [6*m + 1, 12*m + 1, {|i| 2**i * 9*m + 1 }.map(1 .. n-2)...] }   func is_chernick_carmichael (n, m) { (n == 2) ? (is_prime(6*m + 1) && is_prime(12*m + 1))  : (is_prime(2**(n-2) * 9*m + 1) && __FUNC__(n-1, m)) }   func chernick_carmichael_number(n, callback) {...
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)...
#Wren
Wren
import "/big" for BigInt, BigInts import "/fmt" for Fmt   var min = 3 var max = 9 var prod = BigInt.zero var fact = BigInt.zero var factors = List.filled(max, 0) var bigFactors = List.filled(max, null)   var init = Fn.new { for (i in 0...max) bigFactors[i] = BigInt.zero }   var isPrimePretest = Fn.new { |k| if ...
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...
#Groovy
Groovy
class Chowla { static int chowla(int n) { if (n < 1) throw new RuntimeException("argument must be a positive integer") int sum = 0 int i = 2 while (i * i <= n) { if (n % i == 0) { int j = (int) (n / i) sum += (i == j) ? i : 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...
#Perl
Perl
use 5.020; use feature qw<signatures>; no warnings qw<experimental::signatures>;   use constant zero => sub ($f) { sub ($x) { $x }};   use constant succ => sub ($n) { sub ($f) { sub ($x) { $f->($n->($f)($x)) }}};   use constant add => sub ($n) { ...
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...
#Fancy
Fancy
class MyClass { read_slot: 'instance_var # creates getter method for @instance_var @@class_var = []   def initialize { # 'initialize' is the constructor method invoked during 'MyClass.new' by convention @instance_var = 0 }   def some_method { @instance_var = 1 @another_instance_var = "foo" }...
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...
#Fantom
Fantom
class MyClass { // an instance variable Int x   // a constructor, providing default value for instance variable new make (Int x := 1) { this.x = x }   // a method, return double the number x public Int double () { return 2 * x } }   class Main { public static Void main () { a := MyCl...
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...
#Java
Java
import java.util.*;   public class ClosestPair { public static class Point { public final double x; public final double y;   public Point(double x, double y) { this.x = x; this.y = y; }   public String toString() { return "(" + x + ", " + y + ")"; } }   public static cl...
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...
#PicoLisp
PicoLisp
(setq FunList (make (for @N 10 (link (curry (@N) () (* @N @N))) ) ) )
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...
#Pike
Pike
array funcs = ({}); foreach(enumerate(10);; int i) { funcs+= ({ lambda(int j) { return lambda() { return j*j; }; }(i) }); }
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...
#Elixir
Elixir
defmodule RC do def circle(p, p, r) when r>0.0 do raise ArgumentError, message: "Infinite number of circles, points coincide." end def circle(p, p, r) when r==0.0 do {px, py} = p [{px, py, r}] end def circle({p1x,p1y}, {p2x,p2y}, r) do {dx, dy} = {p2x-p1x, p2y-p1y} q = :math.sqrt(dx*dx + d...
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...
#Clojure
Clojure
(def base-year 4) (def celestial-stems ["甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"]) (def terrestrial-branches ["子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"]) (def zodiac-animals ["Rat" "Ox" "Tiger" "Rabbit" "Dragon" "Snake" "Horse" "Goat" "Monkey" "Rooster" "Dog" "Pig"]) (def elements ["Wood" "Fire" "Earth" "Metal" "W...
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 ...
#AppleScript
AppleScript
use framework "Foundation" -- YOSEMITE OS X onwards use scripting additions   on run setCurrentDirectory("~/Desktop")   ap({doesFileExist, doesDirectoryExist}, ¬ {"input.txt", "/input.txt", "docs", "/docs"})   --> {true, true, true, true, false, false, true, true}   -- The first four booleans ar...
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
#Racket
Racket
  (terminal-port? (current-output-port))  
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
#Raku
Raku
$ raku -e 'note $*OUT.t' True $ raku -e 'note $*OUT.t' >/dev/null False
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
#REXX
REXX
/*REXX program determines if the STDIN is a terminal device or other. */ signal on syntax /*if syntax error, then jump ──► SYNTAX*/ say 'output device:' testSTDIN() /*displays terminal ──or── other */ exit 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
#Ruby
Ruby
f = File.open("test.txt") p f.isatty # => false p STDOUT.isatty # => 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
#Rust
Rust
/* Uses C library interface */   extern crate libc;   fn main() { let istty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0; if istty { println!("stdout is tty"); } else { println!("stdout is not 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
#Scala
Scala
import org.fusesource.jansi.internal.CLibrary._   object IsATty extends App {   var enabled = true   def apply(enabled: Boolean): Boolean = { // We must be on some unix variant.. try { enabled && isatty(STDOUT_FILENO) == 1 } catch { case ignore: Throwable => ignore.printStackTra...
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Ada
Ada
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets;   procedure Chat_Server is   package Client_Vectors is new Ada.Contai...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#D
D
import std.stdio, std.regex, std.conv, std.string, std.range, arithmetic_rational;   struct Pair { int x; Rational r; }   Pair[][] parseEquations(in string text) /*pure nothrow*/ { auto r = regex(r"\s*(?P<sign>[+-])?\s*(?:(?P<mul>\d+)\s*\*)?\s*" ~ r"arctan\((?P<num>\d+)/(?P<denom>\d+)\)");...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program character64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
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...
#ABAP
ABAP
report zcharcode data: c value 'A', n type i. field-symbols <n> type x.   assign c to <n> casting. move <n> to n. write: c, '=', n left-justified.
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...
#DWScript
DWScript
function Cholesky(a : array of Float) : array of Float; var i, j, k, n : Integer; s : Float; begin n:=Round(Sqrt(a.Length)); Result:=new Float[n*n]; for i:=0 to n-1 do begin for j:=0 to i do begin s:=0 ; for k:=0 to j-1 do s+=Result[i*n+k] * Result[j*n+k]; if ...
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
#UNIX_Shell
UNIX Shell
#!/bin/sh   if [ -t 0 ] then echo "Input is a terminal" else echo "Input is NOT a terminal" fi
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
#Wren
Wren
import "io" for Stdin   System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")")
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
#zkl
zkl
const S_IFCHR=0x2000; fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() } S_ISCHR(File.stdin).println();
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.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector> using namespace std;   const vector<string> MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };   struct Birthday { int month, day;   friend ostream &operator<<(ostream &, const Birthday &); };   ostr...
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...
#Icon_and_Unicon
Icon and Unicon
global nWorkers, workers, cv   procedure main(A) nWorkers := integer(A[1]) | 3 cv := condvar() every put(workers := [], worker(!nWorkers)) every wait(!workers) end   procedure worker(n) return thread every !3 do { # Union limits each worker to 3 pieces write(n," is working") d...
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...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"]   For siCount = 0 To 9 Print cCollection[Str(siCount)] Next   End
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
combinations[n_Integer, m_Integer]/;m>= 0:=Union[Sort /@ Permutations[Range[0, n - 1], {m}]]
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 ...
#Raku
Raku
given lc prompt("Done? ") { when 'yes' { return } when 'no' { next } default { say "Please answer either yes or no." } }
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 ...
#Common_Lisp
Common Lisp
  (defun chinese-remainder (am) "Calculates the Chinese Remainder for the given set of integer modulo pairs. Note: All the ni and the N must be coprimes." (loop :for (a . m) :in am :with mtot = (reduce #'* (mapcar #'(lambda(X) (cdr X)) am)) :with sum = 0 :finally (return (mod sum mtot)) ...
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)...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn ccFactors(n,m){ // not re-entrant prod:=BI(6*m + 1); if(not prod.probablyPrime()) return(False); fact:=BI(12*m + 1); if(not fact.probablyPrime()) return(False); prod.mul(fact); foreach i in ([1..n-2]){ fact.set((2).pow(i) *9*m + 1); ...
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...
#Haskell
Haskell
import Control.Concurrent (setNumCapabilities) import Control.Monad.Par (runPar, get, spawnP) import Control.Monad (join, (>=>)) import Data.List.Split (chunksOf) import Data.List (intercalate, mapAccumL, genericTake, genericDrop) import Data.Bifunctor (bimap) i...
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...
#Phix
Phix
with javascript_semantics type church(object c) -- eg {r_add,1,{a,b}} return sequence(c) and length(c)=3 and integer(c[1]) and integer(c[2]) and sequence(c[3]) and length(c[3])=2 end type function succ(church c) -- eg {r_add,1,{a,b}} => {r_add,2,{a,b}} aka a+b -> a+b+b c = deep_copy(c) ...
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...
#Forth
Forth
:class MyClass <super Object   int memvar    :m ClassInit: ( -- ) ClassInit: super 1 to memvar ;m    :m ~: ( -- ) ." Final " show: [ Self ] ;m    :m set: ( n -- ) to memvar ;m  :m show: ( -- ) ." Memvar = " memvar . ;m   ;class
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...
#Fortran
Fortran
  !----------------------------------------------------------------------- !Module accuracy defines precision and some constants !----------------------------------------------------------------------- module accuracy_module implicit none integer, parameter, public :: rdp = kind(1.d0) ! constants real(rdp),...
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...
#JavaScript
JavaScript
function distance(p1, p2) { var dx = Math.abs(p1.x - p2.x); var dy = Math.abs(p1.y - p2.y); return Math.sqrt(dx*dx + dy*dy); }   function bruteforceClosestPair(arr) { if (arr.length < 2) { return Infinity; } else { var minDist = distance(arr[0], arr[1]); var minPoints = arr.slice(0, 2);   for ...
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...
#PowerShell
PowerShell
  function Get-Closure ([double]$Number) { {param([double]$Sum) return $script:Number *= $Sum}.GetNewClosure() }  
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...
#Prolog
Prolog
:-use_module(library(lambda)).     closure :- numlist(1,10, Lnum), maplist(make_func, Lnum, Lfunc), maplist(call_func, Lnum, Lfunc).     make_func(I, \X^(X is I*I)).   call_func(N, F) :- call(F, R), format('Func ~w : ~w~n', [N, R]).  
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...
#ERRE
ERRE
  PROGRAM CIRCLES   ! ! for rosettacode.org !   PROCEDURE CIRCLE_CENTER(X1,Y1,X2,Y2,R->MSG$) LOCAL D,W,X3,Y3   D=SQR((X2-X1)^2+(Y2-Y1)^2) IF D=0 THEN MSG$="NO CIRCLES CAN BE DRAWN, POINTS ARE IDENTICAL" EXIT PROCEDURE END IF X3=(X1+X2)/2 Y3=(Y1+Y2)/2   ...
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...
#Commodore_BASIC
Commodore BASIC
1000 rem display the chinese zodiac for a given year 1010 poke 53281,7: rem yellow background 1020 poke 53280,2: rem red border 1030 poke 646,2: rem red text 1040 h1$="chinese zodiac":gosub 2000 set-heading 1050 gosub 3000 initialize-data 1060 print 1070 print "enter year (return to quit):"; 1080 get k$:if k$="" then 1...
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...
#Common_Lisp
Common Lisp
; Any CE Year that was the first of a 60-year cycle (defconstant base-year 1984)   (defconstant celestial-stems '("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))   (defconstant terrestrial-branches '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))   (defconstant zodiac-animals '("Rat" "Ox" "Tiger" "Rabbit" "Dra...
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 ...
#Applesoft_BASIC
Applesoft BASIC
100 F$ = "THAT FILE" 110 T$(0) = "DOES NOT EXIST." 120 T$(1) = "EXISTS." 130 GOSUB 200"FILE EXISTS? 140 PRINT F$; " "; T$(E) 150 END   200 REM FILE EXISTS? 210 REM TRY 220 ON ERR GOTO 300"CATCH 230 PRINT CHR$(4); "VERIFY "; F$ 240 POKE 216, 0 : REM ONERR OFF 250 E = 1 260 GOTO 350"END TRY 300 REM CATCH 3...
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
#Standard_ML
Standard ML
val stdoutRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdout
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
#Tcl
Tcl
set toTTY [dict exists [fconfigure stdout] -mode] puts [expr {$toTTY ? "Output goes to tty" : "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
#UNIX_Shell
UNIX Shell
#!/bin/sh   if [ -t 1 ] then echo "Output is a terminal" else echo "Output is NOT a terminal" >/dev/tty fi
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected) End Sub   End Module
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
#Wren
Wren
/* check_output_device_is_terminal.wren */   class C { foreign static isOutputDeviceTerminal }   System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)")
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#BaCon
BaCon
DECLARE user$ ASSOC STRING DECLARE connect ASSOC long OPEN "localhost:51000" FOR SERVER AS mynet WHILE TRUE IF WAIT(mynet, 30) THEN fd = ACCEPT(mynet) connect(GETPEER$(fd)) = fd SEND "Enter your name: " TO fd ELSE FOR con$ IN OBTAIN$(connect) IF WAIT(connect(con$), 10...
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#EchoLisp
EchoLisp
  (lib 'math) (lib 'match) (math-precision 1.e-10)   ;; formally derive (tan ..) expressions ;; copied from Racket ;; adapted and improved for performance   (define (reduce e) ;; (set! rcount (1+ rcount)) ;; # of calls (match e [(? number? a) a] [('+ (? number? a) (? number? b)) (+ a...
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...
#ACL2
ACL2
(cw "~x0" (char-code #\a)) (cw "~x0" (code-char 97))
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...
#Action.21
Action!
PROC Main() CHAR c=['a] BYTE b=[97]   Put(c) Put('=) PrintBE(c) PrintB(b) Put('=) Put(b) RETURN
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...
#F.23
F#
open Microsoft.FSharp.Collections   let cholesky a = let calc (a: float[,]) (l: float[,]) i j = let c1 j = let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1] sqrt (a.[j, j] - sum) let c2 i j = let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]...
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, ...
#Common_Lisp
Common Lisp
  ;; Author: Amir Teymuri, Saturday 20.10.2018   (defparameter *possible-dates* '((15 . may) (16 . may) (19 . may) (17 . june) (18 . june) (14 . july) (16 . july) (14 . august) (15 . august) (17 . august)))   (defun unique-date-parts (possible-dates &key (alist-look-at #'car) (alist-r-assoc #'assoc)) (l...
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...
#J
J
import java.util.Scanner; import java.util.Random;   public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks...
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...
#Go
Go
package main   import "fmt"   func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
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 ...
#MATLAB
MATLAB
>> nchoosek((0:4),3)   ans =   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
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 ...
#Red
Red
>> if 10 > 2 [print "ten is bigger"] ten is bigger
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 ...
#Crystal
Crystal
def extended_gcd(a, b) last_remainder, remainder = a.abs, b.abs x, last_x = 0, 1   until remainder == 0 tmp = remainder quotient, remainder = last_remainder.divmod(remainder) last_remainder = tmp x, last_x = last_x - quotient * x, x end   return last_remainder, last_x...
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 ...
#D
D
import std.stdio, std.algorithm;   T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a >...
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...
#J
J
chowla=: >: -~ >:@#.~/.~&.q: NB. sum of factors - (n + 1)   intsbelow=: (2 }. i.)"0 countPrimesbelow=: +/@(0 = chowla)@intsbelow findPerfectsbelow=: (#~ <: = chowla)@intsbelow
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...
#Java
Java
  public class Chowla {   public static void main(String[] args) { int[] chowlaNumbers = findChowlaNumbers(37); for (int i = 0; i < chowlaNumbers.length; i++) { System.out.printf("chowla(%d) = %d%n", (i+1), chowlaNumbers[i]); } System.out.println();   int[][] prim...
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...
#PHP
PHP
<?php $zero = function($f) { return function ($x) { return $x; }; };   $succ = function($n) { return function($f) use (&$n) { return function($x) use (&$n, &$f) { return $f( ($n($f))($x) ); }; }; };   $add = function($n, $m) { return function($f) use (&$n, &$m) { return function($x) use (&$f, ...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type MyClass Private: myInt_ As Integer Public: Declare Constructor(myInt_ As Integer) Declare Property MyInt() As Integer Declare Function Treble() As Integer End Type   Constructor MyClass(myInt_ As Integer) This.myInt_ = myInt_ End Constructor   Property MyClass.MyInt() As ...
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...
#jq
jq
# This definition of "until" is included in recent versions (> 1.4) of jq # Emit the first input that satisfied the condition def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # Euclidean 2d distance def dist(x;y): [x[0] - y[0], x[1] - y[1]] | map(.*.) | add | sqrt;
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...
#Python
Python
funcs = [] for i in range(10): funcs.append(lambda: i * i) print funcs[3]() # prints 81
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...
#Quackery
Quackery
[ table ] is functions ( n --> [ )   10 times [ i^ ' [ dup * ] join ' functions put ]   5 functions do echo
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...
#F.23
F#
open System   let add (a:double, b:double) (x:double, y:double) = (a + x, b + y) let sub (a:double, b:double) (x:double, y:double) = (a - x, b - y) let magSqr (a:double, b:double) = a * a + b * b let mag a:double = Math.Sqrt(magSqr a) let mul (a:double, b:double) c = (a * c, b * c) let div2 (a:double, b:double) c = (a ...
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...
#D
D
import std.stdio;   // 10 heavenly stems immutable tiangan=[ ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"], ["jiă","yĭ","bĭng","dīng","wù","jĭ","gēng","xīn","rén","gŭi"] ];   // 12 terrestrial branches immutable dizhi=[ ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"], ["zĭ","chŏu","yín","măo","chén","sì",...
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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program verifFic.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall .equ OPEN, 5 @ Linux syscall .equ CLOSE, 6 @ Linux syscall   .equ O_RDWR, 0x0002 /* open for reading and writing...