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/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Julia | Julia | # It'st most appropriate to define a Julia iterable object for this task
# Julia doesn't have Python'st yield, the closest to it is produce/consume calls with Julia tasks
# but for various reasons they don't work out for this task
# This solution works with two integers, a Julia rational or a real
mutable struct ContinuedFraction{T<:Integer}
n1::T # numerator or real
n2::T # denominator or 1 if real
t1::T # generated coefficient
end
# Constructors for all possible input types
ContinuedFraction{T<:Integer}(n1::T, n2::T) = ContinuedFraction(n1, n2, 0)
ContinuedFraction(n::Rational) = ContinuedFraction(numerator(n), denominator(n))
ContinuedFraction(n::AbstractFloat) = ContinuedFraction(Rational(n))
# Methods to make our object iterable
Base.start(::ContinuedFraction) = nothing
# Returns true if we've prepared the continued fraction
Base.done(cf::ContinuedFraction, st) = cf.n2 == 0
# Generates the next coefficient
function Base.next(cf::ContinuedFraction, st)
cf.n1, (cf.t1, cf.n2) = cf.n2, divrem(cf.n1, cf.n2)
return cf.t1, nothing
end
# Tell Julia that this object always returns ints (all coeffs are integers)
Base.eltype{T}(::Type{ContinuedFraction{T}}) = T
# Overload the default collect function so that we can collect the first maxiter coeffs of infinite continued fractions
# array slicing doesn't work as Julia crashes before the slicing due to our infinitely long array
function Base.collect(itr::ContinuedFraction, maxiter::Integer = 100)
r = Array{eltype(itr)}(maxiter)
i = 1
for v in itr
r[i] = v
i += 1
if i > maxiter break end
end
return r[1:i-1]
end
# Test cases according to task description with outputs in comments
println(collect(ContinuedFraction(1, 2))) # => [0, 2]
println(collect(ContinuedFraction(3, 1))) # => [3]
println(collect(ContinuedFraction(23, 8))) # => [2, 1, 7]
println(collect(ContinuedFraction(13, 11))) # => [1, 5, 2]
println(collect(ContinuedFraction(22, 7))) # => [3, 7]
println(collect(ContinuedFraction(14142, 10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]
println(collect(ContinuedFraction(141421, 100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]
println(collect(ContinuedFraction(1414214, 1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]
println(collect(ContinuedFraction(14142136, 10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]
println(collect(ContinuedFraction(13 // 11))) # => [1, 5, 2]
println(collect(ContinuedFraction(√2), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Kotlin | Kotlin | // version 1.1.2
// compile with -Xcoroutines=enable flag from command line
import kotlin.coroutines.experimental.buildSequence
fun r2cf(frac: Pair<Int, Int>) =
buildSequence {
var num = frac.first
var den = frac.second
while (Math.abs(den) != 0) {
val div = num / den
val rem = num % den
num = den
den = rem
yield(div)
}
}
fun iterate(seq: Sequence<Int>) {
for (i in seq) print("$i ")
println()
}
fun main(args: Array<String>) {
val fracs = arrayOf(1 to 2, 3 to 1, 23 to 8, 13 to 11, 22 to 7, -151 to 77)
for (frac in fracs) {
print("${"%4d".format(frac.first)} / ${"%-2d".format(frac.second)} = ")
iterate(r2cf(frac))
}
val root2 = arrayOf(14142 to 10000, 141421 to 100000,
1414214 to 1000000, 14142136 to 10000000)
println("\nSqrt(2) ->")
for (frac in root2) {
print("${"%8d".format(frac.first)} / ${"%-8d".format(frac.second)} = ")
iterate(r2cf(frac))
}
val pi = arrayOf(31 to 10, 314 to 100, 3142 to 1000, 31428 to 10000,
314285 to 100000, 3142857 to 1000000,
31428571 to 10000000, 314285714 to 100000000)
println("\nPi ->")
for (frac in pi) {
print("${"%9d".format(frac.first)} / ${"%-9d".format(frac.second)} = ")
iterate(r2cf(frac))
}
} |
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
| #Groovy | Groovy | Number.metaClass.mixin RationalCategory
[
0.9054054, 0.518518, 0.75, Math.E, -0.423310825, Math.PI, 0.111111111111111111111111
].each{
printf "%30.27f %s\n", it, it as Rational
} |
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
| #Haskell | Haskell | Prelude> map (\d -> Ratio.approxRational d 0.0001) [0.9054054, 0.518518, 0.75]
[67 % 74,14 % 27,3 % 4]
Prelude> [0.9054054, 0.518518, 0.75] :: [Rational]
[4527027 % 5000000,259259 % 500000,3 % 4]
Prelude> map (fst . head . Numeric.readFloat) ["0.9054054", "0.518518", "0.75"] :: [Rational]
[4527027 % 5000000,259259 % 500000,3 % 4] |
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
| #Action.21 | Action! | PROC Main()
CHAR ARRAY str1,str2,str3(10)
str1="Atari"
str2=str1
SCopy(str3,str1)
PrintF(" base=%S%E",str1)
PrintF("alias=%S%E",str2)
PrintF(" copy=%S%E",str3)
PutE()
SCopy(str1,"Action!")
PrintF(" base=%S%E",str1)
PrintF("alias=%S%E",str2)
PrintF(" copy=%S%E",str3)
RETURN |
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
| #ActionScript | ActionScript | var str1:String = "Hello";
var str2:String = str1; |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ContinuedFraction[1/2]
ContinuedFraction[3]
ContinuedFraction[23/8]
ContinuedFraction[13/11]
ContinuedFraction[22/7]
ContinuedFraction[-151/77]
ContinuedFraction[14142/10000]
ContinuedFraction[141421/100000]
ContinuedFraction[1414214/1000000]
ContinuedFraction[14142136/10000000] |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Modula-2 | Modula-2 | MODULE ConstructFromrationalNumber;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE R2cf = RECORD
num,den : INTEGER;
END;
PROCEDURE HasNext(self : R2cf) : BOOLEAN;
BEGIN
RETURN self.den # 0;
END HasNext;
PROCEDURE Next(VAR self : R2cf) : INTEGER;
VAR div,rem : INTEGER;
BEGIN
div := self.num / self.den;
rem := self.num REM self.den;
self.num := self.den;
self.den := rem;
RETURN div;
END Next;
PROCEDURE Iterate(self : R2cf);
VAR buf : ARRAY[0..64] OF CHAR;
BEGIN
WHILE HasNext(self) DO
FormatString("%i ", buf, Next(self));
WriteString(buf);
END;
WriteLn;
END Iterate;
PROCEDURE Print(num,den : INTEGER);
VAR frac : R2cf;
VAR buf : ARRAY[0..64] OF CHAR;
BEGIN
FormatString("%9i / %-9i = ", buf, num, den);
WriteString(buf);
frac.num := num;
frac.den := den;
Iterate(frac);
END Print;
VAR frac : R2cf;
BEGIN
Print(1,2);
Print(3,1);
Print(23,8);
Print(13,11);
Print(22,7);
Print(-151,77);
WriteLn;
WriteString("Sqrt(2) ->");
WriteLn;
Print(14142,10000);
Print(141421,100000);
Print(1414214,1000000);
Print(14142136,10000000);
WriteLn;
WriteString("Pi ->");
WriteLn;
Print(31,10);
Print(314,100);
Print(3142,1000);
Print(31428,10000);
Print(314285,100000);
Print(3142857,1000000);
Print(31428571,10000000);
Print(314285714,100000000);
ReadChar;
END ConstructFromrationalNumber. |
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
| #J | J | x: 0.9054054 0.518518 0.75 NB. find "exact" rational representation
127424481939351r140737488355328 866492568306r1671094481399 3r4 |
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
| #Java | Java | import org.apache.commons.math3.fraction.BigFraction;
public class Test {
public static void main(String[] args) {
double[] n = {0.750000000, 0.518518000, 0.905405400, 0.142857143,
3.141592654, 2.718281828, -0.423310825, 31.415926536};
for (double d : n)
System.out.printf("%-12s : %s%n", d, new BigFraction(d, 0.00000002D, 10000));
}
} |
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
| #Ada | Ada | Src : String := "Hello";
Dest : String := 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
| #Aime | Aime | text s, t;
t = "Rosetta";
s = t; |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Nim | Nim | iterator r2cf*(n1, n2: int): int =
var (n1, n2) = (n1, n2)
while n2 != 0:
yield n1 div n2
n1 = n1 mod n2
swap n1, n2
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
from sequtils import toSeq
for pair in [(1, 2), (3, 1), (23, 8), (13, 11), (22, 7), (-151, 77)]:
echo pair, " -> ", toSeq(r2cf(pair[0], pair[1]))
echo ""
for pair in [(14142, 10000), (141421, 100000), (1414214, 1000000), (14142136, 10000000)]:
echo pair, " -> ", toSeq(r2cf(pair[0], pair[1]))
echo ""
for pair in [(31,10), (314,100), (3142,1000), (31428,10000), (314285,100000),
(3142857,1000000), (31428571,10000000), (314285714,100000000)]:
echo pair, " -> ", toSeq(r2cf(pair[0], pair[1])) |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #PARI.2FGP | PARI/GP | apply(contfrac,[1/2,3,23/8,13/11,22/7,-151/77]) |
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
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () =>
showJSON(
map( // Using a tolerance epsilon of 1/10000
n => showRatio(approxRatio(0.0001)(n)),
[0.9054054, 0.518518, 0.75]
)
);
// Epsilon -> Real -> Ratio
// approxRatio :: Real -> Real -> Ratio
const approxRatio = eps => n => {
const
gcde = (e, x, y) => {
const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));
return _gcd(Math.abs(x), Math.abs(y));
},
c = gcde(Boolean(eps) ? eps : (1 / 10000), 1, n);
return Ratio(
Math.floor(n / c), // numerator
Math.floor(1 / c) // denominator
);
};
// GENERIC FUNCTIONS ----------------------------------
// Ratio :: Int -> Int -> Ratio
const Ratio = (n, d) => ({
type: 'Ratio',
'n': n, // numerator
'd': d // denominator
});
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// showJSON :: a -> String
const showJSON = x => JSON.stringify(x, null, 2);
// showRatio :: Ratio -> String
const showRatio = nd =>
nd.n.toString() + '/' + nd.d.toString();
// MAIN ---
return main();
})(); |
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
| #ALGOL_68 | ALGOL 68 | (
STRING src:="Hello", dest;
dest:=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
| #ALGOL_W | ALGOL W | begin
% strings are (fixed length) values in algol W. Assignment makes a copy %
string(10) a, copyOfA;
a := "some text";
copyOfA := a;
% assignment to a will not change copyOfA %
a := "new value";
write( a, copyOfA )
end. |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Perl | Perl | $|=1;
sub rc2f {
my($num, $den) = @_;
return sub { return unless $den;
my $q = int($num/$den);
($num, $den) = ($den, $num - $q*$den);
$q; };
}
sub rcshow {
my $sub = shift;
print "[";
my $n = $sub->();
print "$n" if defined $n;
print "; $n" while defined($n = $sub->());
print "]\n";
}
rcshow(rc2f(@$_))
for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]);
print "\n";
rcshow(rc2f(@$_))
for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]);
print "\n";
rcshow(rc2f(314285714,100000000)); |
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
| #jq | jq | # include "rational"; # a reminder that r/2 and power/1 are required
# Input: any JSON number, not only a decimal
# Output: a rational, constructed using r/2
# Requires power/1 (to take advantage of gojq's support for integer arithmetic)
# and r/2 (for rational number constructor)
def number_to_r:
# input: a decimal string
# $in - either null or the original input
# $e - the integer exponent of the original number, or 0
def dtor($in; $e):
index(".") as $ix
| if $in and ($ix == null) then $in
else (if $ix then sub("[.]"; "") else . end | tonumber) as $n
| (if $ix then ((length - ($ix+1)) - $e) else - $e end) as $p
| if $p >= 0
then r( $n; 10|power($p))
else r( $n * (10|power(-$p)); 1)
end
end;
. as $in
| tostring
| if (test("[Ee]")|not) then dtor($in; 0)
else capture("^(?<s>[^eE]*)[Ee](?<e>.*$)")
| (.e | if length > 0 then tonumber else 0 end) as $e
| .s | dtor(null; $e)
end ; |
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
| #Julia | Julia | rationalize(0.9054054)
rationalize(0.518518)
rationalize(0.75) |
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
| #Apex | Apex | String original = 'Test';
String cloned = original;
//"original == cloned" is true
cloned += ' more';
//"original == cloned" is 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
| #AppleScript | AppleScript | set src to "Hello"
set dst to src |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Phix | Phix | with javascript_semantics
function r2cf(atom num, denom)
atom quot = 0
if denom!=0 then
quot = trunc(num/denom)
{num,denom} = {denom,num-quot*denom}
end if
return {quot,{num,denom}}
end function
procedure test(string txt, sequence tests)
printf(1,"Running %s :\n",{txt})
for i=1 to length(tests) do
atom {num,denom} = tests[i], quot
string sep = ";"
printf(1,"%d/%d ==> [",{num,denom})
while denom!=0 do
{quot,{num,denom}} = r2cf(num,denom)
printf(1,"%d",quot)
if denom=0 then exit end if
printf(1,"%s",sep)
sep = ","
end while
printf(1,"]\n")
end for
printf(1,"\n")
end procedure
constant examples = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}},
sqrt2 = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}},
pi = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000},
{31428571,10000000}, {314285714,100000000}, {3141592653589793,1000000000000000}}
test("the examples",examples)
test("for sqrt(2)",sqrt2)
test("for pi",pi)
|
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
| #Kotlin | Kotlin | // version 1.1.2
class Rational(val num: Long, val den: Long) {
override fun toString() = "$num/$den"
}
fun decimalToRational(d: Double): Rational {
val ds = d.toString().trimEnd('0').trimEnd('.')
val index = ds.indexOf('.')
if (index == -1) return Rational(ds.toLong(), 1L)
var num = ds.replace(".", "").toLong()
var den = 1L
for (n in 1..(ds.length - index - 1)) den *= 10L
while (num % 2L == 0L && den % 2L == 0L) {
num /= 2L
den /= 2L
}
while (num % 5L == 0L && den % 5L == 0L) {
num /= 5L
den /= 5L
}
return Rational(num, den)
}
fun main(args: Array<String>) {
val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6)
for (decimal in decimals)
println("${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}")
} |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program copystr.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
/* UnInitialized data */
.bss
.align 4
iPtString: .skip 4
szString1: .skip 80
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
@ display start string
ldr r0,iAdrszString
bl affichageMess
@ copy pointer string
ldr r0,iAdrszString
ldr r1,iAdriPtString
str r0,[r1]
@ control
ldr r1,iAdriPtString
ldr r0,[r1]
bl affichageMess
@ copy string
ldr r0,iAdrszString
ldr r1,iAdrszString1
1:
ldrb r2,[r0],#1 @ read one byte and increment pointer one byte
strb r2,[r1],#1 @ store one byte and increment pointer one byte
cmp r2,#0 @ end of string ?
bne 1b @ no -> loop
@ control
ldr r0,iAdrszString1
bl affichageMess
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszString: .int szString
iAdriPtString: .int iPtString
iAdrszString1: .int szString1
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
|
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Python | Python | def r2cf(n1,n2):
while n2:
n1, (t1, n2) = n2, divmod(n1, n2)
yield t1
print(list(r2cf(1,2))) # => [0, 2]
print(list(r2cf(3,1))) # => [3]
print(list(r2cf(23,8))) # => [2, 1, 7]
print(list(r2cf(13,11))) # => [1, 5, 2]
print(list(r2cf(22,7))) # => [3, 7]
print(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]
print(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]
print(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]
print(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2] |
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
| #Liberty_BASIC | Liberty BASIC |
' Uses convention that one repeating sequence implies infinitely repeating sequence..
' Non-recurring fractions are limited to nd number of digits in nuerator & denominator
nd =3 ' suggest 3. 4 is slow. >4 is .......
do
read x$
data "0.5", "0.1", "0.333", "1 /3", "0.33", "0.14159265", "2^-0.5", "0.1 +0.9*rnd(1)"
data "0.142857142857", "int( 1000*rnd(1))/int( 1000*rnd(1))","end" ' always between 0 and 0.999999...
if x$ ="end" then exit do
print x$; " is ";
type$ =check$( x$)
print type$;
if type$ ="recurring" then
x =val( mid$( x$, 3, ( len( x$) -2) /2))
rep =( len( x$) -2) /2
num =x
den =10^rep -1
gcd =gcd( num, den)
print
print " Calculating exact fraction for ", recurring$( x); " recurring & found";
print num /gcd; " /"; den /gcd
print
else ' non-recurring. Check numerators & denominators <1000
x =eval( x$)
print
print " Looking for fractions that are close to "; using( "#.############", x); " & found ";
eps =10^nd
for n = 1 to nd
for i =1 to 10^n -1
for j =i to 10^n -1
fr =i /j
if abs( x -fr) <eps then
eps =abs( x -fr)
'print i; " /"; j; " = ", using( "##.############", fr), "with error +/-"; using( "###.#########", eps /x *100); " %"
ii =i: jj =j
if eps =0 then exit for
end if
next j
scan
if eps =0 then exit for
next i
if eps =0 then exit for
next n
print ii; " /"; jj
print
end if
loop until 0
print
print "END."
end
function recurring$( x)
recurring$ ="0."
do
recurring$ =recurring$ +str$( x)
loop until len( recurring$) >=14
end function
function gcd( a, b) ' thanks Uncle Ben..
while b <>0
t =b
b =a mod b
a =t
wend
gcd =a
end function
function check$( i$)
check$ ="non-recurring"
length =len( i$) -2 ' allow for the '0.'.
if length /2 =int( length /2) then if mid$( i$, 3, length /2) =mid$( i$, 3 +length /2, length /2) then check$ ="recurring"
end function
|
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
| #Arturo | Arturo | a: new "Hello"
b: a ; reference the same string
; changing one string in-place
; will change both strings
'b ++ "World"
print b
print a
c: "Hello"
d: new c ; make a copy of the older string
; changing one string in-place
; will change only the string in question
'd ++ "World"
print d
print c |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
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
| #Asymptote | Asymptote | string src, dst;
src = "Hello";
dst = src;
src = " world...";
write(dst, src); |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Quackery | Quackery |
[ $ "bigrat.qky" loadfile ] now!
[ [] unrot
[ proper
2swap join unrot
over 0 != while
1/v again ]
2drop ] is cf ( n/d --> [ )
' [ [ 1 2 ]
[ 3 1 ]
[ 23 8 ]
[ 13 11 ]
[ 22 7 ]
[ -151 77 ]
[ 14142 10000 ]
[ 141421 100000 ]
[ 1414214 1000000 ]
[ 14142136 10000000 ]
[ 31 10 ]
[ 314 100 ]
[ 3142 1000 ]
[ 31428 10000 ]
[ 314285 100000 ]
[ 3142857 1000000 ]
[ 31428571 10000000 ]
[ 314285714 100000000 ] ]
witheach
[ do over echo say "/"
dup echo
say " = "
cf echo cr ] |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Racket | Racket |
#lang racket
(define ((r2cf n d))
(or (zero? d)
(let-values ([(q r) (quotient/remainder n d)])
(set! n d)
(set! d r)
q)))
(define (r->cf n d)
(for/list ([i (in-producer (r2cf n d) #t)]) i))
(define (real->cf x places)
(define d (expt 10 places))
(define n (exact-floor (* x d)))
(r->cf n d))
(map r->cf
'(1 3 23 13 22 -151)
'(2 1 8 11 7 77))
(real->cf (sqrt 2) 10)
(real->cf pi 10)
|
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
| #Lua | Lua | for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do
local n, d, dmax, eps = 1, 1, 1e7, 1e-15
while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end
print(string.format("%15.13f --> %d / %d", v, n, d))
end |
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
| #AutoHotkey | AutoHotkey | 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
| #AutoIt | AutoIt | $Src= "Hello"
$dest = $Src |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Raku | Raku | sub r2cf(Rat $x is copy) {
gather loop {
$x -= take $x.floor;
last unless $x > 0;
$x = 1 / $x;
}
}
say r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>; |
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
| #Maple | Maple |
> map( convert, [ 0.9054054, 0.518518, 0.75 ], 'rational', 'exact' );
4527027 259259
[-------, ------, 3/4]
5000000 500000
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Map[Rationalize[#,0]&,{0.9054054,0.518518, 0.75} ]
-> {4527027/5000000,259259/500000,3/4} |
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
| #AWK | AWK | BEGIN {
a = "a string"
b = a
sub(/a/, "X", a) # modify a
print b # b is a copy, not a reference to...
} |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #REXX | REXX | /*REXX program converts a decimal or rational fraction to a continued fraction. */
numeric digits 230 /*determines how many terms to be gened*/
say ' 1/2 ──► CF: ' r2cf( '1/2' )
say ' 3 ──► CF: ' r2cf( 3 )
say ' 23/8 ──► CF: ' r2cf( '23/8' )
say ' 13/11 ──► CF: ' r2cf( '13/11' )
say ' 22/7 ──► CF: ' r2cf( '22/7 ' )
say ' ___'
say '───────── attempts at √ 2.'
say '14142/1e4 ──► CF: ' r2cf( '14142/1e4 ' )
say '141421/1e5 ──► CF: ' r2cf( '141421/1e5 ' )
say '1414214/1e6 ──► CF: ' r2cf( '1414214/1e6 ' )
say '14142136/1e7 ──► CF: ' r2cf( '14142136/1e7 ' )
say '141421356/1e8 ──► CF: ' r2cf( '141421356/1e8 ' )
say '1414213562/1e9 ──► CF: ' r2cf( '1414213562/1e9 ' )
say '14142135624/1e10 ──► CF: ' r2cf( '14142135624/1e10 ' )
say '141421356237/1e11 ──► CF: ' r2cf( '141421356237/1e11 ' )
say '1414213562373/1e12 ──► CF: ' r2cf( '1414213562373/1e12 ' )
say '√2 ──► CF: ' r2cf( sqrt(2) )
say
say '───────── an attempt at pi'
say 'pi ──► CF: ' r2cf( pi() )
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
$maxFact: procedure; parse arg x 1 _x,y; y=10**(digits()-1); b=0; h=1; a=1; g=0
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; return b'/'h
/*──────────────────────────────────────────────────────────────────────────────────────*/
pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862,
|| 089986280348253421170679821480865132823066470938446095505822317253594081284,
|| 811174502841027019385211055596446229489549303819644288109756659334461284756,
|| 48233786783165271 /* ··· should ≥ NUMERIC DIGITS */
/*──────────────────────────────────────────────────────────────────────────────────────*/
r2cf: procedure; parse arg g 1 s 2; $=; if s=='-' then g=substr(g, 2)
else s=
if pos(., g)\==0 then do; if \datatype(g, 'N') then call serr 'not numeric:' g
g=$maxfact(g)
end
if pos('/', g)==0 then g=g"/"1
parse var g n '/' d
if \datatype(n, 'W') then call serr "a numerator isn't an integer:" n
if \datatype(d, 'W') then call serr "a denominator isn't an integer:" d
if d=0 then call serr 'a denominator is zero'
n=abs(n) /*ensure numerator is positive. */
do while d\==0; _=d /*where the rubber meets the road*/
$=$ s || (n%d) /*append another number to list. */
d=n // d; n=_ /* % is int div, // is modulus.*/
end /*while*/
return strip($)
/*──────────────────────────────────────────────────────────────────────────────────────*/
serr: say; say '***error***'; say; say arg(1); say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric form
m.=9; numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1 |
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).
| #11l | 11l | F duration(=sec)
[Int] t
L(dm) [60, 60, 24, 7]
Int m
(sec, m) = (sec I/ dm, sec % dm)
t.insert(0, m)
t.insert(0, sec)
R zip(t, [‘wk’, ‘d’, ‘hr’, ‘min’, ‘sec’]).filter(num_unit -> num_unit[0] > 0).map(num_unit -> num_unit[0]‘ ’num_unit[1]).join(‘, ’)
print(duration(7259))
print(duration(86400))
print(duration(6000000)) |
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
| #MATLAB_.2F_Octave | MATLAB / Octave |
[a,b]=rat(.75)
[a,b]=rat(.518518)
[a,b]=rat(.9054054)
|
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 П1 ИП1 {x} x#0 14 КИП4 ИП1 1 0
* П1 БП 02 ИП4 10^x П0 ПA ИП1 ПB
ИПA ИПB / П9 КИП9 ИПA ИПB ПA ИП9 *
- ПB x=0 20 ИПA ИП0 ИПA / П0 ИП1
ИПA / П1 ИП0 ИП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
| #Axe | Axe | Lbl STRCPY
r₁→S
While {r₂}
{r₂}→{r₁}
r₁++
r₂++
End
0→{r₁}
S
Return |
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
| #Babel | Babel | babel> "Hello, world\n" dup cp dup 0 "Y" 0 1 move8
babel> << <<
Yello, world
Hello, world
|
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Ruby | Ruby | # Generate a continued fraction from a rational number
def r2cf(n1,n2)
while n2 > 0
n1, (t1, n2) = n2, n1.divmod(n2)
yield t1
end
end |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Rust | Rust |
struct R2cf {
n1: i64,
n2: i64
}
// This iterator generates the continued fraction representation from the
// specified rational number.
impl Iterator for R2cf {
type Item = i64;
fn next(&mut self) -> Option<i64> {
if self.n2 == 0 {
None
}
else {
let t1 = self.n1 / self.n2;
let t2 = self.n2;
self.n2 = self.n1 - t1 * t2;
self.n1 = t2;
Some(t1)
}
}
}
fn r2cf(n1: i64, n2: i64) -> R2cf {
R2cf { n1: n1, n2: n2 }
}
macro_rules! printcf {
($x:expr, $y:expr) => (println!("{:?}", r2cf($x, $y).collect::<Vec<_>>()));
}
fn main() {
printcf!(1, 2);
printcf!(3, 1);
printcf!(23, 8);
printcf!(13, 11);
printcf!(22, 7);
printcf!(-152, 77);
printcf!(14_142, 10_000);
printcf!(141_421, 100_000);
printcf!(1_414_214, 1_000_000);
printcf!(14_142_136, 10_000_000);
printcf!(31, 10);
printcf!(314, 100);
printcf!(3142, 1000);
printcf!(31_428, 10_000);
printcf!(314_285, 100_000);
printcf!(3_142_857, 1_000_000);
printcf!(31_428_571, 10_000_000);
printcf!(314_285_714, 100_000_000);
}
|
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).
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
TYPE Time=[BYTE s,m,h,d,w]
CARD ARRAY units(5)
PROC Convert(REAL POINTER seconds Time POINTER t)
BYTE ARRAY b,duration=[60 60 24 7]
BYTE i
REAL r,n
b=t
FOR i=0 TO 3
DO
IntToReal(duration(i),n)
RealMod(seconds,n,r)
b(i)=RealToInt(r)
RealDivInt(seconds,n,r)
RealAssign(r,seconds)
OD
b(4)=RealToInt(seconds)
RETURN
PROC PrintTime(Time POINTER t)
INT i
BYTE first,n
BYTE ARRAY b
b=t i=4 first=1
WHILE i>=0
DO
n=b(i)
IF n>0 THEN
IF first=0 THEN
Print(", ")
ELSE
first=0
FI
PrintF("%B %S",n,units(i))
FI
i==-1
OD
RETURN
PROC Test(CHAR ARRAY s)
REAL seconds
Time t
ValR(s,seconds)
PrintR(seconds) Print(" -> ")
Convert(seconds,t)
PrintTime(t) PutE()
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
MathInit()
units(0)="sec" units(1)="min"
units(2)="hr" units(3)="d"
units(4)="wk"
Test("7259")
Test("86400")
Test("6000000")
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).
| #Ada | Ada | with Ada.Text_IO;
procedure Convert is
type Time is range 0 .. 10_000*356*20*60*60; -- at most 10_000 years
subtype Valid_Duration is Time range 1 .. 10_000*356*20*60*60;
type Units is (WK, D, HR, MIN, SEC);
package IO renames Ada.Text_IO;
Divide_By: constant array(Units) of Time := (1_000*53, 7, 24, 60, 60);
Split: array(Units) of Time;
No_Comma: Units;
X: Time;
Test_Cases: array(Positive range <>) of Valid_Duration :=
(6, 60, 3659, 7_259, 86_400, 6_000_000, 6_001_200, 6_001_230, 600_000_000);
begin
for Test_Case of Test_Cases loop
IO.Put(Time'Image(Test_Case) & " SECONDS =");
X := Test_Case;
-- split X up into weeks, days, ..., seconds
No_Comma := Units'First;
for Unit in reverse Units loop -- Unit = SEC, ..., WK (in that order)
Split(Unit) := X mod Divide_By(Unit);
X := X / Divide_By(Unit);
if Unit > No_Comma and Split(Unit)>0 then
No_Comma := Unit;
end if;
end loop;
-- ouput weeks, days, ..., seconds
for Unit in Units loop -- Unit = WK, .., SEC (in that order)
if Split(Unit) > 0 then
IO.Put(Time'Image(Split(Unit)) & " " & Units'Image(Unit) &
(if No_Comma > Unit then "," else ""));
end if;
end loop;
IO.New_Line;
end loop;
end Convert; |
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
| #NetRexx | NetRexx |
/*NetRexx program to convert decimal numbers to fractions *************
* 16.08.2012 Walter Pachl derived from Rexx Version 2
**********************************************************************/
options replace format comments java crossref savelog symbols
Numeric Digits 10 /* use "only" 10 digs of precision */
ratt('0.9054054054','67/74')
ratt('0.5185185185','14/27')
ratt('0.75' ,'3/4')
ratt('0.905405400',' 693627417/766095958')
ratt('0.9054054054','67/74')
ratt('0.1428571428','1/7')
ratt('35.000','35')
ratt('35.001','35001/1000')
ratt('0.00000000001','?')
ratt('0.000001000001','1/999999')
ratt(0.9054054054,'1/3')
method ratt(d = Rexx,fs = Rexx) public static
fract=rat(d)
Say ' 'd '->' fract
Parse fract no '/' de
If de='' Then x=no
Else x=no/de
If x<>d Then
Say '> '||x 'is different'
method rat(in, high='') public static
/**********************************************************************
* rat(number<,high) returns a fraction or an integer that is equal to
* or approximately equal to number.
* Nominator and denominator must not have more than high digits
* 16.08.2012 Walter Pachl derived from Rexx Version 2
**********************************************************************/
if high=='' then
high=10**(digits - 1) /* maximum nominator/denominator */
x=in /* working copy */
nom=0 /* start values nominator */
den=1 /* denominator */
tnom=1 /* temp nominator */
tden=0 /* temp denominator */
loop While tnom<=high & tden<=high /* nominator... not too large */
n=x.trunc() /* take integer part of x */
z=tnom; /* save temp nominator */
tnom=n*tnom+nom; /* compute new temp nominator */
nom=z /* assign nominator */
z=tden; /* save temp denominator */
tden=n*tden+den /* compute new temp denominato*/
den=z /* assign denominator */
if n=x | tnom/tden=in then do
if tnom>high | tden>high then /* temp value(s) too large */
Leave /* don't use them */
nom=tnom /* otherwise take them as */
den=tden /* final values */
leave /* and end the loop */
end
x=1/(x-n) /* compute x for next round */
end
If den=1 Then Return nom /* an integer */
Else Return nom'/'den /* otherwise a 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
| #BASIC | BASIC | 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
| #Batch_File | Batch File | set src=Hello
set dst=%src% |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Scheme | Scheme | ; Create a terminating Continued Fraction generator for the given rational number.
; Returns one term per call; returns #f when no more terms remaining.
(define make-continued-fraction-gen
(lambda (rat)
(let ((num (numerator rat)) (den (denominator rat)))
(lambda ()
(if (= den 0)
#f
(let ((ret (quotient num den))
(rem (modulo num den)))
(set! num den)
(set! den rem)
ret))))))
; Return the continued fraction representation of a rational number as a string.
(define rat->cf-string
(lambda (rat)
(let* ((cf (make-continued-fraction-gen rat))
(str (string-append "[" (format "~a" (cf))))
(sep ";"))
(let loop ((term (cf)))
(when term
(set! str (string-append str (format "~a ~a" sep term)))
(set! sep ",")
(loop (cf))))
(string-append str "]"))))
; Return the continued fraction representation of a rational number as a list of terms.
(define rat->cf-list
(lambda (rat)
(let ((cf (make-continued-fraction-gen rat))
(lst '()))
(let loop ((term (cf)))
(when term
(set! lst (append lst (list term)))
(loop (cf))))
lst))) |
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).
| #ALGOL_68 | ALGOL 68 | # MODE to hold the compound duration #
MODE DURATION = STRUCT( INT weeks, days, hours, minutes, seconds );
# returns seconds converted to a DURATION #
OP TODURATION = ( LONG INT seconds )DURATION:
BEGIN
LONG INT time := seconds;
DURATION result := DURATION( 0, 0, 0, 0, 0 );
seconds OF result := SHORTEN ( time MOD 60 );
time OVERAB 60;
minutes OF result := SHORTEN ( time MOD 60 );
time OVERAB 60;
hours OF result := SHORTEN ( time MOD 24 );
time OVERAB 24;
days OF result := SHORTEN ( time MOD 7 );
time OVERAB 7;
weeks OF result := SHORTEN time;
result
END # DURATION # ;# returns seconds converted to a DURATION #
OP TODURATION = ( INT seconds )DURATION: TODURATION LENG seconds;
# returns a readable form of the DURATION #
OP TOSTRING = ( DURATION t )STRING:
BEGIN
STRING result := "";
STRING separator := "";
IF weeks OF t /= 0 THEN result +:= separator + whole( weeks OF t, 0 ) + " wk"; separator := ", " FI;
IF days OF t /= 0 THEN result +:= separator + whole( days OF t, 0 ) + " d"; separator := ", " FI;
IF hours OF t /= 0 THEN result +:= separator + whole( hours OF t, 0 ) + " hr"; separator := ", " FI;
IF minutes OF t /= 0 THEN result +:= separator + whole( minutes OF t, 0 ) + " min"; separator := ", " FI;
IF seconds OF t /= 0 THEN result +:= separator + whole( seconds OF t, 0 ) + " sec"; separator := ", " FI;
IF result = ""
THEN
# duration is 0 #
result := "0 sec"
FI;
result
END # TOSTRING # ;
# test cases #
print( ( TOSTRING TODURATION 7259, newline ) );
print( ( TOSTRING TODURATION 86400, newline ) );
print( ( TOSTRING TODURATION 6000000, newline ) ) |
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
| #Nim | Nim | import math
import fenv
type
Rational = object
numerator: int
denominator: int
proc `$`(self: Rational): string =
if self.denominator == 1:
$self.numerator
else:
$self.numerator & "//" & $self.denominator
func rationalize(x: float, tol: float = epsilon(float)): Rational =
var xx = x
let flagNeg = xx < 0.0
if flagNeg:
xx = -xx
if xx < minimumPositiveValue(float):
return Rational(numerator: 0, denominator: 1)
if abs(xx - round(xx)) < tol:
return Rational(numerator: int(round(xx)), denominator: 1)
var a = 0
var b = 1
var c = int(ceil(xx))
var d = 1
var aux1 = high(int) div 2
while c < aux1 and d < aux1:
var aux2 = (float(a) + float(c)) / (float(b) + float(d))
if abs(xx - aux2) < tol:
break
if xx > aux2:
inc a, c
inc b, d
else:
inc c, a
inc d, b
var gcd = gcd(a + c, b + d)
if flagNeg:
Rational(numerator: -(a + c) div gcd, denominator: (b + d) div gcd)
else:
Rational(numerator: (a + c) div gcd, denominator: (b + d) div gcd)
echo rationalize(0.9054054054)
echo rationalize(0.9054054054, 0.0001)
echo rationalize(0.5185185185)
echo rationalize(0.5185185185, 0.0001)
echo rationalize(0.75)
echo rationalize(0.1428571428, 0.001)
echo rationalize(35.000)
echo rationalize(35.001)
echo rationalize(0.9)
echo rationalize(0.99)
echo rationalize(0.909)
echo rationalize(0.909, 0.001) |
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
| #PARI.2FGP | PARI/GP | convert(x)={
my(n=0);
while(x-floor(x*10^n)/10^n!=0.,n++);
floor(x*10^n)/10^n
}; |
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
| #BBC_BASIC | BBC BASIC | source$ = "Hello, world!"
REM Copy the contents of a string:
copy$ = source$
PRINT copy$
REM Make an additional reference to a string:
!^same$ = !^source$
?(^same$+4) = ?(^source$+4)
?(^same$+5) = ?(^source$+5)
PRINT same$ |
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
| #BQN | BQN | a ← "Hello"
b ← a
•Show a‿b
a ↩ "hi"
•Show a‿b |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Sidef | Sidef | func r2cf(num, den) {
func() {
den || return nil
var q = num//den
(num, den) = (den, num - q*den)
return q
}
}
func showcf(f) {
print "["
var n = f()
print "#{n}" if defined(n)
print "; #{n}" while defined(n = f())
print "]\n"
}
[
[1/2, 3/1, 23/8, 13/11, 22/7, -151/77],
[14142/10000, 141421/100000, 1414214/1000000, 14142136/10000000],
[314285714/100000000],
].each { |seq|
seq.each { |r| showcf(r2cf(r.nude)) }
print "\n"
} |
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).
| #ALGOL_W | ALGOL W | begin
% record structure to hold a compound duration %
record Duration ( integer weeks, days, hours, minutes, seconds );
% returns seconds converted to a Duration %
reference(Duration) procedure toDuration( integer value secs ) ;
begin
integer time;
reference(Duration) d;
time := secs;
d := Duration( 0, 0, 0, 0, 0 );
seconds(d) := time rem 60;
time := time div 60;
minutes(d) := time rem 60;
time := time div 60;
hours(d) := time rem 24;
time := time div 24;
days(d) := time rem 7;
time := time div 7;
weeks(d) := time;
d
end toDuration ;
% returns a readable form of the DURATION %
string(80) procedure durationToString ( reference(Duration) value d ) ;
begin
% appends an element of the compound duration to text %
procedure add ( integer value componentValue
; string(6) value componentName
; integer value nameLength
) ;
begin
string(9) vStr;
integer v, vPos;
if needSeparator then begin
% must separate this component from the previous %
text( textPos // 2 ) := ", ";
textPos:= textPos + 2
end if_needSepartator ;
% add the value %
% construct a string representaton of the value with the digits reversed %
% as this routine isn't called if componentValue is 0 or -ve, we don't need to handle %
% the componentVaue <= 0 case %
v := componentValue;
vStr := "";
vPos := 0;
while v > 0 do begin
vStr( vPos // 1 ) := code( decode( "0" ) + ( v rem 10 ) );
vPos := vPos + 1;
v := v div 10
end while_v_gt_0 ;
% add the digits in the correct order %
while vPos > 0 do begin
vPos := vPos - 1;
text( textPos // 1 ) := vStr( vPos // 1 );
textPos := textPos + 1
end while_vPos_gt_0 ;
% add the component name %
text( textPos // 6 ) := componentName;
textPos := textPos + nameLength;
% if there is another component, we'll need a separator %
needSeparator := true
end add ;
string(80) text;
logical needSeparator;
integer textPos;
textPos := 0;
text := "";
needSeparator := false;
if weeks(d) not = 0 then add( weeks(d), " wk", 3 );
if days(d) not = 0 then add( days(d), " d", 2 );
if hours(d) not = 0 then add( hours(d), " hr", 3 );
if minutes(d) not = 0 then add( minutes(d), " min", 4 );
if seconds(d) not = 0 then add( seconds(d), " sec", 4 );
if text = "" then begin
% duration is 0 %
text := "0 sec"
end if_text_is_blank ;
text
end % durationToString % ;
% test cases %
write( durationToString( toDuration( 7259 ) ) );
write( durationToString( toDuration( 86400 ) ) );
write( durationToString( toDuration( 6000000 ) ) )
end. |
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
| #Perl | Perl | sub gcd {
my ($m, $n) = @_;
($m, $n) = ($n, $m % $n) while $n;
return $m
}
sub rat_machine {
my $n = shift;
my $denom = 1;
while ($n != int $n) {
# assuming the machine format is base 2, and multiplying
# by 2 doesn't change the mantissa
$n *= 2;
# multiply denom by 2, ignoring (very) possible overflow
$denom <<= 1;
}
if ($n) {
my $g = gcd($n, $denom);
$n /= $g;
$denom /= $g;
}
return $n, $denom;
}
# helper, make continued fraction back into normal fraction
sub get_denom {
my ($num, $denom) = (1, pop @_);
for (reverse @_) {
($num, $denom) = ($denom, $_ * $denom + $num);
}
wantarray ? ($num, $denom) : $denom
}
sub best_approx {
my ($n, $limit) = @_;
my ($denom, $neg);
if ($n < 0) {
$neg = 1;
$n = -$n;
}
my $int = int($n);
my ($num, $denom, @coef) = (1, $n - $int);
# continued fraction, sort of
while (1) {
# make sure it terminates
last if $limit * $denom < 1;
my $i = int($num / $denom);
# not the right way to get limit, but it works
push @coef, $i;
if (get_denom(@coef) > $limit) {
pop @coef;
last;
}
# we lose precision here, but c'est la vie
($num, $denom) = ($denom, $num - $i * $denom);
}
($num, $denom) = get_denom @coef;
$num += $denom * $int;
return $neg ? -$num : $num, $denom;
}
sub rat_string {
my $n = shift;
my $denom = 1;
my $neg;
# trival xyz.0000 ... case
$n =~ s/\.0+$//;
return $n, 1 unless $n =~ /\./;
if ($n =~ /^-/) {
$neg = 1;
$n =~ s/^-//;
}
# shift decimal point to the right till it's gone
$denom *= 10 while $n =~ s/\.(\d)/$1\./;
$n =~ s/\.$//;
# removing leading zeros lest it looks like octal
$n =~ s/^0*//;
if ($n) {
my $g = gcd($n, $denom);
$n /= $g;
$denom /= $g;
}
return $neg ? -$n : $n, $denom;
}
my $limit = 1e8;
my $x = 3/8;
print "3/8 = $x:\n";
printf "machine: %d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = 137/4291;
print "\n137/4291 = $x:\n";
printf "machine: %d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = sqrt(1/2);
print "\n1/sqrt(2) = $x\n";
printf "machine: %d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
printf "approx below 10: %d/%d\n", best_approx $x, 10;
printf "approx below 100: %d/%d\n", best_approx $x, 100;
printf "approx below 1000: %d/%d\n", best_approx $x, 1000;
printf "approx below 10000: %d/%d\n", best_approx $x, 10000;
printf "approx below 100000: %d/%d\n", best_approx $x, 100000;
printf "approx below $limit: %d/%d\n", best_approx $x, $limit;
$x = -4 * atan2(1,1);
print "\n-Pi = $x\n";
printf "machine: %d/%d\n", rat_machine $x;
printf "string: %d/%d\n", rat_string $x;
for (map { 10 ** $_ } 1 .. 10) {
printf "approx below %g: %d / %d\n", $_, best_approx($x, $_)
} |
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
| #Bracmat | Bracmat | abcdef:?a;
!a:?b;
c=abcdef;
!c:?d;
!a:!b { variables a and b are the same and probably referencing the same string }
!a:!d { variables a and d are also the same but not referencing the same string }
|
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
| #C | C | #include <stdlib.h> /* exit(), free() */
#include <stdio.h> /* fputs(), perror(), printf() */
#include <string.h>
int
main()
{
size_t len;
char src[] = "Hello";
char dst1[80], dst2[80];
char *dst3, *ref;
/*
* Option 1. Use strcpy() from <string.h>.
*
* DANGER! strcpy() can overflow the destination buffer.
* strcpy() is only safe if the source string is shorter than
* the destination buffer. We know that "Hello" (6 characters
* with the final '\0') easily fits in dst1 (80 characters).
*/
strcpy(dst1, src);
/*
* Option 2. Use strlen() and memcpy() from <string.h>, to copy
* strlen(src) + 1 bytes including the final '\0'.
*/
len = strlen(src);
if (len >= sizeof dst2) {
fputs("The buffer is too small!\n", stderr);
exit(1);
}
memcpy(dst2, src, len + 1);
/*
* Option 3. Use strdup() from <string.h>, to allocate a copy.
*/
dst3 = strdup(src);
if (dst3 == NULL) {
/* Failed to allocate memory! */
perror("strdup");
exit(1);
}
/* Create another reference to the source string. */
ref = src;
/* Modify the source string, not its copies. */
memset(src, '-', 5);
printf(" src: %s\n", src); /* src: ----- */
printf("dst1: %s\n", dst1); /* dst1: Hello */
printf("dst2: %s\n", dst2); /* dst2: Hello */
printf("dst3: %s\n", dst3); /* dst3: Hello */
printf(" ref: %s\n", ref); /* ref: ----- */
/* Free memory from strdup(). */
free(dst3);
return 0;
} |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Tcl | Tcl | package require Tcl 8.6
proc r2cf {n1 {n2 1}} {
# Convert a decimal fraction (e.g., 1.23) into a form we can handle
if {$n1 != int($n1) && [regexp {\.(\d+)} $n1 -> suffix]} {
set pow [string length $suffix]
set n1 [expr {int($n1 * 10**$pow)}]
set n2 [expr {$n2 * 10**$pow}]
}
# Construct the continued fraction as a coroutine that yields the digits in sequence
coroutine cf\#[incr ::cfcounter] apply {{n1 n2} {
yield [info coroutine]
while {$n2 > 0} {
yield [expr {$n1 / $n2}]
set n2 [expr {$n1 % [set n1 $n2]}]
}
return -code break
}} $n1 $n2
} |
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).
| #APL | APL | duration←{
names←'wk' 'd' 'hr' 'min' 'sec'
parts←0 7 24 60 60⊤⍵
fmt←⍕¨(parts≠0)/parts,¨names
¯2↓∊fmt,¨⊂', '
} |
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
| #Phix | Phix | with javascript_semantics
function decrat(string s)
integer nom = 0,
denom = 1
assert(s[1..2]="0.")
for i=3 to length(s) do
integer ch = s[i]
assert(ch>='0' and ch<='9')
nom = nom*10 + ch-'0'
denom *= 10
end for
return sq_div({nom,denom},gcd(nom,denom))
end function
?decrat("0.9054054")
?decrat("0.518518")
?decrat("0.75")
|
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
| #C.23 | C# | string src = "Hello";
string 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
| #C.2B.2B | C++ | #include <iostream>
#include <string>
int main( ) {
std::string original ("This is the original");
std::string my_copy = original;
std::cout << "This is the copy: " << my_copy << std::endl;
original = "Now we change the original! ";
std::cout << "my_copy still is " << my_copy << std::endl;
} |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #Wren | Wren | import "/rat" for Rat
import "/fmt" for Fmt
var toContFrac = Fn.new { |r|
var a = r.num
var b = r.den
while (true) {
Fiber.yield((a/b).truncate)
var t = a % b
a = b
b = t
if (a == 1) return
}
}
var groups = [
[ [1, 2], [3, 1], [23, 8], [13, 11], [22, 7], [-151, 77] ],
[ [14142, 1e4], [141421, 1e5], [1414214, 1e6], [14142136, 1e7] ],
[ [31, 10], [314, 100], [3142, 1e3], [31428, 1e4], [314285, 1e5], [3142857, 1e6],
[31428571, 1e7], [314285714,1e8]]
]
var lengths = [ [4, 2], [8, 8], [9, 9] ]
var headings = [ "Examples ->", "Sqrt(2) ->", "Pi ->" ]
var i = 0
for (group in groups) {
System.print(headings[i])
for (pair in group) {
Fmt.write("$*d / $*d = ", lengths[i][0], pair[0], -lengths[i][1], pair[1])
var f = Fiber.new(toContFrac)
var r = Rat.new(pair[0], pair[1])
while (!f.isDone) {
var d = f.call(r)
if (d) System.write("%(d) ")
}
System.print()
}
System.print()
i = i + 1
} |
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).
| #AppleScript | AppleScript |
-------------------- COMPOUND DURATIONS ------------------
-- weekParts Int -> [Int]
on weekParts(intSeconds)
unitParts(intSeconds, [missing value, 7, 24, 60, 60])
end weekParts
-- localCompoundDuration :: Int -> String
on localCompoundDuration(localNames, intSeconds)
-- [String] -> (Int, String) -> [String]
script formatted
on |λ|(lstPair, a)
set q to item 1 of lstPair
if q > 0 then
{(q as string) & space & item 2 of lstPair} & a
else
a
end if
end |λ|
end script
intercalate(", ", ¬
foldr(formatted, [], ¬
zip(weekParts(intSeconds), localNames)))
end localCompoundDuration
------------------ INTEGER DECOMPOSITION -----------------
-- unitParts :: Int -> [maybe Int] -> [Int]
on unitParts(intTotal, unitList)
-- partList :: Record -> Int -> Record
script partList
on |λ|(x, a)
set intRest to remaining of a
if x is not missing value then
set intMod to intRest mod x
set d to x
else
set intMod to intRest
set d to 1
end if
{remaining:(intRest - intMod) div d, parts:{intMod} & parts of a}
end |λ|
end script
parts of foldr(partList, ¬
{remaining:intTotal, parts:[]}, unitList)
end unitParts
--------------------------- TEST -------------------------
on run
script angloNames
on |λ|(n)
(n as string) & " -> " & ¬
localCompoundDuration(["wk", "d", "hr", "min", "sec"], n)
end |λ|
end script
unlines(map(angloNames, [7259, 86400, 6000000]))
end run
-------------------- GENERIC FUNCTIONS -------------------
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
-- A list of step-wise pairs drawn from xs and ys
-- up to the length of the shorter of those lists.
set lng to min(length of xs, length of ys)
set zs to {}
repeat with i from 1 to lng
set end of zs to {item i of xs, item i of ys}
end repeat
return zs
end zip |
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
| #PHP | PHP | function asRational($val, $tolerance = 1.e-6)
{
if ($val == (int) $val) {
// integer
return $val;
}
$h1=1;
$h2=0;
$k1=0;
$k2=1;
$b = 1 / $val;
do {
$b = 1 / $b;
$a = floor($b);
$aux = $h1;
$h1 = $a * $h1 + $h2;
$h2 = $aux;
$aux = $k1;
$k1 = $a * $k1 + $k2;
$k2 = $aux;
$b = $b - $a;
} while (abs($val-$h1/$k1) > $val * $tolerance);
return $h1.'/'.$k1;
}
echo asRational(1/5)."\n"; // "1/5"
echo asRational(1/4)."\n"; // "1/4"
echo asRational(1/3)."\n"; // "1/3"
echo asRational(5)."\n"; // "5" |
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
| #Clojure | Clojure | (let [s "hello"
s1 s]
(println s s1)) |
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
| #COBOL | COBOL | MOVE "Hello" TO src
MOVE src TO dst |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #XPL0 | XPL0 | include c:\cxpl\codes;
real Val;
proc R2CF(N1, N2, Lev); \Output continued fraction for N1/N2
int N1, N2, Lev;
int Quot, Rem;
[if Lev=0 then Val:= 0.0;
Quot:= N1/N2;
Rem:= rem(0);
IntOut(0, Quot);
if Rem then [ChOut(0, if Lev then ^, else ^;); R2CF(N2, Rem, Lev+1)];
Val:= Val + float(Quot); \generate value from continued fraction
if Lev then Val:= 1.0/Val;
];
int I, Data;
[Data:= [1,2, 3,1, 23,8, 13,11, 22,7, 0];
Format(0, 15);
I:= 0;
while Data(I) do
[IntOut(0, Data(I)); ChOut(0, ^/); IntOut(0, Data(I+1)); ChOut(0, 9\tab\);
ChOut(0, ^[); R2CF(Data(I), Data(I+1), 0); ChOut(0, ^]); ChOut(0, 9\tab\);
RlOut(0, Val); CrLf(0);
I:= I+2];
] |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} }
N
)
{\displaystyle N)}
, which will output a continued fraction assuming:
N
1
{\displaystyle N_{1}}
is the numerator
N
2
{\displaystyle N_{2}}
is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of
N
1
{\displaystyle N_{1}}
divided by
N
2
{\displaystyle N_{2}}
. It then sets
N
1
{\displaystyle N_{1}}
to
N
2
{\displaystyle N_{2}}
and
N
2
{\displaystyle N_{2}}
to the determined remainder part. It then outputs the determined integer part. It does this until
a
b
s
(
N
2
)
{\displaystyle \mathrm {abs} (N_{2})}
is zero.
Demonstrate the function by outputing the continued fraction for:
1/2
3
23/8
13/11
22/7
-151/77
2
{\displaystyle {\sqrt {2}}}
should approach
[
1
;
2
,
2
,
2
,
2
,
…
]
{\displaystyle [1;2,2,2,2,\ldots ]}
try ever closer rational approximations until boredom gets the better of you:
14142,10000
141421,100000
1414214,1000000
14142136,10000000
Try :
31,10
314,100
3142,1000
31428,10000
314285,100000
3142857,1000000
31428571,10000000
314285714,100000000
Observe how this rational number behaves differently to
2
{\displaystyle {\sqrt {2}}}
and convince yourself that, in the same way as
3.7
{\displaystyle 3.7}
may be represented as
3.70
{\displaystyle 3.70}
when an extra decimal place is required,
[
3
;
7
]
{\displaystyle [3;7]}
may be represented as
[
3
;
7
,
∞
]
{\displaystyle [3;7,\infty ]}
when an extra term is required.
| #zkl | zkl | fcn r2cf(nom,dnom){ // -->Walker (iterator)
Walker.tweak(fcn(state){
nom,dnom:=state;
if(dnom==0) return(Void.Stop);
n,d:=nom.divr(dnom);
state.clear(dnom,d);
n
}.fp(List(nom,dnom))) // partial application (light weight closure)
} |
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).
| #Applesoft_BASIC | Applesoft BASIC | 100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC
110 FOR I = 0 TO 4
120 READ M(I), U$(I)
130 NEXT
140 DATA7259,86400,6000000
150 ON ERR GOTO 270
160 READ S
170 GOSUB 200
180 PRINT S " = " S$
190 GOTO 160
200 N = S
210 S$ = ""
220 FOR I = 0 TO 4
230 IF INT(N / M(I)) THEN S$ = S$ + MID$(", ", 1, (LEN(S$) > 0) * 2) + STR$(INT(N / M(I))) + " " + U$(I)
240 N = N - INT(N / M(I)) * M(I)
250 NEXT I
260 RETURN
270 END
|
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).
| #Arturo | Arturo | Units: [" wk", " d", " hr", " min", " sec"]
Quantities: @[7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
durationString: function [d][
dur: d
idx: 0
result: new []
while [not? zero? dur][
q: dur / Quantities\[idx]
if not? zero? q [
dur: dur % Quantities\[idx]
'result ++ ~{|q||Units\[idx]|}
]
idx: idx +1
]
return join.with:", " result
]
loop [7259 86400 6000000] 't [
print [t "s => " durationString t]
] |
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
| #PL.2FI | PL/I | (size, fofl):
Convert_Decimal_To_Rational: procedure options (main); /* 14 January 2014, from Ada */
Real_To_Rational: procedure (R, Bound, Numerator, Denominator) recursive
options (reorder);
declare R float (18), Bound float,
(Numerator, Denominator) fixed binary (31);
declare Error float;
declare Best fixed binary initial (1);
declare Best_Error float initial (huge(error));
declare I fixed binary (31);
if R = 0 then
do;
Numerator = 0;
Denominator = 1;
return;
end;
else if R < 0 then
do;
call Real_To_Rational(-R, Bound, Numerator, Denominator);
Numerator = -Numerator;
return;
end;
else
do I = 1 to Bound;
Error = abs(I * R - trunc(I * R + sign(R)*0.5));
if Error < Best_Error then
do;
Best = I;
Best_Error = Error;
end;
end;
Denominator = Best;
Numerator = Denominator * R + sign(R) * 0.5;
end Real_To_Rational;
declare (Num, Denom) fixed binary (31);
declare R float (18);
declare I fixed BINARY;
do R = 0.75, 0.25, 0.3333333, 0.518518000, 0.905405400,
0.142857143, 3.141592654, 2.718281828, -0.423310825,
31.415926536, 0;
put skip edit(R) (f(13,9));
do I = 0 to 4;
call Real_to_Rational(R, 10**I, Num, Denom);
put edit(' ' || trim(Num) || ' / ' || trim(Denom)) (a);
end;
end;
end Convert_Decimal_To_Rational; |
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
| #PureBasic | PureBasic | Procedure.i ggT(a.i, b.i)
Define t.i : If a < b : Swap a, b : EndIf
While a%b : t=a : a=b : b=t%a : Wend : ProcedureReturn b
EndProcedure
Procedure.s Dec2Rat(dn.d)
Define nk$, gt.i, res$
nk$=Trim(StringField(StrD(dn),2,"."),"0")
gt=ggT(Val(nk$),Int(Pow(10.0,Len(nk$))))
res$=Str(Val(nk$)/gt)+"/"+Str(Int(Pow(10.0,Len(nk$)))/gt)
ProcedureReturn res$
EndProcedure
OpenConsole()
Define d.d
Repeat
Read.d d : If Not (d>0.0 And d<1.0) : Break : EndIf
Print(LSet(StrD(d),15," ")+" -> "+#TAB$+Dec2Rat(d)+#CRLF$)
ForEver
Input() : End
DataSection
Data.d 0.9054054,0.518518,0.75,0.0
EndDataSection |
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
| #ColdFusion | ColdFusion | <cfset stringOrig = "I am a string." />
<cfset stringCopy = stringOrig /> |
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
| #Common_Lisp | Common Lisp | (let* ((s1 "Hello") ; s1 is a variable containing a string
(s1-ref s1) ; another variable with the same value
(s2 (copy-seq s1))) ; s2 has a distinct string object with the same contents
(assert (eq s1 s1-ref)) ; same object
(assert (not (eq s1 s2))) ; different object
(assert (equal s1 s2)) ; same contents
(fill s2 #\!) ; overwrite s2
(princ s1)
(princ s2)) ; will print "Hello!!!!!" |
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).
| #AutoHotkey | AutoHotkey | duration(n){
sec:=1, min:=60*sec, hr:=60*min, day:=24*hr, wk:=7*day
w :=n//wk , n:=Mod(n,wk)
d :=n//day , n:=Mod(n,day)
h :=n//hr , n:=Mod(n,hr)
m :=n//min , n:=Mod(n,min)
s :=n
return trim((w?w " wk, ":"") (d?d " d, ":"") (h?h " hr, ":"") (m?m " min, ":"") (s?s " sec":""),", ")
} |
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
| #Python | Python | >>> from fractions import Fraction
>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))
0.9054054 67/74
0.518518 14/27
0.75 3/4
>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))
0.9054054 4527027/5000000
0.518518 259259/500000
0.75 3/4
>>> |
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
| #Component_Pascal | Component Pascal |
VAR
str1: ARRAY 128 OF CHAR;
str2: ARRAY 32 OF CHAR;
str3: ARRAY 25 OF CHAR;
|
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
| #Computer.2Fzero_Assembly | Computer/zero Assembly | ldsrc: LDA src
stdest: STA dest
BRZ done ; 0-terminated
LDA ldsrc
ADD one
STA ldsrc
LDA stdest
ADD one
STA stdest
JMP ldsrc
done: STP
one: 1
src: 82 ; ASCII
111
115
101
116
116
97
0
dest: |
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).
| #AWK | AWK |
# syntax: GAWK -f CONVERT_SECONDS_TO_COMPOUND_DURATION.AWK
BEGIN {
n = split("7259 86400 6000000 0 1 60 3600 604799 604800 694861",arr," ")
for (i=1; i<=n; i++) {
printf("%9s %s\n",arr[i],howlong(arr[i]))
}
exit(0)
}
function howlong(seconds, n_day,n_hour,n_min,n_sec,n_week,str,x) {
if (seconds >= (x = 60*60*24*7)) {
n_week = int(seconds / x)
seconds = seconds % x
}
if (seconds >= (x = 60*60*24)) {
n_day = int(seconds / x)
seconds = seconds % x
}
if (seconds >= (x = 60*60)) {
n_hour = int(seconds / x)
seconds = seconds % x
}
if (seconds >= (x = 60)) {
n_min = int(seconds / x)
seconds = seconds % x
}
n_sec = int(seconds)
str = (n_week > 0) ? (str n_week " wk, ") : str
str = (n_day > 0) ? (str n_day " d, ") : str
str = (n_hour > 0) ? (str n_hour " hr, ") : str
str = (n_min > 0) ? (str n_min " min, ") : str
str = (n_sec > 0) ? (str n_sec " sec") : str
sub(/, $/,"",str)
return(str)
}
|
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.
| #11l | 11l | F calc(f_a, f_b, =n = 1000)
V r = 0.0
L n > 0
r = f_b(n) / (f_a(n) + r)
n--
R f_a(0) + r
print(calc(n -> I n > 0 {2} E 1, n -> 1))
print(calc(n -> I n > 0 {n} E 2, n -> I n > 1 {n - 1} E 1))
print(calc(n -> I n > 0 {6} E 3, n -> (2 * n - 1) ^ 2)) |
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
| #R | R |
ratio<-function(decimal){
denominator=1
while(nchar(decimal*denominator)!=nchar(round(decimal*denominator))){
denominator=denominator+1
}
str=paste(decimal*denominator,"/",sep="")
str=paste(str,denominator,sep="")
return(str)
}
|
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
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ dup echo$
say " is "
$->v drop
dup 100 > if
[ say "approximately "
proper 100 round
improper ]
vulgar$ echo$
say "." cr ] is task ( $ --> )
$ "0.9054054 0.518518 0.75" nest$ witheach task |
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
| #Crystal | Crystal | s1 = "Hello"
s2 = s1 |
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 | D | void main() {
string src = "This is a string";
// copy contents:
auto dest1 = src.idup;
// copy contents to mutable char array
auto dest2 = src.dup;
// copy just the fat reference of the string
auto dest3 = 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).
| #BASIC | BASIC | 10 REM CONVERT SECONDS TO COMPOUND DURATION
20 REM ADAPTED FROM RUN BASIC VERSION
30 REM ===============================================================
40 PRINT CHR$(14)
50 SEC = 7259
60 GOSUB 1000
70 SEC = 85400
80 GOSUB 1000
90 SEC = 6000000
100 GOSUB 1000
110 END
120 REM ==============================================================
1000 WK = INT(SEC/60/60/24/7)
1010 DY = INT(SEC/60/60/24) - 7*WK
1020 HR = INT(SEC/60/60) - 24*(DY+7*WK)
1030 MN = INT(SEC/60) - 60*(HR+24*(DY+7*WK))
1040 SC = SEC - 60*(MN+60*(HR+24*(DY+7*WK)))
1050 PRINT SEC;"SEC" : PRINT " =";
1055 F = 0
1060 IF WK = 0 THEN 1080
1070 PRINT WK;"WK"; : F = 1
1080 IF DY = 0 THEN 1110
1090 IF F THEN PRINT ",";
1100 PRINT DY;"DY"; : F = 1
1110 IF HR = 0 THEN 1140
1120 IF F THEN PRINT ",";
1130 PRINT HR;"HR"; : F = 1
1140 IF MN = 0 THEN 1170
1150 IF F THEN PRINT ",";
1160 PRINT MN;"MIN"; : F = 1
1170 IF (SC > 0) AND F THEN PRINT ",";SC;"SEC" : GOTO 1200
1180 IF (SC = 0) AND F THEN 1200
1190 PRINT SC;"SEC"
1200 PRINT
1210 RETURN |
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.
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
DEFINE JSR="$20"
DEFINE RTS="$60"
PROC CoeffA=*(INT n REAL POINTER res)
[JSR $00 $00 ;JSR to address set by SetCoeffA
RTS]
PROC CoeffB=*(INT n REAL POINTER res)
[JSR $00 $00 ;JSR to address set by SetCoeffB
RTS]
PROC SetCoeffA(PTR p)
PTR addr
addr=CoeffA+1 ;location of address of JSR
PokeC(addr,p)
RETURN
PROC SetCoeffB(PTR p)
PTR addr
addr=CoeffB+1 ;location of address of JSR
PokeC(addr,p)
RETURN
PROC Calc(PTR funA,funB INT count REAL POINTER res)
INT i
REAL a,b,tmp
SetCoeffA(funA)
SetCoeffB(funB)
IntToReal(0,res)
i=count
WHILE i>0
DO
CoeffA(i,a)
CoeffB(i,b)
RealAdd(a,res,tmp)
RealDiv(b,tmp,res)
i==-1
OD
CoeffA(0,a)
RealAdd(a,res,tmp)
RealAssign(tmp,res)
RETURN
PROC sqrtA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(2,res)
ELSE
IntToReal(1,res)
FI
RETURN
PROC sqrtB(INT n REAL POINTER res)
IntToReal(1,res)
RETURN
PROC napierA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(n,res)
ELSE
IntToReal(2,res)
FI
RETURN
PROC napierB(INT n REAL POINTER res)
IF n>1 THEN
IntToReal(n-1,res)
ELSE
IntToReal(1,res)
FI
RETURN
PROC piA(INT n REAL POINTER res)
IF n>0 THEN
IntToReal(6,res)
ELSE
IntToReal(3,res)
FI
RETURN
PROC piB(INT n REAL POINTER res)
REAL tmp
IntToReal(2*n-1,tmp)
RealMult(tmp,tmp,res)
RETURN
PROC Main()
REAL res
Put(125) PutE() ;clear the screen
Calc(sqrtA,sqrtB,50,res)
Print(" Sqrt2=") PrintRE(res)
Calc(napierA,napierB,50,res)
Print("Napier=") PrintRE(res)
Calc(piA,piB,500,res)
Print(" Pi=") PrintRE(res)
RETURN |
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.
| #Ada | Ada | generic
type Scalar is digits <>;
with function A (N : in Natural) return Natural;
with function B (N : in Positive) return Natural;
function Continued_Fraction (Steps : in Natural) return Scalar; |
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
| #Racket | Racket | #lang racket
(inexact->exact 0.75) ; -> 3/4
(exact->inexact 3/4) ; -> 0.75
(exact->inexact 67/74) ; -> 0.9054054054054054
(inexact->exact 0.9054054054054054) ;-> 8155166892806033/9007199254740992 |
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
| #Raku | Raku | say .nude.join('/') for 0.9054054, 0.518518, 0.75; |
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
| #dc | dc | [a string] # push "a string" on the main stack
d # duplicate the top value
f # show the current contents of the main stack |
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
| #Delphi | Delphi | program CopyString;
{$APPTYPE CONSOLE}
var
s1: string;
s2: string;
begin
s1 := 'Goodbye';
s2 := s1; // S2 points at the same string as S1
s2 := s2 + ', World!'; // A new string is created for S2
Writeln(s1);
Writeln(s2);
end. |
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).
| #Batch_File | Batch File | @echo off
::The Main Thing...
for %%d in (7259 86400 6000000) do call :duration %%d
exit/b 0
::/The Main Thing.
::The Function...
:duration
set output=
set /a "wk=%1/604800,rem=%1%%604800"
if %wk% neq 0 set "output= %wk% wk,"
set /a "d=%rem%/86400,rem=%rem%%%86400"
if %d% neq 0 set "output=%output% %d% d,"
set /a "hr=%rem%/3600,rem=%rem%%%3600"
if %hr% neq 0 set "output=%output% %hr% hr,"
set /a "min=%rem%/60,rem=%rem%%%60"
if %min% neq 0 set "output=%output% %min% min,"
if %rem% neq 0 set "output=%output% %rem% sec,"
if %1 gtr 0 echo %1 sec = %output:~1,-1%
goto :EOF
::/The Function. |
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.
| #Ada | Ada | with Ada.Containers.Indefinite_Vectors;
package Nutrition is
type Food is interface;
procedure Eat (Object : in out Food) is abstract;
end Nutrition;
with Ada.Containers;
with Nutrition;
generic
type New_Food is new Nutrition.Food;
package Food_Boxes is
package Food_Vectors is
new Ada.Containers.Indefinite_Vectors
( Index_Type => Positive,
Element_Type => New_Food
);
subtype Food_Box is Food_Vectors.Vector;
end Food_Boxes; |
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.
| #11l | 11l | F primes_upto(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .. limit).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
V primelist = primes_upto(1'000'000)
V listlen = primelist.len
V pindex = 1
V old_diff = -1
V curr_list = [primelist[0]]
[Int] longest_list
L pindex < listlen
V diff = primelist[pindex] - primelist[pindex - 1]
I diff > old_diff
curr_list.append(primelist[pindex])
I curr_list.len > longest_list.len
longest_list = curr_list
E
curr_list = [primelist[pindex - 1], primelist[pindex]]
old_diff = diff
pindex++
print(longest_list)
pindex = 1
old_diff = -1
curr_list = [primelist[0]]
longest_list.drop()
L pindex < listlen
V diff = primelist[pindex] - primelist[pindex - 1]
I diff < old_diff
curr_list.append(primelist[pindex])
I curr_list.len > longest_list.len
longest_list = curr_list
E
curr_list = [primelist[pindex - 1], primelist[pindex]]
old_diff = diff
pindex++
print(longest_list) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.