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/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#ALGOL_68
ALGOL 68
  PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL: BEGIN REAL result; result := 0; FOR n FROM steps BY -1 TO 1 DO result := b(n) / (a(n) + result) OD; a(0) + result END;   PROC asqr2 = (INT n) INT: (n = 0 | 1 | 2); PROC bsqr2 = (INT n) INT: 1;   PROC anap = (INT n) INT: (n = 0 | 2 | n); P...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#REXX
REXX
/*REXX program converts a rational fraction [n/m] (or nnn.ddd) to it's lowest terms.*/ numeric digits 10 /*use ten decimal digits of precision. */ parse arg orig 1 n.1 "/" n.2; if n.2='' then n.2=1 /*get the fraction.*/ if n.1='' then call er 'no argument specified....
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#DWScript
DWScript
var src = "foobar" var dst = src
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Dyalect
Dyalect
var src = "foobar" var dst = src
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#beeswax
beeswax
#>%f# #>%f# #f%<##>%f# pq":X~7~ :X@~++8~8@:X:X@~-~4~.+~8@T_ ## ## #### #`K0[`}`D2[`}BF3< < >{` wk, `>g?"p{` d, `>g?"p{` hr, `>g?"p{` min, `>g"b{` sec, `b > d > d > d > d
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#C.23
C#
interface IEatable { void Eat(); }
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#C.2B.2B
C++
template<typename T> //Detection helper struct struct can_eat //Detects presence of non-const member function void eat() { private: template<typename U, void (U::*)()> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::eat>*); template<typename U> static int Test(...); public: ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Common_Lisp
Common Lisp
(defclass food () ())   (defclass inedible-food (food) ())   (defclass edible-food (food) ())   (defgeneric eat (foodstuff) (:documentation "Eat the foodstuff."))   (defmethod eat ((foodstuff edible-food)) "A specialized method for eating edible-food." (format nil "Eating ~w." foodstuff))   (defun eatable-p (thin...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#ALGOL_68
ALGOL 68
BEGIN # find sequences of primes where the gaps between the elements # # are strictly ascending/descending # # reurns a list of primes up to n # PROC prime list = ( INT n )[]INT: BEGIN # sieve the primes to n # INT no = 0, yes = 1; [ ...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Arturo
Arturo
calc: function [f, n][ [a, b, temp]: 0.0   loop n..1 'i [ [a, b]: call f @[i] temp: b // a + temp ] [a, b]: call f @[0] return a + temp ]   sqrt2: function [n][ (n > 0)? -> [2.0, 1.0] -> [1.0, 1.0] ]   napier: function [n][ a: (n > 0)? -> to :floating n -> 2.0 b: (n > 1)?...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Ruby
Ruby
> '0.9054054 0.518518 0.75'.split.each { |d| puts "%s %s" % [d, Rational(d)] } 0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 => ["0.9054054", "0.518518", "0.75"]
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Rust
Rust
  extern crate rand; extern crate num;   use num::Integer; use rand::Rng;   fn decimal_to_rational (mut n : f64) -> [isize;2] { //Based on Farey sequences assert!(n.is_finite()); let flag_neg = n < 0.0; if flag_neg { n = n*(-1.0) } if n < std::f64::MIN_POSITIVE { return [0,1] } if (n - n.round(...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :orgininal "this is the original" local :scopy concat( original "" ) !. scopy
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#E
E
a$ = "hello" b$ = a$
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Befunge
Befunge
&>:"<"%\"O{rq"**+\"<"/:"<"%\"r<|":*+*5-\v v-7*"l~"/7\"d"\%7:/*83\+*:"xD"\%*83:/"<"< > \:! #v_v#-#<",",#$48*#<,#<.#<>#_:"~"%,v ^_@#:$$< > .02g92p ^ ^!:/"~"<
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Crystal
Crystal
class Apple def eat end end   class Carrot def eat end end   class FoodBox(T) def initialize(@data : Array(T)) {% if T.union? %} {% raise "All items should be eatable" unless T.union_types.all? &.has_method?(:eat) %} {% else %} {% raise "Items should be eatable" unless T.has_method?(:eat) %} ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#D
D
enum IsEdible(T) = is(typeof(T.eat));   struct FoodBox(T) if (IsEdible!T) { T[] food; alias food this; }   struct Carrot { void eat() {} }   static struct Car {}   void main() { FoodBox!Carrot carrotsBox; // OK carrotsBox ~= Carrot(); // Adds a carrot   //FoodBox!Car carsBox; // Not allow...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#C.23
C#
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console;   class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0,...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#ATS
ATS
#include "share/atspre_staload.hats" // (* ****** ****** *) // (* ** a coefficient function creates double values from in paramters *) typedef coeff_f = int -> double // (* ** a continued fraction is described by a record of two coefficent ** functions a and b *) typedef frac = @{a= coeff_f, b= coeff_f} // (* ****** **...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Scala
Scala
import org.apache.commons.math3.fraction.BigFraction   object Number2Fraction extends App { val n = Array(0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536) for (d <- n) println(f"$d%-12s : ${new BigFraction(d, 0.00000002D, 10000)}%s") }
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigrat.s7i";   const proc: main is func begin writeln(bigRational parse "0.9(054)"); writeln(bigRational parse "0.(518)"); writeln(bigRational parse "0.75"); writeln(bigRational parse "3.(142857)"); writeln(bigRational parse "0.(8867924528301)"); writeln(bi...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#EasyLang
EasyLang
a$ = "hello" b$ = a$
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#EchoLisp
EchoLisp
  (define-syntax-rule (string-copy s) (string-append s)) ;; copy = append nothing → #syntax:string-copy (define s "abc") (define t (string-copy s)) t → "abc" (eq? s t) → #t ;; same reference, same object  
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#C
C
/* * Program seconds2string, C89 version. * * Read input from argv[1] or stdin, write output to stdout. */   #define _CRT_SECURE_NO_WARNINGS /* unlocks printf in Microsoft Visual Studio */   #include <stdio.h> #include <stdlib.h>   /* * Converting the number of seconds in a human-readable string. * It is worth no...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#E
E
/** Guard accepting only objects with an 'eat' method */ def Eatable { to coerce(specimen, ejector) { if (Ref.isNear(specimen) && specimen.__respondsTo("eat", 0)) { return specimen } else { throw.eject(ejector, `inedible: $specimen`) } } }   def makeFoodBox() { ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Eiffel
Eiffel
  deferred class EATABLE   feature -- Basic operations   eat -- Eat this eatable substance deferred end end  
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#F.23
F#
type ^a FoodBox // a generic type FoodBox when ^a: (member eat: unit -> string) // with an explicit member constraint on ^a, (items:^a list) = // a one-argument constructor member inline x.foodItems = items // and a public read-only property   // a class type that f...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp>   void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::co...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#AutoHotkey
AutoHotkey
sqrt2_a(n) ; function definition is as simple as that { return n?2.0:1.0 }   sqrt2_b(n) { return 1.0 }   napier_a(n) { return n?n:2.0 }   napier_b(n) { return n>1.0?n-1.0:1.0 }   pi_a(n) { return n?6.0:3.0 }   pi_b(n) { return (2.0*n-1.0)**2.0 ; exponentiation operator }   calc(f,expansions) { r:=0,i:=expansions ; A na...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Sidef
Sidef
say 0.75.as_frac #=> 3/4 say 0.518518.as_frac #=> 259259/500000 say 0.9054054.as_frac #=> 4527027/5000000
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Tcl
Tcl
#!/usr/bin/env tclsh   proc dbl2frac {dbl {eps 0.000001}} { for {set den 1} {$den<1024} {incr den} { set num [expr {round($dbl*$den)}] if {abs(double($num)/$den - $dbl) < $eps} break } list $num $den } #-------------------- That's all... the rest is the test suite if {[file tail $argv0] eq [file ...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#EDSAC_order_code
EDSAC order code
[ Copy a string =============   A program for the EDSAC   Copies the source string into storage tank 6, which is assumed to be free, and then prints it from there   Works with Initial Orders 2 ]   T56K GK   [ 0 ] A34@ [ copy the string ] [ 1 ] T192F [ 2 ] H34@ C32@ ...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Elena
Elena
  var src := "Hello"; var dst := src; // copying the reference var copy := src.clone(); // copying the content  
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace ConvertSecondsToCompoundDuration { class Program { static void Main( string[] args ) { foreach ( string arg in args ) { int duration ; bool isValid = int.TryParse( arg , out duration ) ;   if (...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Forth
Forth
include FMS-SI.f include FMS-SILib.f :class Eatable  :m eat ." successful eat " ;m ;class   \ FoodBox is defined without inspecting for the eat message :class FoodBox object-list eatable-types  :m init: eatable-types init: ;m  :m add: ( obj -- ) dup is-kindOf Eatable if eatable-types add: else d...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Fortran
Fortran
  module cg implicit none   type, abstract :: eatable end type eatable   type, extends(eatable) :: carrot_t end type carrot_t   type :: brick_t; end type brick_t   type :: foodbox class(eatable), allocatable :: food contains procedure, public :: add_item => add_item_fb end t...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Go
Go
type eatable interface { eat() }
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#F.23
F#
  // Longest ascending and decending sequences of difference between consecutive primes: Nigel Galloway. April 5th., 2021 let fN g fW=primes32()|>Seq.takeWhile((>)g)|>Seq.pairwise|>Seq.fold(fun(n,i,g)el->let w=fW el in match w>n with true->(w,el::i,g) |_->(w,[el],if List.length i>List.length g then i else g))(0,[],[]) ...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Factor
Factor
USING: arrays assocs formatting grouping io kernel literals math math.primes math.statistics sequences sequences.extras tools.memory.private ;   << CONSTANT: limit 1,000,000 >>   CONSTANT: primes $[ limit primes-upto ]   : run ( n quot -- seq quot ) [ primes ] [ <clumps> ] [ ] tri* '[ differences _ monotonic? ]...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Axiom
Axiom
get(obj) == convergents(obj).1000 -- utility to extract the 1000th value get continuedFraction(1, repeating [1], repeating [2]) :: Float get continuedFraction(2, cons(1,[i for i in 1..]), [i for i in 1..]) :: Float get continuedFraction(3, [i^2 for i in 1.. by 2], repeating [6]) :: Float
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#BBC_BASIC
BBC BASIC
*FLOAT64 @% = &1001010   PRINT "SQR(2) = " ; FNcontfrac(1, 1, "2", "1") PRINT " e = " ; FNcontfrac(2, 1, "N", "N") PRINT " PI = " ; FNcontfrac(3, 1, "6", "(2*N+1)^2") END   REM a$ and b$ are functions of N DEF FNcontfrac(a0, b1, a$, b$) LOCAL N, expr$ R...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Vala
Vala
struct Fraction { public long d; public long n; }   Fraction rat_approx(double f, long md) { long a; long[] h = {0, 1, 0}; long[] k = {1, 0, 0}; long x, d, n = 1; bool neg = false; if (md <= 1) return {1, (long)f}; if (f < 0) { neg = true; f = -f; } while (f != Math.floor(f)) { n <<= 1...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Elixir
Elixir
src = "Hello" dst = src
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Emacs_Lisp
Emacs Lisp
(let* ((str1 "hi") (str1-ref str1) (str2 (copy-sequence str1))) (eq str1 str1-ref) ;=> t (eq str1 str2) ;=> nil (equal str1 str1-ref) ;=> t (equal str1 str2)) ;=> t
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#C.2B.2B
C++
  #include <iostream> #include <vector>   using entry = std::pair<int, const char*>;   void print(const std::vector<entry>& entries, std::ostream& out = std::cout) { bool first = true; for(const auto& e: entries) { if(!first) out << ", "; first = false; out << e.first << " " << e.second;...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Haskell
Haskell
class Eatable a where eat :: a -> String
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Icon_and_Unicon
Icon and Unicon
import Utils # From the UniLib package to get the Class class.   class Eatable:Class() end   class Fish:Eatable(name) method eat(); write("Eating "+name); end end   class Rock:Class(name) method eat(); write("Eating "+name); end end   class FoodBox(A) initially every item := !A do if "Eatable" == ite...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#J
J
coclass'Connoisseur' isEdible=:3 :0 0<nc<'eat__y' )   coclass'FoodBox' create=:3 :0 collection=: 0#y ) add=:3 :0"0 'inedible' assert isEdible_Connoisseur_ y collection=: collection, y EMPTY )
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#FreeBASIC
FreeBASIC
#define UPPER 1000000 #include"isprime.bas"   dim as uinteger champ = 0, record = 0, streak, i, j, n   'first generate all the primes below UPPER redim as uinteger prime(1 to 2) prime(1) = 2 : prime(2) = 3 for i = 5 to UPPER step 2 if isprime(i) then redim preserve prime(1 to ubound(prime) + 1) prim...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Go
Go
package main   import ( "fmt" "rcu" )   const LIMIT = 999999   var primes = rcu.Primes(LIMIT)   func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) ||...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#C
C
/* calculate approximations for continued fractions */ #include <stdio.h>   /* kind of function that returns a series of coefficients */ typedef double (*coeff_func)(unsigned n);   /* calculates the specified number of expansions of the continued fraction * described by the coefficient series f_a and f_b */ double cal...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#VBA
VBA
Function Real2Rational(r As Double, bound As Long) As String   If r = 0 Then Real2Rational = "0/1" ElseIf r < 0 Then Result = Real2Rational(-r, bound) Real2Rational = "-" & Result Else best = 1 bestError = 1E+99 For i = 1 To bound + 1 currentError = Abs(i * r - Round(i * r)) If c...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Erlang
Erlang
Src = "Hello". Dst = Src.
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Euphoria
Euphoria
sequence first = "ABC" sequence newOne = first
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#11l
11l
F orientation(p, q, r) V val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y) I val == 0 R 0 R I val > 0 {1} E 2   F calculateConvexHull(points) [(Int, Int)] result   I points.len < 3 R points   V indexMinX = 0 L(p) points V i = L.index I p.x < points[indexMinX].x ...
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Clojure
Clojure
(require '[clojure.string :as string])   (def seconds-in-minute 60) (def seconds-in-hour (* 60 seconds-in-minute)) (def seconds-in-day (* 24 seconds-in-hour)) (def seconds-in-week (* 7 seconds-in-day))   (defn seconds->duration [seconds] (let [weeks ((juxt quot rem) seconds seconds-in-week) wk (first w...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Java
Java
interface Eatable { void eat(); }
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Julia
Julia
abstract type Edible end eat(::Edible) = "Yum!"   mutable struct FoodBox{T<:Edible} food::Vector{T} end   struct Carrot <: Edible variety::AbstractString end   struct Brick volume::Float64 end   c = Carrot("Baby") b = Brick(125.0) eat(c) eat(b)
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Kotlin
Kotlin
// version 1.0.6   interface Eatable { fun eat() }   class Cheese(val name: String) : Eatable { override fun eat() { println("Eating $name") }   override fun toString() = name }   class Meat(val name: String) : Eatable { override fun eat() { println("Eating $name") }   override...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Haskell
Haskell
import Data.Numbers.Primes (primes)   -- generates consecutive subsequences defined by given equivalence relation consecutives equiv = filter ((> 1) . length) . go [] where go r [] = [r] go [] (h : t) = go [h] t go (y : ys) (h : t) | y `equiv` h = go (h : y : ys) t | otherwise = (y : ys) : go ...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#jq
jq
# For streams of strings or of arrays or of numbers: def add(s): reduce s as $x (null; .+$x);   # Primes less than . // infinite def primes: (. // infinite) as $n | if $n < 3 then empty else 2, (range(3; $n) | select(is_prime)) end;  
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#C.23
C#
using System; using System.Collections.Generic;   namespace ContinuedFraction { class Program { static double Calc(Func<int, int[]> f, int n) { double temp = 0.0; for (int ni = n; ni >= 1; ni--) { int[] p = f(ni); temp = p[1] / (p[0] + temp); ...
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Wren
Wren
import "/rat" for Rat import "/fmt" for Fmt   var tests = [0.9054054, 0.518518, 0.75] for (test in tests) { var r = Rat.fromFloat(test) System.print("%(Fmt.s(-9, test)) -> %(r)") }
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#zkl
zkl
fcn real2Rational(r,bound){ if (r == 0.0) return(0,1); if (r < 0.0){ result := real2Rational(-r, bound); return(-result[0],result[1]); } else { best,bestError := 1,(1.0).MAX; foreach i in ([1 .. bound + 1]){ error := (r*i - (r*i).round()).abs(); if (error < bestError) best,be...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#F.23
F#
let str = "hello" let additionalReference = str let deepCopy = System.String.Copy( str )   printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy ) // prints false
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Factor
Factor
"This is a mutable string." dup ! reference "Let's make a deal!" dup clone  ! copy "New" " string" append .  ! new string "New string"
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Action.21
Action!
DEFINE POINTSIZE="4" TYPE PointI=[INT x,y]   CARD FUNC GetAddr(INT ARRAY points BYTE index) RETURN (points+POINTSIZE*index)   BYTE FUNC GetMinXIndex(INT ARRAY points BYTE pLen) PointI POINTER p BYTE i,index INT minX   p=GetAddr(points,0) minX=p.x index=0 FOR i=1 TO pLen-1 DO p=GetAddr(points,i) ...
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#CLU
CLU
duration = proc (s: int) returns (string) own units: array[string] := array[string]$["wk","d","hr","min","sec"] own sizes: array[int] := array[int]$[2:7,24,60,60]   d: string := "" r: int for i: int in int$from_to_by(5,1,-1) do begin r := s // sizes[i] s := s / sizes...
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#COBOL
COBOL
identification division. program-id. fmt-dura. data division. working-storage section. 1 input-seconds pic 9(8). 1 formatted-duration pic x(30) global. 1 fractions. 2 weeks pic z(3)9. 2 days pic z(3)9. 2 hours pic z(3)9. 2 minutes pic z(3)...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Morfa
Morfa
import morfa.type.traits;   template < T > alias IsEdible = HasMember< T, "eat" >;   template < T > if (IsEdible< T >) struct FoodBox { var food: T[]; }   struct Carrot { func eat(): void {} }   struct Car {}   func main(): void { var carrotBox: FoodBox< Carrot >; // OK carrotBox.food ~= Carrot(); ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Nemerle
Nemerle
using System.Collections.Generic;   interface IEatable { Eat() : void; }   class FoodBox[T] : IEnumerable[T] where T : IEatable { private _foods : list[T] = [];   public this() {}   public this(items : IEnumerable[T]) { this._foods = $[food | food in items]; }   public Add(food : T...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Nim
Nim
type Eatable = concept e eat(e)   FoodBox[e: Eatable] = seq[e]   Food = object name: string count: int   proc eat(x: int) = echo "Eating the int: ", x proc eat(x: Food) = echo "Eating ", x.count, " ", x.name, "s"   var ints = FoodBox[int](@[1,2,3,4,5]) var fs = FoodBox[Food](@[])   fs.add Food(name: "...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Objeck
Objeck
use Collection.Generic;   interface Eatable { method : virtual : Eat() ~ Nil; }   class FoodBox<T : Eatable> { food : List<T>; }   class Plum implements Eatable { method : Eat() ~ Nil { "Yummy Plum!"->PrintLine(); } }   class Genericity { function : Main(args : String[]) ~ Nil { plums : FoodBox<Plum>;...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Julia
Julia
using Primes   function primediffseqs(maxnum = 1_000_000) mprimes = primes(maxnum) diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1])) incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0 for i in 1:length(diffs)-1 foundinc, founddec = false, false ...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Lua
Lua
function findcps(primelist, fcmp) local currlist = {primelist[1]} local longlist, prevdiff = currlist, 0 for i = 2, #primelist do local diff = primelist[i] - primelist[i-1] if fcmp(diff, prevdiff) then currlist[#currlist+1] = primelist[i] if #currlist > #longlist then longlist = currli...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <tuple>   typedef std::tuple<double,double> coeff_t; // coefficients type typedef coeff_t (*func_t)(int); // callback function type   double calc(func_t func, int n) { double a, b, temp = 0; for (; n > 0; --n) { std::tie(a, b) = func(n); temp = b /...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Forth
Forth
\ Allocate two string buffers create stringa 256 allot create stringb 256 allot   \ Copy a constant string into a string buffer s" Hello" stringa place   \ Copy the contents of one string buffer into another stringa count stringb place
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#11l
11l
F print_circle(lo, hi, ndots) V canvas = [[0B] * (2*hi+1)] * (2*hi+1) V i = 0 L i < ndots V x = random:(-hi..hi) V y = random:(-hi..hi) I x^2 + y^2 C lo^2 .. hi^2 canvas[x + hi][y + hi] = 1B i++   L(i) 0 .. 2*hi print(canvas[i].map(j -> I j {‘♦ ’} E ‘ ’).join(‘’)) ...
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Ada
Ada
with Ada.Text_IO; with Ada.Containers.Vectors;   procedure Convex_Hull is   type Point is record X, Y : Integer; end record;   package Point_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Point); use Point_Vectors;   function...
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Common_Lisp
Common Lisp
(defconstant +seconds-in-minute* 60) (defconstant +seconds-in-hour* (* 60 +seconds-in-minute*)) (defconstant +seconds-in-day* (* 24 +seconds-in-hour*)) (defconstant +seconds-in-week* (* 7 +seconds-in-day*))   (defun seconds->duration (seconds) (multiple-value-bind (weeks wk-remainder) (floor seconds +seconds-in-week*...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Objective-C
Objective-C
@protocol Eatable - (void)eat; @end
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#OCaml
OCaml
module type Eatable = sig type t val eat : t -> unit end
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#ooRexx
ooRexx
call dinnerTime "yogurt" call dinnerTime .pizza~new call dinnerTime .broccoli~new     -- a mixin class that defines the interface for being "food", and -- thus expected to implement an "eat" method ::class food mixinclass object ::method eat abstract   ::class pizza subclass food ::method eat Say "mmmmmmmm, pizza".  ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#OxygenBasic
OxygenBasic
  macro Gluttony(vartype, capacity, foodlist) '==========================================   typedef vartype physical   enum food foodlist   type ActualFood sys name physical size physical quantity end type   Class foodbox '============ has ActualFood Item[capacity] sys max   method put(sys f, physical s,q) ...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
prime = Prime[Range[PrimePi[10^6]]]; s = Split[Differences[prime], Less]; max = Max[Length /@ s]; diffs = Select[s, Length/*EqualTo[max]]; seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs; Take[prime, # + {0, 1}] & /@ seqs   s = Split[Differences[prime], Greater]; max = Max[Length /@ s]; diffs = Select[s, Leng...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Nim
Nim
import math, strformat, sugar   const N = 1_000_000   #################################################################################################### # Erathostenes sieve.   var composite: array[2..N, bool] # Initialized to false i.e. prime.   for n in 2..int(sqrt(float(N))): if not composite[n]: for k in...
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Pari.2FGP
Pari/GP
showPrecPrimes(p, n)= { my(v=vector(n)); v[n]=p; forstep(i=n-1,1,-1, v[i]=precprime(v[i+1]-1) ); for(i=1,n, print1(v[i]" ")); } list(lim)= { my(p=3,asc,dec,ar,dr,arAt=3,drAt=3,last=2); forprime(q=5,lim, my(g=q-p); if(g<last, asc=0; if(desc++>dr, dr=desc; drAt=q ...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Chapel
Chapel
proc calc(f, n) { var r = 0.0;   for k in 1..n by -1 { var v = f.pair(k); r = v(2) / (v(1) + r); }   return f.pair(0)(1) + r; }   record Sqrt2 { proc pair(n) { return (if n == 0 then 1 else 2, 1); } ...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Clojure
Clojure
  (defn cfrac [a b n] (letfn [(cfrac-iter [[x k]] [(+ (a k) (/ (b (inc k)) x)) (dec k)])] (ffirst (take 1 (drop (inc n) (iterate cfrac-iter [1 n]))))))   (def sq2 (cfrac #(if (zero? %) 1.0 2.0) (constantly 1.0) 100)) (def e (cfrac #(if (zero? %) 2.0 %) #(if (= 1 %) 1.0 (double (dec %))) 100)) (def pi (cfrac #(i...
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Fortran
Fortran
str2 = str1
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s As String = "This is a string" Dim t As String = s ' a separate copy of the string contents has been made as can be seen from the addresses Print s, StrPtr(s) Print t, StrPtr(t) ' to refer to the same string a pointer needs to be used Dim u As String Ptr = @s Print Print *u, StrPtr(*u) Sleep
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Action.21
Action!
PROC DrawCircle(BYTE rmin,rmax,max,x0,y0) BYTE count,limit INT x,y,r2,rmin2,rmax2   limit=rmax*2+1 rmin2=rmin*rmin rmax2=rmax*rmax count=0 WHILE count<max DO x=Rand(limit) y=Rand(limit) x==-rmax y==-rmax r2=x*x+y*y IF r2>=rmin2 AND r2<=rmax2 THEN Plot(x+x0,y+y0) count==+1 ...
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Arturo
Arturo
define :point [x y][]   orientation: function [P Q R][ val: sub (Q\y - P\y)*(R\x - Q\x) (Q\x - P\x)*(R\y - Q\y) if val=0 -> return 0 if val>0 -> return 1 return 2 ]   calculateConvexHull: function [points][ result: new []   if 3 > size points [ loop points 'p -> 'result ++ p ]   ...
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#D
D
  import std.stdio, std.conv, std.algorithm;   immutable uint SECSPERWEEK = 604_800; immutable uint SECSPERDAY = 86_400; immutable uint SECSPERHOUR = 3_600; immutable uint SECSPERMIN = 60;   string ConvertSeconds(in uint seconds) { uint rem = seconds;   uint weeks = rem / SECSPERWEEK; rem %= SECSPERWEEK; ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Phix
Phix
include builtins\structs.e as structs   class foodbox sequence contents = {} procedure add(class food) -- (aside: class food is 100% abstract here... -- ie: class is *the* root|anything class, -- and food is just an arbitrary name) integer t = structs:get_field_flags(...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#PicoLisp
PicoLisp
(class +Eatable)   (dm eat> () (prinl "I'm eatable") )     (class +FoodBox) # obj   (dm set> (Obj) (unless (method 'eat> Obj) # Check if the object is eatable (quit "Object is not eatable" Obj) ) (=: obj Obj) ) # If so, set the object     (let (Box (new '(+FoodBo...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Racket
Racket
#lang racket (module+ test (require tests/eli-tester))   ;; This is all that an object should need to properly implement. (define edible<%> (interface () [eat (->m void?)]))   (define (generic-container<%> containee/c) (interface () [contents (->m (listof containee/c))] [insert (->m containee/c void?)] ...
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Raku
Raku
subset Eatable of Any where { .^can('eat') };   class Cake { method eat() {...} }   role FoodBox[Eatable] { has %.foodbox; }   class Yummy does FoodBox[Cake] { } # composes correctly # class Yucky does FoodBox[Int] { } # fails to compose   my Yummy $foodbox .= new; say $foodbox;
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'primes'; use List::AllUtils <indexes max>;   my $limit = 1000000; my @primes = @{primes( $limit )};   sub runs { my($op) = @_; my @diff = my $diff = my $run = 1; push @diff, map { my $next = $primes[$_] - $primes[$_ - 1]; if ($op eq ...
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#COBOL
COBOL
identification division. program-id. show-continued-fractions.   environment division. configuration section. repository. function continued-fractions function all intrinsic.   procedure division. fractions-main.   display "Square root 2 appr...