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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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); PROC bnap = (INT n) INT: (n = 1 | 1 | n - 1);   PROC api = (INT n) INT: (n = 0 | 3 | 6); PROC bpi = (INT n) INT: (n = 1 | 1 | (2 * n - 1) ** 2);   INT precision = 10000;   print (("Precision: ", precision, newline)); print (("Sqr(2): ", cf(precision, asqr2, bsqr2), newline)); print (("Napier: ", cf(precision, anap, bnap), newline)); print (("Pi: ", cf(precision, api, bpi)))  
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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.'   do j=1 for 2; if \datatype(n.j, 'N') then call er "argument isn't numeric:" n.j end /*j*/ /* [↑] validate arguments: n.1 n.2 */   if n.2=0 then call er "divisor can't be zero." /*Whoa! We're dividing by zero ! */ say 'old =' space(orig) /*display the original fraction. */ say 'new =' rat(n.1/n.2) /*display the result ──► terminal. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ er: say; say '***error***'; say; say arg(1); say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ rat: procedure; parse arg x 1 _x,y; if y=='' then y = 10**(digits()-1) b=0; g=0; a=1; h=1 /* [↑] Y is the tolerance.*/ do while a<=y & g<=y; n=trunc(_x) _=a; a=n*a+b; b=_ _=g; g=n*g+h; h=_ if n=_x | a/g=x then do; if a>y | g>y then iterate b=a; h=g; leave end _x=1/(_x-n) end /*while*/ if h==1 then return b /*don't return number ÷ by 1.*/ return b'/'h /*proper or improper fraction. */
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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: static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char); };   struct potato { void eat(); };   struct brick {};   template<typename T> class FoodBox { //Using static assertion to prohibit non-edible types static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox");   //Rest of class definition };   int main() { FoodBox<potato> lunch;   //Following leads to compile-time error //FoodBox<brick> practical_joke; }
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 (thing) "Returns true if there are eat methods defined for thing." (not (endp (compute-applicable-methods #'eat (list thing)))))   (deftype eatable () "Eatable objects are those satisfying eatable-p." '(satisfies eatable-p))   (defun make-food-box (extra-type &rest array-args) "Returns an array whose element-type is (and extra-type food). array-args should be suitable for MAKE-ARRAY, and any provided element-type keyword argument is ignored." (destructuring-bind (dimensions &rest array-args) array-args (apply 'make-array dimensions :element-type `(and ,extra-type food) array-args)))   (defun make-eatable-food-box (&rest array-args) "Return an array whose elements are declared to be of type (and eatable food)." (apply 'make-food-box 'eatable array-args))
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 are multiple sequences of the same length, only the first need be shown.
#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; [ 1 : n ]INT p; p[ 1 ] := no; p[ 2 ] := yes; FOR i FROM 3 BY 2 TO n DO p[ i ] := yes OD; FOR i FROM 4 BY 2 TO n DO p[ i ] := no OD; FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO IF p[ i ] = yes THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := no OD FI OD; # replace the sieve with a list # INT p pos := 0; FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD; p[ 1 : p pos ] END # prime list # ; # shos the results of a search # PROC show sequence = ( []INT primes, STRING seq name, INT seq start, seq length )VOID: BEGIN print( ( " The longest sequence of primes with " , seq name , " differences contains " , whole( seq length, 0 ) , " primes" , newline , " First such sequence (differences in brackets):" , newline , " " ) ); print( ( whole( primes[ seq start ], 0 ) ) ); FOR p FROM seq start + 1 TO seq start + ( seq length - 1 ) DO print( ( " (", whole( ABS( primes[ p ] - primes[ p - 1 ] ), 0 ), ") ", whole( primes[ p ], 0 ) ) ) OD; print( ( newline ) ) END # show seuence # ; # find the longest sequence of primes where the successive differences are ascending/descending # PROC find sequence = ( []INT primes, BOOL ascending, REF INT seq start, seq length )VOID: BEGIN seq start := seq length := 0; INT start diff = IF ascending THEN 0 ELSE UPB primes + 1 FI; FOR p FROM LWB primes TO UPB primes DO INT prev diff := start diff; INT length := 1; FOR s FROM p + 1 TO UPB primes WHILE INT diff = ABS ( primes[ s ] - primes[ s - 1 ] ); IF ascending THEN diff > prev diff ELSE diff < prev diff FI DO length +:= 1; prev diff := diff OD; IF length > seq length THEN # found a longer sequence # seq length := length; seq start := p FI OD END # find sequence #; INT max number = 1 000 000; []INT primes = prime list( max number ); INT asc length := 0; INT asc start := 0; INT desc length := 0; INT desc start := 0; find sequence( primes, TRUE, asc start, asc length ); find sequence( primes, FALSE, desc start, desc length ); # show the sequences # print( ( "For primes up to ", whole( max number, 0 ), newline ) ); show sequence( primes, "ascending", asc start, asc length ); show sequence( primes, "descending", desc start, desc length ) 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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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)? -> to :floating n-1 -> 1.0 @[a, b] ]   Pi: function [n][ a: (n > 0)? -> 6.0 -> 3.0 b: ((2 * to :floating n)-1) ^ 2 @[a, b] ]   print calc 'sqrt2 20 print calc 'napier 15 print calc 'Pi 10000
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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()).abs() < std::f64::EPSILON { return [n.round() as isize, 1] } let mut a : isize = 0; let mut b : isize = 1; let mut c : isize = n.ceil() as isize; let mut d : isize = 1; let aux1 = isize::max_value()/2; while c < aux1 && d < aux1 { let aux2 : f64 = (a as f64 + c as f64)/(b as f64 + d as f64); if (n - aux2).abs() < std::f64::EPSILON { break } if n > aux2 { a = a + c; b = b + d; } else { c = a + c; d = b + d; } } // Make sure that the fraction is irreducible let gcd = (a+c).gcd(&(b+d)); if flag_neg { [-(a + c)/gcd, (b + d)/gcd] } else { [(a + c)/gcd, (b + d)/gcd] } }   #[test] fn test1 () { // Test the function with 1_000_000 random decimal numbers let mut rng = rand::thread_rng(); for _i in 1..1_000_000 { let number = rng.gen::<f64>(); let result = decimal_to_rational(number); assert!((number - (result[0] as f64)/(result[1] as f64)).abs() < std::f64::EPSILON); assert!(result[0].gcd(&result[1]) == 1); } }   fn main () { let mut rng = rand::thread_rng(); for _i in 1..10 { let number = rng.gen::<f64>(); let result = decimal_to_rational(number); if result[1] == 1 { println!("{} -> {}", number, result[0]) } else { println!("{} -> {}/{}", number, result[0], result[1]) } } for i in [-0.9054054, 0.518518, -0.75, 0.5185185185185185, -0.9054054054054054, 0.0, 1.0, 2.0].iter() { let result = decimal_to_rational(*i as f64); if result[1] == 1 { println!("{} = {}",*i, result[0]) } else { println!("{} = {}/{}", *i, result[0], result[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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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) %} {% end %} end end   FoodBox.new([Apple.new, Apple.new]) FoodBox.new([Apple.new, Carrot.new]) FoodBox.new([Apple.new, Carrot.new, 123])
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 allowed }
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 are multiple sequences of the same length, only the first need be shown.
#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, ng, d, ld = 0; var desc = new string[] { "A", "", "De" }; int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 }; WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray(); for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++; else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; } for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n {2} ", desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r])) Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } }   class PG { public static IEnumerable<TG> Primes(int lim) { bool[] flags = new bool[lim + 1]; int j = 3, lj = 2; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; } } }
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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} // (* ****** ****** *)   fun calc ( f: frac, n: int ) : double = let // (* ** recursive definition of the approximation *) fun loop ( n: int, r: double ) : double = ( if n = 0 then f.a(0) + r else loop (n - 1, f.b(n) / (f.a(n) + r)) // end of [if] ) // in loop (n, 0.0) end // end of [calc]   (* ****** ****** *)   val sqrt2 = @{ a= lam (n: int): double => if n = 0 then 1.0 else 2.0 , b= lam (n: int): double => 1.0 } (* end of [val] *)   val napier = @{ a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n , b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0 } (* end of [val] *)   val pi = @{ a= lam (n: int): double => if n = 0 then 3.0 else 6.0 , b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end }   (* ****** ****** *)   implement main0 () = ( println! ("sqrt2 = ", calc(sqrt2, 100)); println! ("napier = ", calc(napier, 100)); println! (" pi = ", calc( pi , 100)); ) (* end of [main0] *)
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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(bigRational parse "0.(846153)"); writeln(bigRational parse "0.9054054"); writeln(bigRational parse "0.518518"); writeln(bigRational parse "0.14285714285714"); writeln(bigRational parse "3.14159265358979"); writeln(bigRational parse "2.718281828"); writeln(bigRational parse "31.415926536"); writeln(bigRational parse "0.000000000"); end func;
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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 noting that direct output to stdout would be even simpler. */ char* seconds2string(unsigned long seconds) { int i;   const unsigned long s = 1; const unsigned long m = 60 * s; const unsigned long h = 60 * m; const unsigned long d = 24 * h; const unsigned long w = 7 * d;   const unsigned long coeff[5] = { w, d, h, m, s }; const char units[5][4] = { "wk", "d", "hr", "min", "sec" };   static char buffer[256]; char* ptr = buffer;   for ( i = 0; i < 5; i++ ) { unsigned long value; value = seconds / coeff[i]; seconds = seconds % coeff[i]; if ( value ) { if ( ptr != buffer ) ptr += sprintf(ptr, ", "); ptr += sprintf(ptr,"%lu %s",value,units[i]); } }   return buffer; }   /* * Main function for seconds2string program. */ int main(int argc, char argv[]) { unsigned long seconds;   if ( (argc < 2) && scanf( "%lu", &seconds ) || (argc >= 2) && sscanf( argv[1], "%lu", & seconds ) ) { printf( "%s\n", seconds2string(seconds) ); return EXIT_SUCCESS; }   return EXIT_FAILURE; }
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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() { return [].diverge(Eatable) # A guard-constrained list }
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 fullfills the member constraint type Banana() = member x.eat() = "I'm eating a banana."   // an instance of a Banana FoodBox let someBananas = FoodBox [Banana(); Banana()]
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 are multiple sequences of the same length, only the first need be shown.
#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::cout << '\n'; }   int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 nasty trick: the names of the two coefficient functions are generated dynamically ; a dot surrounded by spaces means string concatenation f_a:=f . "_a",f_b:=f . "_b"   while i>0 { ; You can see two dynamic function calls here r:=%f_b%(i)/(%f_a%(i)+r) i-- }   return %f_a%(0)+r }   Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("napier", 1000) . "`npi = " . calc("pi", 1000)
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 tail [info script]]} { foreach {test -> expected} { {dbl2frac 0.518518} -> {42 81} {dbl2frac 0.75} -> {3 4} {dbl2frac 0.9054054} -> {67 74} } { catch $test res if {$res ne $expected} { puts "$test -> $res, expected $expected" } } }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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@ S32@ E17@ T31@ A@ A33@ T@ A1@ A33@ T1@ A2@ A33@ T2@ E@ [ 17 ] O192F [ print the copy ] [ 18 ] H192F C32@ S32@ E30@ T31@ A17@ A33@ T17@ A18@ A33@ T18@ E17@ [ 30 ] ZF [ 31 ] PF [ 32 ] PD [ 33 ] P1F [ 34 ] *F RF OF SF EF TF TF AF  !F CF OF DF ED   EZPF
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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 ( !isValid ) { Console.Error.WriteLine( "ERROR: Not an integer: {0}" , arg ) ; } if ( duration < 0 ) { Console.Error.WriteLine( "ERROR: duration must be non-negative" , arg ) ; }   Console.WriteLine(); Console.WriteLine( "{0:#,##0} seconds ==> {1}" , duration , FormatAsDuration(duration) ) ;   } }   private static string FormatAsDuration( int duration ) { if ( duration < 0 ) throw new ArgumentOutOfRangeException("duration") ; return string.Join( ", " , GetDurationParts(duration) ) ; }   private static IEnumerable<string> GetDurationParts( int duration ) { var parts = new[] { new { Name="wk" , Length = 7*24*60*60*1 , } , new { Name="d" , Length = 24*60*60*1 , } , new { Name="h" , Length = 60*60*1 , } , new { Name="m" , Length = 60*1 , } , new { Name="s" , Length = 1 , } , } ;   foreach ( var part in parts ) { int n = Math.DivRem( duration , part.Length , out duration ) ; if ( n > 0 ) yield return string.Format( "{0} {1}" , n , part.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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 drop ." not an eatable type " then ;m  :m test begin eatable-types each: while eat repeat ;m ;class   FoodBox aFoodBox Eatable aEatable aEatable aFoodBox add: \ add the e1 object to the object-list aFoodBox test \ => successful eat   :class brick  :m eat cr ." successful eat " ;m ;class   brick abrick \ create an object that is not eatable abrick aFoodBox add: \ => not an eatable type   :class apple <super Eatable ;class   apple anapple anapple aFoodBox add: aFoodBox test \ => successful eat successful 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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 type foodbox   contains   subroutine add_item_fb(this, f) class(foodbox), intent(inout) :: this class(eatable), intent(in) :: f allocate(this%food, source=f) end subroutine add_item_fb end module cg     program con_gen use cg implicit none   type(carrot_t) :: carrot type(brick_t) :: brick type(foodbox) :: fbox   ! Put a carrot into the foodbox call fbox%add_item(carrot)   ! Try to put a brick in - results in a compiler error call fbox%add_item(brick)   end program con_gen    
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 are multiple sequences of the same length, only the first need be shown.
#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,[],[]) for i in [1;2;6;12;18;100] do let _,_,g=fN(i*1000000)(fun(n,g)->g-n) in printfn "Longest ascending upto %d000000->%d:" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf "%d (%d) %d " n (g-n) g); printfn "" let _,_,g=fN(i*1000000)(fun(n,g)->n-g) in printfn "Longest decending upto %d000000->%d:" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf "%d (%d) %d " n (g-n) g); printfn ""  
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 are multiple sequences of the same length, only the first need be shown.
#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? ] ; inline   : max-run ( quot -- n ) 1 swap '[ 1 + dup _ run find drop ] loop 1 - ; inline   : runs ( quot -- seq ) [ max-run ] keep run filter ; inline   : .run ( seq -- ) dup differences [ [ commas ] map ] bi@ [ "(" ")" surround ] map 2array round-robin " " join print ;   : .runs ( quot -- ) [ runs ] keep [ < ] = "rising" "falling" ? limit commas "Largest run(s) of %s gaps between primes less than %s:\n" printf [ .run ] each ; inline   [ < ] [ > ] [ .runs nl ] bi@
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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$ REPEAT N += 1 expr$ += STR$(EVAL(a$)) + "+" + STR$(EVAL(b$)) + "/(" UNTIL LEN(expr$) > (65500 - N) = a0 + b1 / EVAL (expr$ + "1" + STRING$(N, ")"))
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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; f *= 2; } d = (long)f; for (int i = 0; i < 64; i++) { a = (n != 0) ? d / n : 0; if (i != 0 && a == 0) break; x = d; d = n; n = x %n; x = a; if (k[1] * a + k[0] >= md) { x = (md - k[0]) / k[1]; if (x * 2 >= a || k[1] >= md) i = 65; else break; } h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } return {k[1], neg ? -h[1] : h[1]}; }   void main() { double f;   print("f = %16.14f\n", f = 1.0/7); for (int i = 1; i < 20000000; i *= 16) { print("denom <= %11d: ", i); var r = rat_approx(f, i); print("%11ld/%ld\n", r.n, r.d); }   print("f = %16.14f\n", f = Math.atan2(1,1) * 4); for (int i = 1; i < 20000000; i *= 16) { print("denom <= %11d: ", i); var r = rat_approx(f, i); print("%11ld/%ld\n", r.n, r.d); } }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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; } out << '\n'; }   std::vector<entry> convert(int seconds) { static const entry time_table[] = { {7*24*60*60, "wk"}, {24*60*60, "d"}, {60*60, "hr"}, {60, "min"}, {1, "sec"} }; std::vector<entry> result; for(const auto& e: time_table) { int time = seconds / e.first; if(time != 0) result.emplace_back(time, e.second); seconds %= e.first; } return result; }   int main() { std::cout << " 7259 sec is "; print(convert( 7259)); std::cout << " 86400 sec is "; print(convert( 86400)); std::cout << "6000000 sec is "; print(convert(6000000)); }
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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" == item.Type() then next else bad := "yes" return /bad end   procedure main() if FoodBox([Fish("salmon")]) then write("Edible") else write("Inedible") if FoodBox([Rock("granite")]) then write("Edible") else write("Inedible") 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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 are multiple sequences of the same length, only the first need be shown.
#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) prime(ubound(prime)) = i end if next i n = ubound(prime)   'now look for the longest streak of ascending primes for i = 2 to n-1 j = i + 1 streak = 1 while j<=n andalso prime(j)-prime(j-1) > prime(j-1)-prime(j-2) streak += 1 j+=1 wend if streak > record then champ = i-1 record = streak end if next i   print "The longest sequence of ascending primes (with their difference from the last one) is:" for i = champ+1 to champ+record print prime(i-1);" (";prime(i)-prime(i-1);") "; next i print prime(i-1) : print 'now for the descending ones   record = 0 : champ = 0 for i = 2 to n-1 j = i + 1 streak = 1 while j<=n andalso prime(j)-prime(j-1) < prime(j-1)-prime(j-2) 'identical to above, but for the inequality sign streak += 1 j+=1 wend if streak > record then champ = i-1 record = streak end if next i   print "The longest sequence of descending primes (with their difference from the last one) is:" for i = champ+1 to champ+record print prime(i-1);" (";prime(i)-prime(i-1);") "; next i print prime(i-1)
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 are multiple sequences of the same length, only the first need be shown.
#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) || (dir == "descending" && d >= pd) { if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } currSeq = []int{primes[i-1], primes[i]} } else { currSeq = append(currSeq, primes[i]) } pd = d } if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":") for _, ls := range longSeqs { var diffs []int for i := 1; i < len(ls); i++ { diffs = append(diffs, ls[i]-ls[i-1]) } for i := 0; i < len(ls)-1; i++ { fmt.Print(ls[i], " (", diffs[i], ") ") } fmt.Println(ls[len(ls)-1]) } fmt.Println() }   func main() { fmt.Println("For primes < 1 million:\n") for _, dir := range []string{"ascending", "descending"} { longestSeq(dir) } }
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 calc(coeff_func f_a, coeff_func f_b, unsigned expansions) { double a, b, r; a = b = r = 0.0;   unsigned i; for (i = expansions; i > 0; i--) { a = f_a(i); b = f_b(i); r = b / (a + r); } a = f_a(0);   return a + r; }   /* series for sqrt(2) */ double sqrt2_a(unsigned n) { return n ? 2.0 : 1.0; }   double sqrt2_b(unsigned n) { return 1.0; }   /* series for the napier constant */ double napier_a(unsigned n) { return n ? n : 2.0; }   double napier_b(unsigned n) { return n > 1.0 ? n - 1.0 : 1.0; }   /* series for pi */ double pi_a(unsigned n) { return n ? 6.0 : 3.0; }   double pi_b(unsigned n) { double c = 2.0 * n - 1.0;   return c * c; }   int main(void) { double sqrt2, napier, pi;   sqrt2 = calc(sqrt2_a, sqrt2_b, 1000); napier = calc(napier_a, napier_b, 1000); pi = calc(pi_a, pi_b, 1000);   printf("%12.10g\n%12.10g\n%12.10g\n", sqrt2, napier, pi);   return 0; }
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 currentError < bestError Then best = i bestError = currentError If bestError < 1 / bound Then GoTo SkipLoop End If Next i SkipLoop: Real2Rational = Round(best * r) & "/" & best End If End Function   Sub TestReal2Rational() Debug.Print "0.75" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(0.75, CLng(Order)); Next i Debug.Print   Debug.Print "0.518518" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(0.518518, CLng(Order)); Next i Debug.Print   Debug.Print "0.9054054" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(0.9054054, CLng(Order)); Next i Debug.Print   Debug.Print "0.142857143" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(0.142857143, CLng(Order)); Next i Debug.Print   Debug.Print "3.141592654" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(3.141592654, CLng(Order)); Next i Debug.Print   Debug.Print "2.718281828" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(2.718281828, CLng(Order)); Next i Debug.Print   Debug.Print "-0.423310825" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(-0.423310825, CLng(Order)); Next i Debug.Print   Debug.Print "31.415926536" & ":"; For i = 0 To 5 Order = CDbl(10) ^ CDbl(i) Debug.Print " " & Real2Rational(31.415926536, CLng(Order)); Next i End Sub  
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15). See also Convex Hull (youtube) http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
#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 indexMinX = i   V p = indexMinX V q = 0   L result.append(points[p])   q = (p + 1) % points.len   L(i) 0 .< points.len I orientation(points[p], points[i], points[q]) == 2 q = i   p = q I p == indexMinX L.break   R result   V points = [(16, 3), (12, 17), (0, 6), (-4, -6), (16, 6), (16, -7), (17, -4), (5, 19), (19, -8), (3, 16), (12, 13), (3, -4), (17, 5), (-3, 15), (-3, -9), (0, 11), (-9, -3), (-4, -2), (12, 10)]   V hull = calculateConvexHull(points) L(i) hull print(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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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 weeks) days ((juxt quot rem) (last weeks) seconds-in-day) d (first days) hours ((juxt quot rem) (last days) seconds-in-hour) hr (first hours) min (quot (last hours) seconds-in-minute) sec (rem (last hours) seconds-in-minute)] (string/join ", " (filter #(not (string/blank? %)) (conj [] (when (> wk 0) (str wk " wk")) (when (> d 0) (str d " d")) (when (> hr 0) (str hr " hr")) (when (> min 0) (str min " min")) (when (> sec 0) (str sec " sec")))))))   (seconds->duration 7259) (seconds->duration 86400) (seconds->duration 6000000)
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 fun toString() = name }   class FoodBox<T: Eatable> { private val foodList = mutableListOf<T>()   fun add(food: T) { foodList.add(food) }   override fun toString() = foodList.toString() }   fun main(args: Array<String>) { val cheddar = Cheese("cheddar") val feta = Cheese("feta") val cheeseBox = FoodBox<Cheese>() cheeseBox.add(cheddar) cheeseBox.add(feta) println("CheeseBox contains : $cheeseBox")   val beef = Meat("beef") val ham = Meat("ham") val meatBox = FoodBox<Meat>() meatBox.add(beef) meatBox.add(ham) println("MeatBox contains : $meatBox")   cheddar.eat() beef.eat() println("Full now!") }
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 are multiple sequences of the same length, only the first need be shown.
#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 [h] t   -- finds maximal values in a list and returns the first one maximumBy g (h : t) = foldr f h t where f r x = if g r < g x then x else r   -- the task implementation task ord n = reverse $ p + s : p : (fst <$> rest) where (p, s) : rest = maximumBy length $ consecutives (\(_, a) (_, b) -> a `ord` b) $ differences $ takeWhile (< n) primes differences l = zip l $ zipWith (-) (tail l) l
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 are multiple sequences of the same length, only the first need be shown.
#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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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); } return f(0)[0] + temp; }   static void Main(string[] args) { List<Func<int, int[]>> fList = new List<Func<int, int[]>>(); fList.Add(n => new int[] { n > 0 ? 2 : 1, 1 }); fList.Add(n => new int[] { n > 0 ? n : 2, n > 1 ? (n - 1) : 1 }); fList.Add(n => new int[] { n > 0 ? 6 : 3, (int) Math.Pow(2 * n - 1, 2) });   foreach (var f in fList) { Console.WriteLine(Calc(f, 200)); } } } }
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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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 exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#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,bestError = i,error; } return((r*best).round().toInt(),best); } }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15). See also Convex Hull (youtube) http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
#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) IF p.x<minX THEN minX=p.x index=i FI OD RETURN (index)   BYTE FUNC Orientation(PointI POINTER p,q,r) INT v v=(q.y-p.y)*(r.x-q.x) v==-(q.x-p.x)*(r.y-q.y)   IF v=0 THEN RETURN (0) ELSEIF v>0 THEN RETURN (1) FI RETURN (2)   PROC ConvexHull(INT ARRAY points BYTE pLen INT ARRAY res BYTE POINTER resLen) PointI POINTER pSrc,pDst,p1,p2,p3 BYTE minIndex,i,p,q   IF pLen<3 THEN resLen^=pLen MoveBlock(res,points,pLen*POINTSIZE) RETURN FI   resLen^=0 minIndex=GetMinXIndex(points,pLen) p=minIndex q=0 DO pSrc=GetAddr(points,p) pDst=GetAddr(res,resLen^) pDst.x=pSrc.x pDst.y=pSrc.y resLen^==+1   q=(p+1) MOD pLen FOR i=0 TO pLen-1 DO p1=GetAddr(points,p) p2=GetAddr(points,i) p3=GetAddr(points,q) IF Orientation(p1,p2,p3)=2 THEN q=i FI OD p=q UNTIL p=minIndex OD RETURN   PROC PrintPoints(INT ARRAY points BYTE len) PointI POINTER p BYTE i   FOR i=0 TO len-1 DO p=GetAddr(points,i) PrintF("(%I,%I) ",p.x,p.y) OD RETURN   PROC Main() INT ARRAY points=[ 16 3 12 17 0 6 65532 65530 16 6 16 65529 17 65532 5 19 19 65528 3 16 12 13 3 65532 17 5 65533 15 65533 65527 0 11 65527 65533 65532 65534 12 10] INT ARRAY result(38) BYTE pLen=[19],rlen   ConvexHull(points,pLen,result,@rlen)   PrintE("Points:") PrintPoints(points,pLen) PutE() PutE() PrintE("Convex hull:") PrintPoints(result,rLen) RETURN
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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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[i] end except when bounds: r := s end if r ~= 0 then d := ", " || int$unparse(r) || " " || units[i] || d end end return(string$rest(d,3)) end duration   start_up = proc () po: stream := stream$primary_output() tests: array[int] := array[int]$[7259,86400,6000000]   for test: int in array[int]$elements(tests) do stream$putl(po, int$unparse(test) || " => " || duration(test)) end end start_up
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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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)9. 2 seconds pic z(3)9. 1 . 2 weeks-str pic x(4) value "wk". 2 days-str pic x(4) value "d". 2 hours-str pic x(4) value "hr". 2 minutes-str pic x(4) value "min". 2 seconds-str pic x(4) value "sec". 1 work binary global. 2 str-pos pic 9(4). 2 chars-transferred pic 9(4). procedure division. begin. display "Enter duration (seconds): " no advancing accept input-seconds divide input-seconds by 60 giving input-seconds remainder seconds divide input-seconds by 60 giving input-seconds remainder minutes divide input-seconds by 24 giving input-seconds remainder hours divide input-seconds by 7 giving weeks remainder days move 1 to str-pos call "fmt" using weeks weeks-str call "fmt" using days days-str call "fmt" using hours hours-str call "fmt" using minutes minutes-str call "fmt" using seconds seconds-str display formatted-duration stop run .   identification division. program-id. fmt. data division. working-storage section. 77 nothing pic x. linkage section. 1 formatted-value pic x(4). 1 duration-size pic x(4). procedure division using formatted-value duration-size. begin. if function numval (formatted-value) not = 0 perform insert-comma-space unstring formatted-value delimited all space into nothing formatted-duration (str-pos:) count chars-transferred add chars-transferred to str-pos string space delimited size duration-size delimited space into formatted-duration pointer str-pos end-if exit program .   insert-comma-space. if str-pos > 1 move ", " to formatted-duration (str-pos:) add 2 to str-pos end-if . end program fmt. end program fmt-dura.
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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(); // Adds a carrot   // var carBox: FoodBox< Car >; // Not allowed static assert( not trait(compiles, func() { var carBox: FoodBox< Car >; } )); }
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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) : FoodBox[T] { FoodBox(food::_foods); }   public GetEnumerator() : IEnumerator[T] { _foods.GetEnumerator(); } }   class Apple : IEatable { public this() {}   public Eat() : void { System.Console.WriteLine("nom..nom..nom"); } }   mutable appleBox = FoodBox(); repeat(3) { appleBox = appleBox.Add(Apple()); }   foreach (apple in appleBox) apple.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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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: "Hamburger", count: 3) fs.add Food(name: "Cheeseburger", count: 5)   for f in fs: eat(f)
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 are multiple sequences of the same length, only the first need be shown.
#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 for j in i+1:length(diffs) if !foundinc && diffs[j] <= diffs[j - 1] if (runlength = j - i) > bestinclength bestinclength, incstart = runlength, i end foundinc = true end if !founddec && diffs[j] >= diffs[j - 1] if (runlength = j - i) > bestdeclength bestdeclength, decstart = runlength, i end founddec = true end foundinc && founddec && break end end println("Ascending: ", mprimes[incstart:incstart+bestinclength], " Diffs: ", diffs[incstart:incstart+bestinclength-1]) println("Descending: ", mprimes[decstart:decstart+bestdeclength], " Diffs: ", diffs[decstart:decstart+bestdeclength-1]) end   primediffseqs()  
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 are multiple sequences of the same length, only the first need be shown.
#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 = currlist end else currlist = {primelist[i-1], primelist[i]} end prevdiff = diff end return longlist end   primegen:generate(nil, 1000000) cplist = findcps(primegen.primelist, function(a,b) return a>b end) print("ASC ("..#cplist.."): ["..table.concat(cplist, " ").."]") cplist = findcps(primegen.primelist, function(a,b) return a<b end) print("DESC ("..#cplist.."): ["..table.concat(cplist, " ").."]")
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 / (a + temp); } std::tie(a, b) = func(0); return a + temp; }   coeff_t sqrt2(int n) { return coeff_t(n > 0 ? 2 : 1, 1); }   coeff_t napier(int n) { return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1); }   coeff_t pi(int n) { return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1)); }   int main() { std::streamsize old_prec = std::cout.precision(15); // set output digits std::cout << calc(sqrt2, 20) << '\n' << calc(napier, 15) << '\n' << calc(pi, 10000) << '\n' << std::setprecision(old_prec); // reset precision }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#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(‘’))   print_circle(10, 15, 100)
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 (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15). See also Convex Hull (youtube) http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
#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 Find_Convex_Hull (Vec : in Vector) return Vector is   function Counter_Clock_Wise (A, B, C : in Point) return Boolean is ((B.X - A.X) * (C.Y - A.Y) > (B.Y - A.Y) * (C.X - A.X));   function Less_Than (Left, Right : Point) return Boolean is (Left.X < Right.X);   package Sorter is new Point_Vectors.Generic_Sorting (Less_Than);   Sorted : Vector := Vec; Result : Vector := Empty_vector; use type Ada.Containers.Count_Type; begin if Vec = Empty_Vector then return Empty_Vector; end if;   Sorter.Sort (Sorted);   -- Lower hull for Index in Sorted.First_Index .. Sorted.Last_Index loop while Result.Length >= 2 and then not Counter_Clock_Wise (Result (Result.Last_Index - 1), Result (Result.Last_Index), Sorted (Index)) loop Result.Delete_Last; end loop; Result.Append (Sorted (Index)); end loop;   -- Upper hull declare T : constant Ada.Containers.Count_Type := Result.Length + 1; begin for Index in reverse Sorted.First_Index .. Sorted.Last_Index loop while Result.Length >= T and then not Counter_Clock_Wise (Result (Result.Last_Index - 1), Result (Result.Last_Index), Sorted (Index)) loop Result.Delete_Last; end loop; Result.Append (Sorted (Index)); end loop; end;   Result.Delete_Last; return Result; end Find_Convex_Hull;   procedure Show (Vec : in Vector) is use Ada.Text_IO; begin Put ("[ "); for Point of Vec loop Put ("(" & Point.X'Image & "," & Point.Y'Image & ")"); end loop; Put (" ]"); end Show;   Vec : constant Vector := (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) & (12,10); begin Show (Find_Convex_Hull (Vec)); Ada.Text_IO.New_Line; end Convex_Hull;
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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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*) (multiple-value-bind (days d-remainder) (floor wk-remainder +seconds-in-day*) (multiple-value-bind (hours hr-remainder) (floor d-remainder +seconds-in-hour*) (multiple-value-bind (minutes secs) (floor hr-remainder +seconds-in-minute*) (let ((chunks nil)) (unless (zerop secs) (push (format nil "~D sec" secs) chunks)) (unless (zerop minutes) (push (format nil "~D min" minutes) chunks)) (unless (zerop hours) (push (format nil "~D hr" hours) chunks)) (unless (zerop days) (push (format nil "~D d" days) chunks)) (unless (zerop weeks) (push (format nil "~D wk" weeks) chunks)) (format t "~{~A~^, ~}~%" chunks)))))))   (seconds->duration 7259) (seconds->duration 86400) (seconds->duration 6000000)  
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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".   -- mixin classes can also be used for multiple inheritance ::class broccoli inherit food ::method eat Say "ugh, do I have to?".   ::routine dinnerTime use arg dish -- ooRexx arguments are typeless, so tests for constrained -- types must be peformed at run time. The isA method will -- check if an object is of the required type if \dish~isA(.food) then do say "I can't eat that!" return end else dish~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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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) max++ Item[max]<=f,s,q end method   method GetNext(ActualFood *Stuff) if max then copy @stuff,@Item[max], sizeof Item max-- end if end method   end class   Class Gourmand '============= physical WeightGain, SleepTime   method eats(ActualFood *stuff) WeightGain+=stuff.size*stuff.quantity*0.75 stuff.size=0 stuff.quantity=0 end method   end class   end macro     'IMPLEMENTATION '==============     Gluttony ( double,100,{ oyster,trout,bloater, chocolate,truffles, cheesecake,cream,pudding,pie })   % small 1 % medium 2 % large 3 % huge 7   % none 0 % single 1 % few 3 % several 7 % many 12   'INSTANCE '========   FoodBox Hamper Gourmand MrG   'TEST '====   Hamper.put food.pudding,large,several Hamper.put food.pie,huge,few ActualFood Course Hamper.GetNext Course MrG.eats Course   print MrG.WeightGain 'result 15.75  
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 are multiple sequences of the same length, only the first need be shown.
#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, Length/*EqualTo[max]]; seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs; Take[prime, # + {0, 1}] & /@ seqs
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 are multiple sequences of the same length, only the first need be shown.
#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 countup(n * n, N, n): composite[k] = true   let primes = collect(newSeq): for n in 2..N: if not composite[n]: n     #################################################################################################### # Longest sequences.   type Order {.pure.} = enum Ascending, Descending   proc longestSeq(order: Order): seq[int] = ## Return the longest sequence for the given order.   let ascending = order == Ascending var currseq: seq[int] prevPrime = 2 diff = if ascending: 0 else: N   for prime in primes: let nextDiff = prime - prevPrime if nextDiff != diff and nextDiff > diff == ascending: currseq.add prime else: if currseq.len > result.len: result = move(currseq) currseq = @[prevPrime, prime] diff = nextDiff prevPrime = prime   if currseq.len > result.len: result = move(currseq)     proc `$`(list: seq[int]): string = ## Return the representation of a list of primes with interleaved differences. var prevPrime: int for i, prime in list: if i != 0: result.add &" ({prime - prevPrime}) " result.addInt prime prevPrime = prime   echo "For primes < 1000000.\n" echo "First longest sequence of consecutive primes with ascending differences:" echo longestSeq(Ascending) echo() echo "First longest sequence of consecutive primes with descending differences:" echo longestSeq(Descending)
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 are multiple sequences of the same length, only the first need be shown.
#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 ) ,g>last, desc=0; if(asc++>ar, ar=asc; arAt=q ) , asc=desc=0 ); p=q; last=g ); print("Descending differences:"); showPrecPrimes(drAt, dr+2); print("\nAscending differences:"); showPrecPrimes(arAt, ar+2); } list(10^6)
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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); } }   record Napier { proc pair(n) { return (if n == 0 then 2 else n, if n == 1 then 1 else n - 1); } } record Pi { proc pair(n) { return (if n == 0 then 3 else 6, (2*n - 1)**2); } }   config const n = 200; writeln(calc(new Sqrt2(), n)); writeln(calc(new Napier(), n)); writeln(calc(new Pi(), n));
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 #(if (zero? %) 3.0 6.0) #(let [x (- (* 2.0 %) 1.0)] (* x x)) 900000))  
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#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 FI OD RETURN   PROC Main() BYTE CH=$02FC,COLOR0=$02C4   Graphics(5+16) Color=1 COLOR0=$0C   DrawCircle(10,15,100,40,24)   DO UNTIL CH#$FF OD CH=$FF RETURN
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 (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15). See also Convex Hull (youtube) http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
#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 ]   indexMinX: 0 loop.with:'i points 'p [ if p\x < get points\[indexMinX] 'x -> indexMinX: i ]   p: indexMinX q: 0   while [true][ 'result ++ points\[p]   q: (p + 1) % size points   loop 0..dec size points 'i [ if 2 = orientation points\[p] points\[i] points\[q] -> q: i ]   p: q   if p=indexMinX -> break ]   return result ]   points: @[ to :point [16 3], to :point [12 17], to :point [0 6], to :point @[neg 4 neg 6], to :point [16 6], to :point @[16 neg 7], to :point @[17 neg 4], to :point [5 19], to :point @[19 neg 8], to :point [3 16], to :point [12 13], to :point @[3 neg 4], to :point [17 5], to :point @[neg 3 15], to :point @[neg 3 neg 9], to :point [0 11], to :point @[neg 9 neg 3], to :point @[neg 4 neg 2], to :point [12 10] ]   hull: calculateConvexHull points loop hull 'i -> print 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"). Demonstrate that it passes the following three test-cases: Test Cases input number output string 7259 2 hr, 59 sec 86400 1 d 6000000 9 wk, 6 d, 10 hr, 40 min Details The following five units should be used: unit suffix used in output conversion week wk 1 week = 7 days day d 1 day = 24 hours hour hr 1 hour = 60 minutes minute min 1 minute = 60 seconds second sec However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
#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; uint days = rem / SECSPERDAY; rem %= SECSPERDAY; uint hours = rem / SECSPERHOUR; rem %= SECSPERHOUR; uint mins = rem / SECSPERMIN; rem %= SECSPERMIN;   string formatted = "";   (weeks != 0) ? formatted ~= (weeks.to!string ~ " wk, ") : formatted; (days != 0) ? formatted ~= (days.to!string ~ " d, ") : formatted; (hours != 0) ? formatted ~= (hours.to!string ~ " hr, ") : formatted; (mins != 0) ? formatted ~= (mins.to!string ~ " min, ") : formatted; (rem != 0) ? formatted ~= (rem.to!string ~ " sec") : formatted;   if (formatted.endsWith(", ")) return formatted[0..$-2];   return formatted; }   void main() { 7_259.ConvertSeconds.writeln; 86_400.ConvertSeconds.writeln; 6_000_000.ConvertSeconds.writeln; }  
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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(food,"eat") if t!=SF_PROC+SF_PUBLIC then throw("not edible") -- no public method eat... end if -- you might also want something like this: -- t = structs:fetch_field(food,"eat") -- if t=NULL then -- throw("eat not implemented") -- end if this.contents = append(this.contents,food) end procedure procedure dine() integer l = length(this.contents) string s = iff(l=1?"":"s") printf(1,"foodbox contains %d item%s\n",{l,s}) for i=1 to l do class food = this.contents[i]; --food.eat(); -- error... -- If you don't define an [abstract] eat() method, or use -- "class", you end up having to do something like this: integer eat = structs:fetch_field(food,"eat") eat(food) end for end procedure end class foodbox lunchbox = new()   class fruit string name procedure eat() printf(1,"mmm... %s\n",{this.name}) end procedure end class fruit banana = new({"banana"})   class clay string name = "fletton" end class clay brick = new()   lunchbox.add(banana) try lunchbox.add(brick) -- throws exception catch e printf(1,"%s line %d error: %s\n",{e[E_FILE],e[E_LINE],e[E_USER]}) end try lunchbox.dine()
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 '(+FoodBox)) Eat (new '(+Eatable)) NoEat (new '(+Bla))) (set> Box Eat) # Works (set> Box NoEat) ) # Gives an error
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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?)] [remove-at (->m exact-nonnegative-integer? containee/c)] [count (->m exact-nonnegative-integer?)]))   (define ((generic-box-mixin containee/c) %) (->i ([containee/c contract?]) (rv (containee/c) (implementation?/c (generic-container<%> containee/c)))) (class* % ((generic-container<%> containee/c)) (super-new) (define l empty) (define/public (contents) l) (define/public (insert o) (set! l (cons o l))) (define/public (remove-at i) (begin0 (list-ref l i) (append (take l i) (drop l (add1 i))))) (define/public (count) (length l))))   ;; As I understand it, a "Food Box" from the task is still a generic... i.e. ;; you will specify it down ;; to an "apple-box%" so: food-box%-generic is still ;; generic. food-box% will take any kind of food. (define/contract (food-box-mixin T%) (-> (or/c (λ (i) (eq? edible<%> i)) (implementation?/c edible<%>)) (make-mixin-contract)) (generic-box-mixin (and/c (is-a?/c edible<%>) (is-a?/c T%))))   (module+ test   (define integer-box% ((generic-box-mixin integer?) object%)) (define integer-box (new integer-box%))   (define apple% (class* object% (edible<%>) (super-new) (define/public (eat) (displayln "nom!"))))   (define banana% (class* object% (edible<%>) (super-new) (define/public (eat) (displayln "peel.. peel... nom... nom!"))))   (define semolina% (class* object% () ; <-- empty interfaces clause (super-new)  ;; you can call eat on it... but it's not explicitly (or even vaguely)  ;; edible<%> (define/public (eat) (displayln "blech!"))))    ;; this will take any object that is edible<%> and edible<%> (therefore all  ;; edible<%> objects) (define any-food-box (new ((food-box-mixin edible<%>) object%)))    ;; this will take any object that is edible and an apple<%>  ;; (therefore only apple<%>s) (define apple-food-box (new ((food-box-mixin apple%) object%)))   (test  ;; Test generic boxes (send integer-box insert 22) (send integer-box insert "a string") =error> exn:fail:contract?    ;; Test the food box that takes any edible<%> (send any-food-box insert (new apple%)) (send any-food-box insert (new banana%)) (send any-food-box insert (new semolina%)) =error> exn:fail:contract?    ;; Test the food box that takes any apple% (send apple-food-box insert (new apple%)) (send apple-food-box insert (new banana%)) =error> exn:fail:contract? (send apple-food-box insert (new semolina%)) =error> exn:fail:contract? (send apple-food-box count) => 1    ;; Show that you cannot make a food-box from the non-edible<%> semolina cannot (implementation? semolina% edible<%>) => #f (new ((food-box-mixin semolina%) object%)) =error> exn:fail:contract?))
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 generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.
#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 are multiple sequences of the same length, only the first need be shown.
#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 '>') { if ($next > $diff) { ++$run } else { $run = 1 } } else { if ($next < $diff) { ++$run } else { $run = 1 } } $diff = $next; $run } 1 .. $#primes;   my @prime_run; my $max = max @diff; for my $r ( indexes { $_ == $max } @diff ) { push @prime_run, join ' ', map { $primes[$r - $_] } reverse 0..$max } @prime_run }   say "Longest run(s) of ascending prime gaps up to $limit:\n" . join "\n", runs('>'); say "\nLongest run(s) of descending prime gaps up to $limit:\n" . join "\n", runs('<');
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 such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a 0 = 1 {\displaystyle a_{0}=1} then a N = 2 {\displaystyle a_{N}=2} . b N {\displaystyle b_{N}} is always 1 {\displaystyle 1} . 2 = 1 + 1 2 + 1 2 + 1 2 + ⋱ {\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}} For Napier's Constant, use a 0 = 2 {\displaystyle a_{0}=2} , then a N = N {\displaystyle a_{N}=N} . b 1 = 1 {\displaystyle b_{1}=1} then b N = N − 1 {\displaystyle b_{N}=N-1} . e = 2 + 1 1 + 1 2 + 2 3 + 3 4 + ⋱ {\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}} For Pi, use a 0 = 3 {\displaystyle a_{0}=3} then a N = 6 {\displaystyle a_{N}=6} . b N = ( 2 N − 1 ) 2 {\displaystyle b_{N}=(2N-1)^{2}} . π = 3 + 1 6 + 9 6 + 25 6 + ⋱ {\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}} See also   Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
#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 approximately  : " continued-fractions("sqrt-2-alpha", "sqrt-2-beta", 100) display "Napier constant approximately : " continued-fractions("napier-alpha", "napier-beta", 40) display "Pi approximately  : " continued-fractions("pi-alpha", "pi-beta", 10000)   goback. end program show-continued-fractions.   *> ************************************************************** identification division. function-id. continued-fractions.   data division. working-storage section. 01 alpha-function usage program-pointer. 01 beta-function usage program-pointer. 01 alpha usage float-long. 01 beta usage float-long. 01 running usage float-long. 01 i usage binary-long.   linkage section. 01 alpha-name pic x any length. 01 beta-name pic x any length. 01 iterations pic 9 any length. 01 approximation usage float-long.   procedure division using alpha-name beta-name iterations returning approximation.   set alpha-function to entry alpha-name if alpha-function = null then display "error: no " alpha-name " function" upon syserr goback end-if set beta-function to entry beta-name if beta-function = null then display "error: no " beta-name " function" upon syserr goback end-if   move 0 to alpha beta running perform varying i from iterations by -1 until i = 0 call alpha-function using i returning alpha call beta-function using i returning beta compute running = beta / (alpha + running) end-perform call alpha-function using 0 returning alpha compute approximation = alpha + running   goback. end function continued-fractions.   *> ****************************** identification division. program-id. sqrt-2-alpha.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. if iteration equal 0 then move 1.0 to result else move 2.0 to result end-if   goback. end program sqrt-2-alpha.   *> ****************************** identification division. program-id. sqrt-2-beta.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. move 1.0 to result   goback. end program sqrt-2-beta.   *> ****************************** identification division. program-id. napier-alpha.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. if iteration equal 0 then move 2.0 to result else move iteration to result end-if   goback. end program napier-alpha.   *> ****************************** identification division. program-id. napier-beta.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. if iteration = 1 then move 1.0 to result else compute result = iteration - 1.0 end-if   goback. end program napier-beta.   *> ****************************** identification division. program-id. pi-alpha.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. if iteration equal 0 then move 3.0 to result else move 6.0 to result end-if   goback. end program pi-alpha.   *> ****************************** identification division. program-id. pi-beta.   data division. working-storage section. 01 result usage float-long.   linkage section. 01 iteration usage binary-long unsigned.   procedure division using iteration returning result. compute result = (2 * iteration - 1) ** 2   goback. end program pi-beta.