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/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Raku | Raku | say DateTime.now;
dd DateTime.now.Instant; |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Python | Python | from numpy import array, tril, sum
A = [[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
print(sum(tril(A, -1))) # 69 |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #R | R | mat <- rbind(c(1,3,7,8,10),
c(2,4,16,14,4),
c(3,1,9,18,11),
c(12,14,17,18,20),
c(7,1,3,9,5))
print(sum(mat[lower.tri(mat)])) |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #JavaScript | JavaScript | (function () {
'use strict';
// GENERIC FUNCTIONS
// concatMap :: (a -> [b]) -> [a] -> [b]
var concatMap = function concatMap(f, xs) {
return [].concat.apply([], xs.map(f));
},
// curry :: ((a, b) -> c) -> a -> b -> c
curry = function curry(f) {
return function (a) {
return function (b) {
return f(a, b);
};
};
},
// intersectBy :: (a - > a - > Bool) - > [a] - > [a] - > [a]
intersectBy = function intersectBy(eq, xs, ys) {
return xs.length && ys.length ? xs.filter(function (x) {
return ys.some(curry(eq)(x));
}) : [];
},
// range :: Int -> Int -> Maybe Int -> [Int]
range = function range(m, n, step) {
var d = (step || 1) * (n >= m ? 1 : -1);
return Array.from({
length: Math.floor((n - m) / d) + 1
}, function (_, i) {
return m + i * d;
});
};
// PROBLEM FUNCTIONS
// add, mul :: (Int, Int) -> Int
var add = function add(xy) {
return xy[0] + xy[1];
},
mul = function mul(xy) {
return xy[0] * xy[1];
};
// sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
var sumEq = function sumEq(p) {
var addP = add(p);
return s1.filter(function (q) {
return add(q) === addP;
});
},
mulEq = function mulEq(p) {
var mulP = mul(p);
return s1.filter(function (q) {
return mul(q) === mulP;
});
};
// pairEQ :: ((a, a) -> (a, a)) -> Bool
var pairEQ = function pairEQ(a, b) {
return a[0] === b[0] && a[1] === b[1];
};
// MAIN
// xs :: [Int]
var xs = range(1, 100);
// s1 s2, s3, s4 :: [(Int, Int)]
var s1 = concatMap(function (x) {
return concatMap(function (y) {
return 1 < x && x < y && x + y < 100 ? [
[x, y]
] : [];
}, xs);
}, xs),
s2 = s1.filter(function (p) {
return sumEq(p).every(function (q) {
return mulEq(q).length > 1;
});
}),
s3 = s2.filter(function (p) {
return intersectBy(pairEQ, mulEq(p), s2).length === 1;
}),
s4 = s3.filter(function (p) {
return intersectBy(pairEQ, sumEq(p), s3).length === 1;
});
return s4;
})();
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Ruby | Ruby | module TempConvert
FROM_TEMP_SCALE_TO_K =
{'kelvin' => lambda{|t| t},
'celsius' => lambda{|t| t + 273.15},
'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0},
'rankine' => lambda{|t| t * 5/9.0},
'delisle' => lambda{|t| 373.15 - t * 2/3.0},
'newton' => lambda{|t| t * 100/33.0 + 273.15},
'reaumur' => lambda{|t| t * 5/4.0 + 273.15},
'roemer' => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}}
TO_TEMP_SCALE_FROM_K =
{'kelvin' => lambda{|t| t},
'celsius' => lambda{|t| t - 273.15},
'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67},
'rankine' => lambda{|t| t * 9/5.0},
'delisle' => lambda{|t| (373.15 - t) * 3/2.0},
'newton' => lambda{|t| (t - 273.15) * 33/100.0},
'reaumur' => lambda{|t| (t - 273.15) * 4/5.0},
'roemer' => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}}
SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|')
def self.method_missing(meth, *args, &block)
if valid_temperature_conversion?(meth) then
convert_temperature(meth, *args)
else
super
end
end
def self.respond_to_missing?(meth, include_private = false)
valid_temperature_conversion?(meth) || super
end
def self.valid_temperature_conversion?(meth)
!!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/)
end
def self.convert_temperature(meth, temp)
from_scale, to_scale = meth.to_s.split("_to_")
return temp.to_f if from_scale == to_scale # no kelvin roundtrip
TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2)
end
end |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Raven | Raven | time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #REBOL | REBOL | now
print rejoin [now/year "-" now/month "-" now/day " " now/time] |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Raku | Raku | sub lower-triangle-sum (@matrix) { sum flat (1..@matrix).map( { @matrix[^$_]»[^($_-1)] } )»[*-1] }
say lower-triangle-sum
[
[ 1, 3, 7, 8, 10 ],
[ 2, 4, 16, 14, 4 ],
[ 3, 1, 9, 18, 11 ],
[ 12, 14, 17, 18, 20 ],
[ 7, 1, 3, 9, 5 ]
]; |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #REXX | REXX | /* REXX */
ml ='1 3 7 8 10 2 4 16 14 4 3 1 9 18 11 12 14 17 18 20 7 1 3 9 5'
Do i=1 To 5
Do j=1 To 5
Parse Var ml m.i.j ml
End
End
l=''
Do i=1 To 5
Do j=1 To 5
l=l right(m.i.j,2)
End
Say l
l=''
End
sum=0
Do i=2 To 5
Do j=1 To i-1
sum=sum+m.i.j
End
End
Say 'Sum below main diagonal:' sum |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #jq | jq |
# For readability:
def collect(c): map(select(c));
# stream-oriented checks:
def hasMoreThanOne(s): [limit(2;s)] | length > 1;
def hasOne(s): [limit(2;s)] | length == 1;
def prod: .[0] * .[1];
## A stream of admissible [x,y] values
def xy:
[range(2;50) as $x # 1 < X < Y < 100
| range($x+1; 101-$x) as $y
| [$x, $y] ] ;
# The stream of [x,y] pairs matching "S knows the sum is $sum"
def sumEq($sum): select( $sum == add );
# The stream of [x,y] pairs matching "P knows the product is $prod"
def prodEq($p): select( $p == prod );
## The solver:
def solve:
xy as $s0
# S says P does not know:
| $s0
| collect(add as $sum
| all( $s0[]|sumEq($sum);
prod as $p
| hasMoreThanOne($s0[] | prodEq($p)))) as $s1
# P says: Now I know:
| $s1
| collect(prod as $prod | hasOne( $s1[]|prodEq($prod)) ) as $s2
# S says: Now I also know
| $s2[]
| select(add as $sum | hasOne( $s2[] | sumEq($sum)) ) ;
solve
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Run_BASIC | Run BASIC | [loop]
input "Kelvin Degrees";kelvin
if kelvin <= 0 then end ' zero or less ends the program
celcius = kelvin - 273.15
fahrenheit = kelvin * 1.8 - 459.67
rankine = kelvin * 1.8
print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine"
goto [loop] |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Scala | Scala | object TemperatureConversion extends App {
def kelvinToCelsius(k: Double) = k + 273.15
def kelvinToFahrenheit(k: Double) = k * 1.8 - 459.67
def kelvinToRankine(k: Double) = k * 1.8
if (args.length == 1) {
try {
val kelvin = args(0).toDouble
if (kelvin >= 0) {
println(f"K $kelvin%2.2f")
println(f"C ${kelvinToCelsius(kelvin)}%2.2f")
println(f"F ${kelvinToFahrenheit(kelvin)}%2.2f")
println(f"R ${kelvinToRankine(kelvin)}%2.2f")
} else println("%2.2f K is below absolute zero", kelvin)
} catch {
case e: NumberFormatException => System.out.println(e)
case e: Throwable => {
println("Some other exception type:")
e.printStackTrace()
}
}
} else println("Temperature not given.")
} |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Retro | Retro | time putn |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #REXX | REXX | /*REXX program shows various ways to display the system time, including other options. */
say '════════════ Normal format of time'
say 'hh:mm:ss ◄─────────────── hh= is 00 ──► 23'
say 'hh:mm:ss ◄─────────────── hh= hour mm= minute ss= second'
say time()
say time('n') /* (same as the previous example.) */
say time('N') /* " " " " " */
say time('Normal') /* " " " " " */
say time('nitPick') /* " " " " " */
say
say '════════════ Civil format of time'
say 'hh:mmcc ◄─────────────── hh= is 1 ──► 12'
say 'hh:mmam ◄─────────────── hh= hour mm= minute am= ante meridiem'
say 'hh:mmpm ◄─────────────── pm= post meridiem'
say time('C')
say time('civil') /* (same as the previous example.) */
/*ante meridiem≡Latin for before midday*/
/*post " " " after " */
say
say '════════════ long format of time'
say 'hh:mm:ss ◄─────────────── hh= is 0 ──► 23'
say 'hh:mm:ss.ffffff ◄─────────────── hh= hour mm= minute fffff= fractional seconds'
say time('L')
say time('long') /* (same as the previous example.) */
say time('long time no see') /* " " " " " */
say
say '════════════ complete hours since midnight'
say 'hh ◄─────────────── hh = 0 ───► 23'
say time('H')
say time('hours') /* (same as the previous example.) */
say
say '════════════ complete minutes since midnight'
say 'mmmm ◄─────────────── mmmm = 0 ───► 1439'
say time('M')
say time('minutes') /* (same as the previous example.) */
say
say '════════════ complete seconds since midnight'
say 'sssss ◄─────────────── sssss = 0 ───► 86399'
say time('S')
say time('seconds') /* (same as the previous example.) */
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Ring | Ring |
see "working..." + nl
see "Sum of elements below main diagonal of matrix:" + nl
diag = [[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
lenDiag = len(diag)
ind = lenDiag
sumDiag = 0
for n=1 to lenDiag
for m=1 to lenDiag-ind
sumDiag += diag[n][m]
next
ind--
next
see "" + sumDiag + nl
see "done..." + nl
|
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Ruby | Ruby | arr = [
[ 1, 3, 7, 8, 10],
[ 2, 4, 16, 14, 4],
[ 3, 1, 9, 18, 11],
[12, 14, 17, 18, 20],
[ 7, 1, 3, 9, 5]
]
p arr.each_with_index.sum {|row, x| row[0, x].sum}
|
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Julia | Julia |
using Primes
function satisfy1(x::Integer)
prmslt100 = primes(100)
for i in 2:(x ÷ 2)
if i ∈ prmslt100 && x - i ∈ prmslt100
return false
end
end
return true
end
function satisfy2(x::Integer)
once = false
for i in 2:isqrt(x)
if x % i == 0
j = x ÷ i
if 2 < j < 100 && satisfy1(i + j)
if once return false end
once = true
end
end
end
return once
end
function satisfyboth(x::Integer)
if !satisfy1(x) return 0 end
found = 0
for i in 2:(x ÷ 2)
if satisfy2(i * (x - i))
if found > 0 return 0 end
found = i
end
end
return found
end
for i in 2:99
if (j = satisfyboth(i)) > 0
println("Solution: ($j, $(i - j))")
end
end |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Rust | Rust | fn main() -> std::io::Result<()> {
print!("Enter temperature in Kelvin to convert: ");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
match input.trim().parse::<f32>() {
Ok(kelvin) => {
if kelvin < 0.0 {
println!("Negative Kelvin values are not acceptable.");
} else {
println!("{} K", kelvin);
println!("{} °C", kelvin - 273.15);
println!("{} °F", kelvin * 1.8 - 459.67);
println!("{} °R", kelvin * 1.8);
}
}
_ => println!("Could not parse the input to a number."),
}
Ok(())
} |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #11l | 11l | print(sum((1..1000).map(x -> 1.0/x^2))) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Ring | Ring |
/* Output:
** Sun abbreviated weekday name
** Sunday full weekday name
** May abbreviated month name
** May full month name
** 05/24/15 09:58:38 Date & Time
** 24 Day of the month
** 09 Hour (24)
** 09 Hour (12)
** 144 Day of the year
** 05 Month of the year
** 58 Minutes after hour
** AM AM or PM
** 38 Seconds after the hour
** 21 Week of the year (sun-sat)
** 0 day of the week
** 05/24/15 date
** 09:58:38 time
** 15 year of the century
** 2015 year
** Arab Standard Time time zone
** % percent sign
*/
See TimeList()
|
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Ruby | Ruby | t = Time.now
# textual
puts t # => 2013-12-27 18:00:23 +0900
# epoch time
puts t.to_i # => 1388134823
# epoch time with fractional seconds
puts t.to_f # => 1388134823.9801579
# epoch time as a rational (more precision):
puts Time.now.to_r # 1424900671883862959/1000000000
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #11l | 11l | F sum_digits(=n, base)
V r = 0
L n > 0
r += n % base
n I/= base
R r
print(sum_digits(1, 10))
print(sum_digits(1234, 10))
print(sum_digits(F'E, 16))
print(sum_digits(0F'0E, 16)) |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: sum is 0;
var integer: i is 0;
var integer: j is 0;
const array array integer: m is [] ([] ( 1, 3, 7, 8, 10),
[] ( 2, 4, 16, 14, 4),
[] ( 3, 1, 9, 18, 11),
[] (12, 14, 17, 18, 20),
[] ( 7, 1, 3, 9, 5));
begin
for i range 2 to length(m) do
for j range 1 to i - 1 do
sum +:= m[i][j];
end for;
end for;
writeln(sum);
end func; |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Wren | Wren | var m = [
[ 1, 3, 7, 8, 10],
[ 2, 4, 16, 14, 4],
[ 3, 1, 9, 18, 11],
[12, 14, 17, 18, 20],
[ 7, 1, 3, 9, 5]
]
if (m.count != m[0].count) Fiber.abort("Matrix must be square.")
var sum = 0
for (i in 1...m.count) {
for (j in 0...i) {
sum = sum + m[i][j]
}
}
System.print("Sum of elements below main diagonal is %(sum).") |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Kotlin | Kotlin | // version 1.1.4-3
data class P(val x: Int, val y: Int, val sum: Int, val prod: Int)
fun main(args: Array<String>) {
val candidates = mutableListOf<P>()
for (x in 2..49) {
for (y in x + 1..100 - x) {
candidates.add(P(x, y, x + y, x * y))
}
}
val sums = candidates.groupBy { it.sum }
val prods = candidates.groupBy { it.prod }
val fact1 = candidates.filter { sums[it.sum]!!.all { prods[it.prod]!!.size > 1 } }
val fact2 = fact1.filter { prods[it.prod]!!.intersect(fact1).size == 1 }
val fact3 = fact2.filter { sums[it.sum]!!.intersect(fact2).size == 1 }
print("The only solution is : ")
for ((x, y, _, _) in fact3) println("x = $x, y = $y")
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Scheme | Scheme |
(import (scheme base)
(scheme read)
(scheme write))
(define (kelvin->celsius k)
(- k 273.15))
(define (kelvin->fahrenheit k)
(- (* k 1.8) 459.67))
(define (kelvin->rankine k)
(* k 1.8))
;; Run the program
(let ((k (begin (display "Kelvin : ") (flush-output-port) (read))))
(when (number? k)
(display "Celsius : ") (display (kelvin->celsius k)) (newline)
(display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline)
(display "Rankine : ") (display (kelvin->rankine k)) (newline)))
|
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #360_Assembly | 360 Assembly | * Sum of a series 30/03/2017
SUMSER CSECT
USING SUMSER,12 base register
LR 12,15 set addressability
LR 10,14 save r14
LE 4,=E'0' s=0
LE 2,=E'1' i=1
DO WHILE=(CE,2,LE,=E'1000') do i=1 to 1000
LER 0,2 i
MER 0,2 *i
LE 6,=E'1' 1
DER 6,0 1/i**2
AER 4,6 s=s+1/i**2
AE 2,=E'1' i=i+1
ENDDO , enddo i
LA 0,4 format F13.4
LER 0,4 s
BAL 14,FORMATF call formatf
MVC PG(13),0(1) retrieve result
XPRNT PG,80 print buffer
BR 10 exit
COPY FORMATF formatf code
PG DC CL80' ' buffer
END SUMSER |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Rust | Rust | // 20210210 Rust programming solution
extern crate chrono;
use chrono::prelude::*;
fn main() {
let utc: DateTime<Utc> = Utc::now();
println!("{}", utc.format("%d/%m/%Y %T"));
}
|
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Scala | Scala | println(new java.util.Date) |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #11l | 11l | F sum35(limit)
V sum = 0
L(i) 1 .< limit
I i % 3 == 0 | i % 5 == 0
sum += i
R sum
print(sum35(1000)) |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #360_Assembly | 360 Assembly | * Sum digits of an integer 08/07/2016
SUMDIGIN CSECT
USING SUMDIGIN,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
LA R11,NUMBERS @numbers
LA R8,1 k=1
LOOPK CH R8,=H'4' do k=1 to hbound(numbers)
BH ELOOPK "
SR R10,R10 sum=0
LA R7,1 j=1
LOOPJ CH R7,=H'8' do j=1 to length(number)
BH ELOOPJ "
LR R4,R11 @number
BCTR R4,0 -1
AR R4,R7 +j
MVC D,0(R4) d=substr(number,j,1)
SR R9,R9 ii=0
SR R6,R6 i=0
LOOPI CH R6,=H'15' do i=0 to 15
BH ELOOPI "
LA R4,DIGITS @digits
AR R4,R6 i
MVC C,0(R4) c=substr(digits,i+1,1)
CLC D,C if d=c
BNE NOTEQ then
LR R9,R6 ii=i
B ELOOPI leave i
NOTEQ LA R6,1(R6) i=i+1
B LOOPI end do i
ELOOPI AR R10,R9 sum=sum+ii
LA R7,1(R7) j=j+1
B LOOPJ end do j
ELOOPJ MVC PG(8),0(R11) number
XDECO R10,XDEC edit sum
MVC PG+8(8),XDEC+4 output sum
XPRNT PG,L'PG print buffer
LA R11,8(R11) @number=@number+8
LA R8,1(R8) k=k+1
B LOOPK end do k
ELOOPK L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
DIGITS DC CL16'0123456789ABCDEF'
NUMBERS DC CL8'1',CL8'1234',CL8'FE',CL8'F0E'
C DS CL1
D DS CL1
PG DC CL16' ' buffer
XDEC DS CL12 temp
YREGS
END SUMDIGIN |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #0815 | 0815 |
{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7:
~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff:
~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~%
|
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #XPL0 | XPL0 | int Mat, X, Y, Sum;
[Mat:= [[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]];
Sum:= 0;
for Y:= 0 to 4 do
for X:= 0 to 4 do
if Y > X then
Sum:= Sum + Mat(Y,X);
IntOut(0, Sum);
] |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Lua | Lua | function print_count(t)
local cnt = 0
for k,v in pairs(t) do
cnt = cnt + 1
end
print(cnt .. ' candidates')
end
function make_pair(a,b)
local t = {}
table.insert(t, a) -- 1
table.insert(t, b) -- 2
return t
end
function setup()
local candidates = {}
for x = 2, 98 do
for y = x + 1, 98 do
if x + y <= 100 then
local p = make_pair(x, y)
table.insert(candidates, p)
end
end
end
return candidates
end
function remove_by_sum(candidates, sum)
for k,v in pairs(candidates) do
local s = v[1] + v[2]
if s == sum then
table.remove(candidates, k)
end
end
end
function remove_by_prod(candidates, prod)
for k,v in pairs(candidates) do
local p = v[1] * v[2]
if p == prod then
table.remove(candidates, k)
end
end
end
function statement1(candidates)
local unique = {}
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] ~= nil then
unique[prod] = unique[prod] + 1
else
unique[prod] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] == 1 then
local sum = v[1] + v[2]
remove_by_sum(candidates, sum)
done = false
break
end
end
until done
end
function statement2(candidates)
local unique = {}
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] ~= nil then
unique[prod] = unique[prod] + 1
else
unique[prod] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] > 1 then
remove_by_prod(candidates, prod)
done = false
break
end
end
until done
end
function statement3(candidates)
local unique = {}
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
if unique[sum] ~= nil then
unique[sum] = unique[sum] + 1
else
unique[sum] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
if unique[sum] > 1 then
remove_by_sum(candidates, sum)
done = false
break
end
end
until done
end
function main()
local candidates = setup()
print_count(candidates)
statement1(candidates)
print_count(candidates)
statement2(candidates)
print_count(candidates)
statement3(candidates)
print_count(candidates)
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
local prod = v[1] * v[2]
print("a=" .. v[1] .. ", b=" .. v[2] .. "; S=" .. sum .. ", P=" .. prod)
end
end
main() |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: celsius (in float: kelvin) is
return kelvin - 273.15;
const func float: fahrenheit (in float: kelvin) is
return kelvin * 1.8 - 459.67;
const func float: rankine (in float: kelvin) is
return kelvin * 1.8;
const proc: main is func
local
var float: kelvin is 0.0;
begin
write("Enter temperature in kelvin: ");
readln(kelvin);
writeln("K: " <& kelvin digits 2 lpad 7);
writeln("C: " <& celsius(kelvin) digits 2 lpad 7);
writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7);
writeln("R: " <& rankine(kelvin) digits 2 lpad 7);
end func; |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Sidef | Sidef | var scale = Hash(
Celcius => Hash.new(factor => 1 , offset => -273.15 ),
Rankine => Hash.new(factor => 1.8, offset => 0 ),
Fahrenheit => Hash.new(factor => 1.8, offset => -459.67 ),
);
var kelvin = Sys.readln("Enter a temperature in Kelvin: ").to_n;
kelvin >= 0 || die "No such temperature!";
scale.keys.sort.each { |key|
printf("%12s:%8.2f\n", key, kelvin*scale{key}{:factor} + scale{key}{:offset});
} |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #11l | 11l | F suffize(numstr, digits = -1, base = 10)
V suffixes = [‘’, ‘K’, ‘M’, ‘G’, ‘T’, ‘P’, ‘E’, ‘Z’, ‘Y’, ‘X’, ‘W’, ‘V’, ‘U’, ‘googol’]
V exponent_distance = I base == 2 {10} E 3
V num_sign = I numstr[0] C ‘+-’ {numstr[0]} E ‘’
V num = abs(Float(numstr.replace(‘,’, ‘’)))
Int suffix_index
I base == 10 & num >= 1e100
suffix_index = 13
num /= 1e100
E I num > 1
V magnitude = floor(log(num, base))
suffix_index = min(Int(floor(magnitude / exponent_distance)), 12)
num /= Float(base) ^ (exponent_distance * suffix_index)
E
suffix_index = 0
String num_str
I digits != -1
num_str = format_float(num, digits)
E
num_str = format_float(num, 3).rtrim(‘0’).rtrim(‘.’)
R num_sign‘’num_str‘’suffixes[suffix_index]‘’(I base == 2 {‘i’} E ‘’)
F p(num, digits = -1, base = 10)
print(num, end' ‘ ’)
I digits != -1
print(digits, end' ‘ ’)
I base != 10
print(‘base = ’base, end' ‘ ’)
print(‘: ’suffize(num, digits, base))
p(‘87,654,321’)
p(‘-998,877,665,544,332,211,000’, 3)
p(‘+112,233’, 0)
p(‘16,777,216’, 1)
p(‘456,789,100,000,000’, 2)
p(‘456,789,100,000,000’, 5, 2)
p(‘456,789,100,000.000e+00’, 0, 10)
p(‘+16777216’, -1, 2)
p(‘1.2e101’) |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #ACL2 | ACL2 | (defun sum-x^-2 (max-x)
(if (zp max-x)
0
(+ (/ (* max-x max-x))
(sum-x^-2 (1- max-x))))) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Scheme | Scheme | (use posix)
(seconds->string (current-seconds)) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
begin
writeln(time(NOW));
end func; |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #8th | 8th |
needs combinators/bi
: mul3or5? ( 3 mod 0 = ) ( 5 mod 0 = ) bi or ;
"The sum of the multiples of 3 or 5 below 1000 is " .
0 ( mul3or5? if I n:+ then ) 1 999 loop . cr
with: n
: >triangular SED: n -- n
dup 1+ * 2 / ;
: sumdiv SED: n n -- n
dup >r /mod nip >triangular r> * ;
: sumdiv_3,5 SED: n -- n
( swap sumdiv ) curry [3, 5, 15] swap a:map a:open neg + + ;
;with
"For 10^20 - 1, the sum is " . 10 20 ^ 1- sumdiv_3,5 . cr
bye
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Sum of digits of AX in base BX.
;;; Returns: AX = result
;;; CX, DX destroyed.
digsum: xor cx,cx ; Result
.loop: xor dx,dx ; Divide AX by BX
div bx ; Quotient in AX, modulus in DX
add cx,dx ; Add digit to sum
test ax,ax ; Is the quotient now zero?
jnz .loop ; If not, keep going
mov ax,cx ; Otherwise, return
ret
;;; Print the value of AX in decimal using DOS.
;;; (Note the similarity.)
pr_ax: mov bx,num ; Number buffer pointer
mov cx,10 ; Divisor
.loop: xor dx,dx ; Get digit
div cx
add dl,'0' ; Make ASCII digit
dec bx ; Store in buffer
mov [bx],dl
test ax,ax ; More digits?
jnz .loop ; If so, keep going
mov dx,bx ; Begin of number in DX
mov ah,9 ; MS-DOS syscall 9 prints $-terminated string
int 21h
ret
;;; Run the function on the given examples
demo: mov si,tests ; Pointer to example array
.loop: lodsw ; Get base
test ax,ax ; If 0, we're done
jz .done
xchg bx,ax
lodsw ; Get number
call digsum ; Calculate sum of digits
call pr_ax ; Print sum of digits
jmp .loop ; Get next pair
.done: ret
section .data
db '*****' ; Placeholder for numeric output
num: db 13,10,'$'
tests: dw 10, 1 ; Examples
dw 10, 1234
dw 16, 0FEh
dw 16, 0F0Eh
dw 0 ; End marker |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #11l | 11l | print(sum([1, 2, 3, 4, 5].map(x -> x^2))) |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #360_Assembly | 360 Assembly | * Sum of squares 27/08/2015
SUMOFSQR CSECT
USING SUMOFSQR,R12
LR R12,R15
LA R7,A a(1)
SR R6,R6 sum=0
LA R3,1 i=1
LOOPI CH R3,N do i=1 to hbound(a)
BH ELOOPI
L R5,0(R7) a(i)
M R4,0(R7) a(i)*a(i)
AR R6,R5 sum=sum+a(i)**2
LA R7,4(R7) next a
LA R3,1(R3) i=i+1
B LOOPI end i
ELOOPI XDECO R6,PG+23 edit sum
XPRNT PG,80
XR R15,R15
BR R14
A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
PG DC CL80'The sum of squares is: '
N DC AL2((PG-A)/4)
YREGS
END SUMOFSQR |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Nim | Nim | import sequtils, sets, sugar, tables
var
xycandidates = toSeq(2..98)
sums = collect(initHashSet, for s in 5..100: {s}) # Set of possible sums.
factors: Table[int, seq[(int, int)]] # Mapping product -> list of factors.
# Build the factor mapping.
for i in 0..<xycandidates.high:
let x = xycandidates[i]
for j in (i + 1)..xycandidates.high:
let y = xycandidates[j]
factors.mgetOrPut(x * y, @[]).add (x, y)
iterator terms(n: int): (int, int) =
## Yield the possible terms (x, y) of a given sum.
for x in 2..(n - 1) div 2:
yield (x, n - x)
# S says "P does not know X and Y."
# => For every decomposition of S, there is no product with a single decomposition.
for s in toSeq(sums):
for (x, y) in s.terms():
let p = x * y
if factors[p].len == 1:
sums.excl s
break
# P says "Now I know X and Y."
# => P has only one decomposition with sum in "sums".
for p in toSeq(factors.keys):
var sums = collect(initHashSet):
for (x, y) in factors[p]:
if x + y in sums: {x + y}
if card(sums) > 1: factors.del p
# S says "Now I also know X and Y."
# => S has only one decomposition with product in "factors".
for s in toSeq(sums):
var prods = collect(initHashSet):
for (x, y) in s.terms():
if x * y in factors: {x * y}
if card(prods) > 1: sums.excl s
# Now, combine the sums and the products.
for s in sums:
for (x, y) in s.terms:
if x * y in factors: echo (x, y) |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Swift | Swift |
func KtoC(kelvin : Double)->Double{
return kelvin-273.15
}
func KtoF(kelvin : Double)->Double{
return ((kelvin-273.15)*1.8)+32
}
func KtoR(kelvin : Double)->Double{
return ((kelvin-273.15)*1.8)+491.67
}
var k// input
print("\(k) Kelvin")
var c=KtoC(kelvin : k)
print("\(c) Celsius")
var f=KtoF(kelvin : k)
print("\(f) Fahrenheit")
var r=KtoR(kelvin : k)
print("\(r) Rankine")
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Tcl | Tcl | proc temps {k} {
set c [expr {$k - 273.15}]
set r [expr {$k / 5.0 * 9.0}]
set f [expr {$r - 459.67}]
list $k $c $f $r
} |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Go | Go | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
var suffixes = " KMGTPEZYXWVU"
var ggl = googol()
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func suffize(arg string) {
fields := strings.Fields(arg)
a := fields[0]
if a == "" {
a = "0"
}
var places, base int
var frac, radix string
switch len(fields) {
case 1:
places = -1
base = 10
case 2:
places, _ = strconv.Atoi(fields[1])
base = 10
frac = strconv.Itoa(places)
case 3:
if fields[1] == "," {
places = 0
frac = ","
} else {
places, _ = strconv.Atoi(fields[1])
frac = strconv.Itoa(places)
}
base, _ = strconv.Atoi(fields[2])
if base != 2 && base != 10 {
base = 10
}
radix = strconv.Itoa(base)
}
a = strings.Replace(a, ",", "", -1) // get rid of any commas
sign := ""
if a[0] == '+' || a[0] == '-' {
sign = string(a[0])
a = a[1:] // remove any sign after storing it
}
b := new(big.Float).SetPrec(500)
d := new(big.Float).SetPrec(500)
b.SetString(a)
g := false
if b.Cmp(ggl) >= 0 {
g = true
}
if !g && base == 2 {
d.SetUint64(1024)
} else if !g && base == 10 {
d.SetUint64(1000)
} else {
d.Set(ggl)
}
c := 0
for b.Cmp(d) >= 0 && c < 12 { // allow b >= 1K if c would otherwise exceed 12
b.Quo(b, d)
c++
}
var suffix string
if !g {
suffix = string(suffixes[c])
} else {
suffix = "googol"
}
if base == 2 {
suffix += "i"
}
fmt.Println(" input number =", fields[0])
fmt.Println(" fraction digs =", frac)
fmt.Println("specified radix =", radix)
fmt.Print(" new number = ")
if places >= 0 {
fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
} else {
fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
}
fmt.Println()
}
func main() {
tests := []string{
"87,654,321",
"-998,877,665,544,332,211,000 3",
"+112,233 0",
"16,777,216 1",
"456,789,100,000,000",
"456,789,100,000,000 2 10",
"456,789,100,000,000 5 2",
"456,789,100,000.000e+00 0 10",
"+16777216 , 2",
"1.2e101",
"446,835,273,728 1",
"1e36",
"1e39", // there isn't a big enough suffix for this one but it's less than googol
}
for _, test := range tests {
suffize(test)
}
} |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Calc(CARD n REAL POINTER res)
CARD i,st
BYTE perc
REAL one,a,b
IntToReal(0,res)
IF n=0 THEN RETURN FI
IntToReal(1,one)
st=n/100
FOR i=1 TO n
DO
IF i MOD st=0 THEN
PrintB(perc) Put('%) PutE() Put(28)
perc==+1
FI
IntToReal(i,a)
RealMult(a,a,b)
RealDiv(one,b,a)
RealAdd(res,a,b)
RealAssign(b,res)
OD
RETURN
PROC Main()
REAL POINTER res
CARD n=[1000]
Put(125) PutE() ;clear screen
Calc(n,res)
PrintF("s(%U)=",n)
PrintRE(res)
RETURN |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #SETL | SETL | $ Unix time
print(tod);
$ Human readable time and date
print(date); |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Sidef | Sidef | # textual
say Time.local.ctime; # => Thu Mar 19 15:10:41 2015
# epoch time
say Time.sec; # => 1426770641
# epoch time with fractional seconds
say Time.micro_sec; # => 1426770641.68409 |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #360_Assembly | 360 Assembly | * Sum multiples of 3 and 5
SUM35 CSECT
USING SUM35,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R9,1 n=1
LA R7,7 do j=7 to 1 step -1
LOOPJ MH R9,=H'10' n=n*10
LR R10,R9 n
BCTR R10,0 n-1
ZAP SUM,=PL8'0' sum=0
LA R6,3 i=3
DO WHILE=(CR,R6,LE,R10) do i=3 to n-1
LR R4,R6 i
SRDA R4,32
D R4,=F'3' i/3
LTR R4,R4 if mod(i,3)=0
BZ CVD
LR R4,R6 i
SRDA R4,32
D R4,=F'5' i/5
LTR R4,R4 if mod(i,5)=0
BNZ ITERI
CVD CVD R6,IP ip=p
AP SUM,IP sum=sum+i
ITERI LA R6,1(R6) i++
ENDDO , enddo i
XDECO R9,PG n
MVC PG+15(16),EM16 load mask
ED PG+15(16),SUM packed dec (PL8) to char (CL16)
XPRNT PG,L'PG print
BCT R7,LOOPJ enddo j
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
SUM DS PL8
IP DS PL8
EM16 DC X'40202020202020202020202020202120' mask CL16 15num
PG DC CL80'123456789012 : 1234567890123456'
YREGS
END SUM35 |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Action.21 | Action! | CARD FUNC SumDigits(CARD num,base)
CARD res,a
res=0
WHILE num#0
DO
res==+num MOD base
num=num/base
OD
RETURN(res)
PROC Main()
CARD ARRAY data=[
1 10 1234 10 $FE 16 $F0E 16
$FF 2 0 2 2186 3 2187 3]
BYTE i
CARD num,base,res
FOR i=0 TO 15 STEP 2
DO
num=data(i)
base=data(i+1)
res=SumDigits(num,base)
PrintF("num=%U base=%U sum=%U%E",num,base,res)
OD
RETURN |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #8086_Assembly | 8086 Assembly | ;;; Sum of squares
cpu 8086
bits 16
section .text
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Calculate the sum of the squares of the array in SI.
;;; The array should contain 16-bit unsigned integers.
;;; The output will be 32-bit.
;;; Input: (DS:)SI = array, CX = array length
;;; Output: DX:AX = sum of squares
;;; Registers used: AX,BX,CX,DX,SI,DI
sumsqr: xor bx,bx ; Keep accumulator in BX:DI.
xor di,di ; (So zero it out first)
and cx,cx ; Counter register 0? "Program should work
jz .done ; on a zero-length vector"
.loop: mov ax,[si] ; Grab value from array
mul ax ; Calculate square of value (into DX:AX)
add di,ax ; Add low 16 bits to accumulator
adc bx,dx ; Add high 16 bits, plus carry
inc si ; Point to next value
inc si
loop .loop ; Next value in array
.done: mov ax,di ; Return the value in DX:AX as is tradition
mov dx,bx
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Demo: use the subroutine to calculate the sum of squares
;;; in the included array, and show the result
demo: mov si,array
mov cx,arrlen
call sumsqr
;;; Print the return value in DX:AX as a decimal number
;;; (Note: max supported value 655359 - this is a limitation
;;; of this rudimentary output code, not of the sum of squares
;;; routine.)
mov di,outstr_end
mov cx,10
.decloop: div cx
dec di
add dl,'0'
mov [di],dl
xor dx,dx
and ax,ax
jnz .decloop
mov dx,di
mov ah,9
int 21h
ret
section .data
outstr: db '######' ; Placeholder for decimal output
outstr_end: db '$'
array: dw 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
arrlen: equ ($-array)/2 ; length is in words |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #ooRexx | ooRexx | all =.set~new
Call time 'R'
cnt.=0
do a=2 to 100
do b=a+1 to 100-2
p=a b
if a+b>100 then leave b
all~put(p)
prd=a*b
cnt.prd+=1
End
End
Say "There are" all~items "pairs where X+Y <=" max "(and X<Y)"
spairs=.set~new
Do Until all~items=0
do p over all
d=decompositions(p)
If take Then
spairs=spairs~union(d)
dif=all~difference(d)
Leave
End
all=dif
end
Say "S starts with" spairs~items "possible pairs."
sProducts.=0
Do p over sPairs
Parse Var p x y
prod=x*y
sProducts.prod+=1
End
pPairs=.set~new
Do p over sPairs
Parse Var p xb yb
prod=xb*yb
If sProducts.prod=1 Then
pPairs~put(p)
End
Say "P then has" pPairs~items "possible pairs."
Sums.=0
Do p over pPairs
Parse Var p xc yc
sum=xc+yc
Sums.sum+=1
End
final=.set~new
Do p over pPairs
Parse Var p x y
sum=x+y
If Sums.sum=1 Then
final~put(p)
End
si=0
Do p Over final
si+=1
sol.si=p
End
Select
When final~items=1 Then Say "Answer:" sol.1
When final~items=0 Then Say "No possible answer."
Otherwise Do; Say final~items "possible answers:"
Do p over final
Say p
End
End
End
Say "Elapsed time:" time('E') "seconds"
Exit
decompositions: Procedure Expose cnt. take spairs
epairs=.set~new
Use Arg p
Parse Var p aa bb
s=aa+bb
take=1
Do xa=2 To s/2
ya=s-xa
pp=xa ya
epairs~put(pp)
prod=xa*ya
If cnt.prod=1 Then
take=0
End
return epairs |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #UNIX_Shell | UNIX Shell | #!/bin/ksh
# Temperature conversion
typeset tt[1]=0.00 tt[2]=273.15 tt[3]=373.15
for i in {1..3}
do
((t=tt[i]))
echo $i
echo "Kelvin: $t K"
echo "Celsius: $((t-273.15)) C"
echo "Fahrenheit: $((t*18/10-459.67)) F"
echo "Rankine: $((t*18/10)) R"
done |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Julia | Julia | using Printf
const suf = Dict{BigInt, String}(BigInt(1) => "", BigInt(10)^100 => "googol",
BigInt(10)^3 => "K", BigInt(10)^6 => "M", BigInt(10)^9 => "G", BigInt(10)^12 => "T",
BigInt(10)^15 => "P", BigInt(10)^18 => "E", BigInt(10)^21 => "Z", BigInt(10)^24 => "Y",
BigInt(10)^27 => "X", BigInt(10)^30 => "W", BigInt(10)^33 => "V", BigInt(10)^36 => "U")
const binsuf = Dict{BigInt, String}(BigInt(1) => "", BigInt(10)^100 => "googol",
BigInt(2)^10 => "Ki", BigInt(2)^20 => "Mi", BigInt(2)^30 => "Gi", BigInt(2)^40 => "Ti",
BigInt(2)^50 => "Pi", BigInt(2)^60 => "Ei", BigInt(2)^70 => "Zi", BigInt(2)^80 => "Yi",
BigInt(2)^90 => "Xi", BigInt(2)^100 => "Wi", BigInt(2)^110 => "Vi", BigInt(2)^120 => "Ui")
const googol = BigInt(10)^100
function choosedivisor(n, base10=true)
if n > 10 * googol
return googol
end
s = base10 ? sort(collect(keys(suf))) : sort(collect(keys(binsuf)))
(i = findfirst(x -> x > 0.001 * n, s)) == nothing ? s[end] : s[i]
end
pretty(x) = (floor(x) == x) ? string(BigInt(x)) : replace(@sprintf("%f", x), r"0+$" => "")
function suffize(val::String, rounddigits=-1, suffixbase=10)
if val[1] == '-'
isneg = true
val = val[2:end]
else
isneg = false
if val[1] == '+'
val = val[2:end]
end
end
val = replace(val, r"," => "")
nval = (b = tryparse(BigInt, val)) == nothing ? parse(BigFloat, val) : b
b = choosedivisor(nval, suffixbase != 2)
mantissa = nval / b
if rounddigits >= 0
mantissa = round(mantissa, digits=rounddigits)
end
(isneg ? "-" : "") * pretty(mantissa) * (suffixbase == 10 ? suf[b] : binsuf[b])
end
suffize(val::Number, rounddigits=-1, suffixbase=10) = suffize(string(val), rounddigits, suffixbase)
testnumbers = [
["87,654,321"],
["-998,877,665,544,332,211,000", 3],
["+112,233", 0],
["16,777,216", 1],
["456,789,100,000,000"],
["456,789,100,000,000", 2, 10],
["456,789,100,000,000", 5, 2],
["456,789,100,000.000e+00", 0],
["+16777216", 0, 2],
["1.2e101"]]
for l in testnumbers
n = length(l)
s = (n == 1) ? suffize(l[1]) : (n == 2) ? suffize(l[1], l[2]) : suffize(l[1], l[2], l[3])
println(lpad(l[1], 30), (n > 1) ? lpad(l[2], 3) : " ",
(n > 2) ? lpad(l[3], 3) : " ", " : ", s)
end
|
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Nim | Nim | import math, strutils
const
Suffixes = ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "X", "W", "V", "U", "googol"]
None = -1
proc suffize(num: string; digits = None; base = 10): string =
let exponentDist = if base == 2: 10 else: 3
let num = num.strip().replace(",", "")
let numSign = if num[0] in {'+', '-'}: $num[0] else: ""
var n = abs(num.parseFloat())
var suffixIndex: int
if base == 10 and n >= 1e100:
suffixIndex = 13
n /= 1e100
elif n > 1:
let magnitude = log(n, base.toFloat).int
suffixIndex = min(magnitude div exponentDist, 12)
n /= float(base ^ (exponentDist * suffixIndex))
else:
suffixIndex = 0
let numStr = if digits > 0:
n.formatFloat(ffDecimal, precision = digits)
elif digits == 0:
# Can’t use "formatFloat" with precision = 0 as it keeps the decimal point.
# So convert to nearest int and format this value.
$(n.toInt)
else:
n.formatFloat(ffDecimal, precision = 3).strip(chars = {'0'}).strip(chars = {'.'})
result = numSign & numStr & Suffixes[suffixIndex] & (if base == 2: "i" else: "")
when isMainModule:
echo "[87,654,321]: ",
suffize("87,654,321")
echo "[-998,877,665,544,332,211,000 / digits = 3]: ",
suffize("-998,877,665,544,332,211,000", 3)
echo "[+112,233 / digits = 0]: ",
suffize("+112,233", 0)
echo "[16,777,216 / digits = 1]: ",
suffize("16,777,216", 1)
echo "[456,789,100,000,000 / digits = 2]: ",
suffize("456,789,100,000,000", 2)
echo "[456,789,100,000,000 / digits = 2 / base = 10]: ",
suffize("456,789,100,000,000", 2, 10)
echo "[456,789,100,000,000 / digits = 5 / base = 2]: ",
suffize("456,789,100,000,000", digits = 5, base = 2)
echo "[456,789,100,000.000e+000 / digits = 0 / base = 10]: ",
suffize("456,789,100,000.000e+000", digits = 0, base = 10)
echo "[+16777216 / base = 2]: ",
suffize("+16777216", base = 2)
echo "[1.2e101]: ",
suffize("1.2e101") |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Perl | Perl | use List::Util qw(min max first);
sub sufficate {
my($val, $type, $round) = @_;
$type //= 'M';
if ($type =~ /^\d$/) { $round = $type; $type = 'M' }
my $s = '';
if (substr($val,0,1) eq '-') { $s = '-'; $val = substr $val, 1 }
$val =~ s/,//g;
if ($val =~ m/e/i) {
my ($m,$e) = split /[eE]/, $val;
$val = ($e < 0) ? $m * 10**-$e : $m * 10**$e;
}
my %s;
if ($type eq 'M') {
my @x = qw<K M G T P E Z Y X W V U>;
$s{$x[$_]} = 1000 * 10 ** ($_*3) for 0..$#x
} elsif ($type eq 'B') {
my @x = qw<Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui>;
$s{$x[$_]} = 2 ** (10*($_+1)) for 0..$#x
} elsif ($type eq 'G') {
$s{'googol'} = 10**100
} else {
return 'What we have here is a failure to communicate...'
}
my $k;
if (abs($val) < (my $m = min values %s)) {
$k = first { $s{$_} == $m } keys %s;
} elsif (abs($val) > (my $x = max values %s)) {
$k = first { $s{$_} == $x } keys %s;
} else {
for my $key (sort { $s{$a} <=> $s{$b} } keys %s) {
next unless abs($val)/$s{$key} < min values %s;
$k = $key;
last;
}
}
my $final = abs($val)/$s{$k};
$final = round($final,$round) if defined $round;
$s . $final . $k
}
sub round {
my($num,$dig) = @_;
if ($dig == 0) { int 0.5 + $num }
elsif ($dig < 0) { 10**-$dig * int(0.5 + $num/10**-$dig) }
else { my $fmt = '%.' . $dig . 'f'; sprintf $fmt, $num }
}
sub comma {
my($i) = @_;
my ($whole, $frac) = split /\./, $i;
(my $s = reverse $whole) =~ s/(.{3})/$1,/g;
($s = reverse $s) =~ s/^,//;
$frac = $frac.defined ? ".$frac" : '';
return "$s$frac";
}
my @tests = (
'87,654,321',
'-998,877,665,544,332,211,000 3',
'+112,233 0',
'16,777,216 1',
'456,789,100,000,000',
'456,789,100,000,000 M 2',
'456,789,100,000,000 B 5',
'456,789,100,000.000e+00 M 0',
'+16777216 B',
'1.2e101 G',
'347,344 M -2', # round to -2 past the decimal
'1122334455 Q', # bad unit type example
);
printf "%33s : %s\n", $_, sufficate(split ' ', $_) for @tests; |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #ActionScript | ActionScript | function partialSum(n:uint):Number
{
var sum:Number = 0;
for(var i:uint = 1; i <= n; i++)
sum += 1/(i*i);
return sum;
}
trace(partialSum(1000)); |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Smalltalk | Smalltalk | DateTime now displayNl. |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #SNOBOL4 | SNOBOL4 | OUTPUT = DATE()
END |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Main()
REAL sum,r
INT i
Put(125) PutE() ;clear the screen
IntToReal(0,sum)
FOR i=0 TO 999
DO
IF i MOD 3=0 OR i MOD 5=0 THEN
IntToReal(i,r)
RealAdd(sum,r,sum)
FI
OD
PrintRE(sum)
RETURN |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Ada | Ada | with Ada.Integer_Text_IO;
procedure Sum_Digits is
-- sums the digits of an integer (in whatever base)
-- outputs the sum (in base 10)
function Sum_Of_Digits(N: Natural; Base: Natural := 10) return Natural is
Sum: Natural := 0;
Val: Natural := N;
begin
while Val > 0 loop
Sum := Sum + (Val mod Base);
Val := Val / Base;
end loop;
return Sum;
end Sum_Of_Digits;
use Ada.Integer_Text_IO;
begin -- main procedure Sum_Digits
Put(Sum_OF_Digits(1)); -- 1
Put(Sum_OF_Digits(12345)); -- 15
Put(Sum_OF_Digits(123045)); -- 15
Put(Sum_OF_Digits(123045, 50)); -- 104
Put(Sum_OF_Digits(16#fe#, 10)); -- 11
Put(Sum_OF_Digits(16#fe#, 16)); -- 29
Put(Sum_OF_Digits(16#f0e#, 16)); -- 29
end Sum_Digits; |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #ACL2 | ACL2 | (defun sum-of-squares (xs)
(if (endp xs)
0
(+ (* (first xs) (first xs))
(sum-of-squares (rest xs))))) |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Perl | Perl | use List::Util qw(none);
sub grep_unique {
my($by, @list) = @_;
my @seen;
for (@list) {
my $x = &$by(@$_);
$seen[$x]= defined $seen[$x] ? 0 : join ' ', @$_;
}
grep { $_ } @seen;
}
sub sums {
my($n) = @_;
my @sums;
push @sums, [$_, $n - $_] for 2 .. int $n/2;
@sums;
}
sub sum { $_[0] + $_[1] }
sub product { $_[0] * $_[1] }
for $i (2..97) {
push @all_pairs, map { [$i, $_] } $i + 1..98
}
# Fact 1:
%p_unique = map { $_ => 1 } grep_unique(\&product, @all_pairs);
for my $p (@all_pairs) {
push @s_pairs, [@$p] if none { $p_unique{join ' ', @$_} } sums sum @$p;
}
# Fact 2:
@p_pairs = map { [split ' ', $_] } grep_unique(\&product, @s_pairs);
# Fact 3:
@final_pair = grep_unique(\&sum, @p_pairs);
printf "X = %d, Y = %d\n", split ' ', $final_pair[0]; |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Ursa | Ursa | decl double k
while true
out "Temp. in Kelvin? " console
set k (in double console)
out "K\t" k endl "C\t" (- k 273.15) endl console
out "F\t" (- (* k 1.8) 459.67) endl "R\t" (* k 1.8) endl endl console
end while |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #VBA | VBA |
Option Explicit
Sub Main_Conv_Temp()
Dim K As Single, Result As Single
K = 21
Debug.Print "Input in Kelvin : " & Format(K, "0.00")
Debug.Print "Output in Celsius : " & IIf(ConvTemp(Result, K, "C"), Format(Result, "0.00"), False)
Debug.Print "Output in Fahrenheit : " & IIf(ConvTemp(Result, K, "F"), Format(Result, "0.00"), False)
Debug.Print "Output in Rankine : " & IIf(ConvTemp(Result, K, "R"), Format(Result, "0.00"), False)
Debug.Print "Output error : " & IIf(ConvTemp(Result, K, "T"), Format(Result, "0.00"), False)
End Sub
Function ConvTemp(sngReturn As Single, Kelv As Single, InWhat As String) As Boolean
Dim ratio As Single
ConvTemp = True
ratio = 9 / 5
Select Case UCase(InWhat)
Case "C": sngReturn = Kelv - 273.15
Case "F": sngReturn = (Kelv * ratio) - 459.67
Case "R": sngReturn = Kelv * ratio
Case Else: ConvTemp = False
End Select
End Function
|
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Phix | Phix | include builtins/bigatom.e
constant suffixes = "KMGTPEZYXWVU",
anydp = 100 -- the "any dp" value (prevents nearest 1e-100, though)
function suffize(sequence args)
bigatom size = ba_abs(args[1])
integer sgn = iff(ba_compare(args[1],0)<0?-1:+1),
la = length(args),
dp = iff(la>=2?args[2]:anydp), -- decimal places
bd = iff(la>=3?args[3]:10) -- 2 or 10
atom ip = power(10,dp) -- (inverted precision)
if dp<0 then size = ba_round(size,ip) end if
string suffix
if ba_compare(size,1e100)>0 then
size = ba_div(size,1e100)
suffix = "googol"
else
integer factor = iff(bd=2?1024:1000), fdx = 0
while fdx<length(suffixes) do
bigatom rsize = ba_div(size,factor)
if dp<0 then rsize = ba_round(rsize,ip) end if
if ba_compare(rsize,1)<0 then exit end if
size = rsize
fdx += 1
end while
suffix = iff(fdx=0?"":suffixes[fdx]&iff(bd=2?"i":""))
end if
string fmt = iff(dp<0 or dp=anydp?"%0B":sprintf("%%0.%dB",dp))
string res = ba_sprintf(fmt, ba_mul(size,sgn))
res &= suffix
return res
end function
constant test_text = """
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
16777216 , 2
1.2e101
347,344 -2
10
""",
test_cases = split(test_text,'\n',no_empty:=true)
for i=1 to length(test_cases) do
string ti = test_cases[i]
sequence args = split(ti,no_empty:=true)
args[1] = ba_new(substitute(args[1],",",""))
for a=2 to length(args) do
sequence sa = scanf(args[a],"%f")
args[a] = iff(length(sa)=1?sa[1][1]:anydp)
end for
string res = suffize(args)
printf(1,"%30s : %s\n",{ti,res})
end for
|
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Sum_Series is
function F(X : Long_Float) return Long_Float is
begin
return 1.0 / X**2;
end F;
package Lf_Io is new Ada.Text_Io.Float_Io(Long_Float);
use Lf_Io;
Sum : Long_Float := 0.0;
subtype Param_Range is Integer range 1..1000;
begin
for I in Param_Range loop
Sum := Sum + F(Long_Float(I));
end loop;
Put("Sum of F(x) from" & Integer'Image(Param_Range'First) &
" to" & Integer'Image(Param_Range'Last) & " is ");
Put(Item => Sum, Aft => 10, Exp => 0);
New_Line;
end Sum_Series; |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #SPL | SPL | hour,min,sec = #.now()
day,month,year = #.today()
#.output(#.str(hour,"00:"),#.str(min,"00:"),#.str(sec,"00.000"))
#.output(day,".",#.str(month,"00"),".",year) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #SQL_PL | SQL PL |
SELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1;
|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Ada | Ada | with Ada.Text_IO;
procedure Sum_Multiples is
type Natural is range 0 .. 2**63 - 1;
function Sum_3_5 (Limit : in Natural) return Natural is
Sum : Natural := 0;
begin
for N in 1 .. Limit - 1 loop
if N mod 3 = 0 or else N mod 5 = 0 then
Sum := Sum + N;
end if;
end loop;
return Sum;
end Sum_3_5;
begin
Ada.Text_IO.Put_Line ("n=1000: " & Sum_3_5 (1000)'Image);
Ada.Text_IO.Put_Line ("n=5e9 : " & Sum_3_5 (5e9)'Image);
end Sum_Multiples; |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #ALGOL_68 | ALGOL 68 |
# operator to return the sum of the digits of an integer value in the #
# specified base #
PRIO SUMDIGITS = 1;
OP SUMDIGITS = ( INT value, INT base )INT:
IF base < 2
THEN
# invalid base #
print( ( "Base for digit sum must be at least 2", newline ) );
stop
ELSE
# the base is OK #
INT result := 0;
INT rest := ABS value;
WHILE rest /= 0
DO
result PLUSAB ( rest MOD base );
rest OVERAB base
OD;
result
FI; # SUMDIGITS #
# additional operator so we can sum the digits of values expressed in #
# other than base 10, e.g. 16ra is a hex lteral with value 10 #
# (Algol 68 allows bases 2, 4, 8 and 16 for non-base 10 literals) #
# however as such literals are BITS values, not INTs, we need this #
# second operator #
OP SUMDIGITS = ( BITS value, INT base )INT: ABS value SUMDIGITS base;
main:(
# test the SUMDIGITS operator #
print( ( "value\base base digit-sum", newline ) );
print( ( " 1\10 10 ", whole( 1 SUMDIGITS 10, -9 ), newline ) );
print( ( " 1234\10 10 ", whole( 1234 SUMDIGITS 10, -9 ), newline ) );
print( ( " fe\16 16 ", whole( 16rfe SUMDIGITS 16, -9 ), newline ) );
print( ( " f0e\16 16 ", whole( 16rf0e SUMDIGITS 16, -9 ), newline ) );
# of course, we don't have to express the number in the base we sum #
# the digits in... #
print( ( " 73\10 71 ", whole( 73 SUMDIGITS 71, -9 ), newline ) )
)
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Action.21 | Action! | CARD FUNC SumOfSqr(BYTE ARRAY a BYTE count)
BYTE i
CARD res
IF count=0 THEN
RETURN (0)
FI
res=0
FOR i=0 TO count-1
DO
res==+a(i)*a(i)
OD
RETURN (res)
PROC Test(BYTE ARRAY a BYTE count)
BYTE i
CARD res
res=SumOfSqr(a,count)
Print("[")
IF count>0 THEN
FOR i=0 to count-1
DO
PrintB(a(i))
IF i<count-1 THEN
Put(' )
FI
OD
FI
PrintF("]->%U%E%E",res)
RETURN
PROC Main()
BYTE ARRAY a=[1 2 3 4 5]
BYTE ARRAY b=[10 20 30 40 50 60 70 80 90]
BYTE ARRAY c=[11]
Test(a,5)
Test(b,9)
Test(c,1)
Test(c,0)
RETURN |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #ActionScript | ActionScript | function sumOfSquares(vector:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i:uint = 0; i < vector.length; i++)
sum += vector[i]*vector[i];
return sum;
} |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #11l | 11l | V arr = [1, 2, 3, 4]
print(sum(arr))
print(product(arr)) |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Phix | Phix | with javascript_semantics
function satisfies_statement1(integer s)
-- S says: P does not know the two numbers.
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, at least one of a or b is composite
for a=2 to floor(s/2) do
if is_prime(a) and is_prime(s-a) then
return false
end if
end for
return true
end function
function satisfies_statement2(integer p)
-- P says: Now I know the two numbers.
-- Given p, for /all/ pairs (a,b), a*b=p, 2<=a,b<=99, exactly one pair satisfies statement 1
bool winner = false
for i=2 to floor(sqrt(p)) do
if mod(p,i)=0 then
integer j = floor(p/i)
if 2<=j and j<=99 then
if satisfies_statement1(i+j) then
if winner then return false end if
winner = true
end if
end if
end if
end for
return winner
end function
function satisfies_statement3(integer s)
-- S says: Now I know the two numbers.
-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, exactly one pair satisfies statements 1 and 2
integer winner = 0
if satisfies_statement1(s) then
for a=2 to floor(s/2) do
if satisfies_statement2(a*(s-a)) then
if winner then return 0 end if
winner = a
end if
end for
end if
return winner
end function
for s=2 to 100 do
integer a = satisfies_statement3(s)
if a!=0 then
printf(1,"%d (%d+%d)\n",{s,a,s-a})
end if
end for
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #VBScript | VBScript |
WScript.StdOut.Write "Enter the temperature in Kelvin:"
tmp = WScript.StdIn.ReadLine
WScript.StdOut.WriteLine "Kelvin: " & tmp
WScript.StdOut.WriteLine "Fahrenheit: " & fahrenheit(CInt(tmp))
WScript.StdOut.WriteLine "Celsius: " & celsius(CInt(tmp))
WScript.StdOut.WriteLine "Rankine: " & rankine(CInt(tmp))
Function fahrenheit(k)
fahrenheit = (k*1.8)-459.67
End Function
Function celsius(k)
celsius = k-273.15
End Function
Function rankine(k)
rankine = (k-273.15)*1.8+491.67
End Function
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Visual_FoxPro | Visual FoxPro | #DEFINE ABSZC 273.16
#DEFINE ABSZF 459.67
LOCAL k As Double, c As Double, f As Double, r As Double, n As Integer, ;
cf As String
n = SET("Decimals")
cf = SET("Fixed")
SET DECIMALS TO 2
SET FIXED ON
CLEAR
DO WHILE .T.
k = VAL(INPUTBOX("Degrees Kelvin:", "Temperature"))
IF k <= 0
EXIT
ENDIF
? "K:", k
c = k - ABSZC
? "C:", c
f = 1.8*c + 32
? "F:", f
r = f + ABSZF
? "R:", r
?
ENDDO
SET FIXED &cf
SET DECIMALS TO n |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Python | Python |
import math
import os
def suffize(num, digits=None, base=10):
suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']
exponent_distance = 10 if base == 2 else 3
num = num.strip().replace(',', '')
num_sign = num[0] if num[0] in '+-' else ''
num = abs(float(num))
if base == 10 and num >= 1e100:
suffix_index = 13
num /= 1e100
elif num > 1:
magnitude = math.floor(math.log(num, base))
suffix_index = min(math.floor(magnitude / exponent_distance), 12)
num /= base ** (exponent_distance * suffix_index)
else:
suffix_index = 0
if digits is not None:
num_str = f'{num:.{digits}f}'
else:
num_str = f'{num:.3f}'.strip('0').strip('.')
return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')
tests = [('87,654,321',),
('-998,877,665,544,332,211,000', 3),
('+112,233', 0),
('16,777,216', 1),
('456,789,100,000,000', 2),
('456,789,100,000,000', 2, 10),
('456,789,100,000,000', 5, 2),
('456,789,100,000.000e+00', 0, 10),
('+16777216', None, 2),
('1.2e101',)]
for test in tests:
print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
|
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Aime | Aime | real
Invsqr(real n)
{
1 / (n * n);
}
integer
main(void)
{
integer i;
real sum;
sum = 0;
i = 1;
while (i < 1000) {
sum += Invsqr(i);
i += 1;
}
o_real(14, sum);
o_byte('\n');
0;
} |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Standard_ML | Standard ML | print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n") |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Stata | Stata | di c(current_date)
di c(current_time) |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #ALGOL_68 | ALGOL 68 | # returns the sum of the multiples of 3 and 5 below n #
PROC sum of multiples of 3 and 5 below = ( LONG LONG INT n )LONG LONG INT:
BEGIN
# calculate the sum of the multiples of 3 below n #
LONG LONG INT multiples of 3 = ( n - 1 ) OVER 3;
LONG LONG INT multiples of 5 = ( n - 1 ) OVER 5;
LONG LONG INT multiples of 15 = ( n - 1 ) OVER 15;
( # twice the sum of multiples of 3 #
( 3 * multiples of 3 * ( multiples of 3 + 1 ) )
# plus twice the sum of multiples of 5 #
+ ( 5 * multiples of 5 * ( multiples of 5 + 1 ) )
# less twice the sum of multiples of 15 #
- ( 15 * multiples of 15 * ( multiples of 15 + 1 ) )
) OVER 2
END # sum of multiples of 3 and 5 below # ;
print( ( "Sum of multiples of 3 and 5 below 1000: "
, whole( sum of multiples of 3 and 5 below( 1000 ), 0 )
, newline
)
);
print( ( "Sum of multiples of 3 and 5 below 1e20: "
, whole( sum of multiples of 3 and 5 below( 100 000 000 000 000 000 000 ), 0 )
, newline
)
) |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #AppleScript | AppleScript | ----------------- SUM DIGITS OF AN INTEGER -----------------
-- baseDigitSum :: Int -> Int -> Int
on baseDigitSum(base)
script
on |λ|(n)
script go
on |λ|(x)
if 0 < x then
Just({x mod base, x div base})
else
Nothing()
end if
end |λ|
end script
sum(unfoldl(go, n))
end |λ|
end script
end baseDigitSum
--------------------------- TEST ---------------------------
on run
{ap(map(baseDigitSum, {2, 8, 10, 16}), {255}), ¬
ap(map(baseDigitSum, {10}), {1, 1234}), ¬
ap(map(baseDigitSum, {16}), map(readHex, {"0xfe", "0xf0e"}))}
--> {{8, 17, 12, 30}, {1, 10}, {29, 29}}
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
-- Each member of a list of functions applied to
-- each of a list of arguments, deriving a list of new values
-- ap (<*>) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
set lst to {}
repeat with f in fs
tell mReturn(contents of f)
repeat with x in xs
set end of lst to |λ|(contents of x)
end repeat
end tell
end repeat
return lst
end ap
-- elemIndex :: Eq a => a -> [a] -> Maybe Int
on elemIndex(x, xs)
set lng to length of xs
repeat with i from 1 to lng
if x = (item i of xs) then return Just(i - 1)
end repeat
return Nothing()
end elemIndex
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- 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
-- identity :: a -> a
on identity(x)
-- The argument unchanged.
x
end identity
-- 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
-- maybe :: b -> (a -> b) -> Maybe a -> b
on maybe(v, f, mb)
-- Either the default value v (if mb is Nothing),
-- or the application of the function f to the
-- contents of the Just value in mb.
if Nothing of mb then
v
else
tell mReturn(f) to |λ|(Just of mb)
end if
end maybe
-- 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
-- readHex :: String -> Int
on readHex(s)
-- The integer value of the given hexadecimal string.
set ds to "0123456789ABCDEF"
script go
on |λ|(c, a)
set {v, e} to a
set i to maybe(0, my identity, elemIndex(c, ds))
{v + (i * e), 16 * e}
end |λ|
end script
item 1 of foldr(go, {0, 1}, characters of s)
end readHex
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- > unfoldl (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- > [1,2,3,4,5,6,7,8,9,10]
-- unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
on unfoldl(f, v)
set xr to {v, v} -- (value, remainder)
set xs to {}
tell mReturn(f)
repeat -- Function applied to remainder.
set mb to |λ|(item 2 of xr)
if Nothing of mb then
exit repeat
else -- New (value, remainder) tuple,
set xr to Just of mb
-- and value appended to output list.
set xs to ({item 1 of xr} & xs)
end if
end repeat
end tell
return xs
end unfoldl |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Sum_Of_Squares is
type Float_Array is array (Integer range <>) of Float;
function Sum_Of_Squares (X : Float_Array) return Float is
Sum : Float := 0.0;
begin
for I in X'Range loop
Sum := Sum + X (I) ** 2;
end loop;
return Sum;
end Sum_Of_Squares;
begin
Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array
Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));
end Test_Sum_Of_Squares; |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #360_Assembly | 360 Assembly | * Sum and product of an array 20/04/2017
SUMPROD CSECT
USING SUMPROD,R15 base register
SR R3,R3 su=0
LA R5,1 pr=1
LA R6,1 i=1
DO WHILE=(CH,R6,LE,=AL2((PG-A)/4)) do i=1 to hbound(a)
LR R1,R6 i
SLA R1,2 *4
A R3,A-4(R1) su=su+a(i)
M R4,A-4(R1) pr=pr*a(i)
LA R6,1(R6) i++
ENDDO , enddo i
XDECO R3,PG su
XDECO R5,PG+12 pr
XPRNT PG,L'PG print
BR R14 exit
A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
PG DS CL24 buffer
YREGS
END SUMPROD |
http://rosettacode.org/wiki/Sum_and_product_puzzle | Sum and product puzzle | Task[edit]
Solve the "Impossible Puzzle":
X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.
The following conversation occurs:
S says "P does not know X and Y."
P says "Now I know X and Y."
S says "Now I also know X and Y!"
What are X and Y?
Guidance
It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:
Quote
Implied fact
1)
S says "P does not know X and Y."
For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition.
2)
P says "Now I know X and Y."
The number X*Y has only one product decomposition for which fact 1 is true.
3)
S says "Now I also know X and Y."
The number X+Y has only one sum decomposition for which fact 2 is true.
Terminology:
"sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
"product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.
See also
Wikipedia: Sum and Product Puzzle
| #Picat | Picat |
main =>
N = 98,
PD = new_array(N*N), % PD[I] = no. of product decompositions of I
foreach(I in 1..N*N) PD[I] = 0 end,
foreach(X in 2..N-1, Y in X+1..N) PD[X * Y] := PD[X * Y] + 1 end,
% Fact 1: S says "P does not know X and Y.", i.e.
% For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition:
Solutions1 = [[X,Y] : X in 2..N-1, Y in X+1..100-X, foreach(XX in 2..X+Y-3) PD[XX * (X+Y-XX)] > 1 end],
% Fact 2: P says "Now I know X and Y.", i.e.
% The number X*Y has only one product decomposition for which fact 1 is true:
Solutions2 = [[X,Y] : [X,Y] in Solutions1, foreach([XX,YY] in Solutions1, XX * YY = X * Y) XX = X, YY = Y end],
% Fact 3: S says "Now I also know X and Y.", i.e.
% The number X+Y has only one sum decomposition for which fact 2 is true.
Solutions3 = [[X,Y] : [X,Y] in Solutions2, foreach([XX,YY] in Solutions2, XX + YY = X + Y) XX = X, YY = Y end],
println(Solutions3).
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Wren | Wren | import "/fmt" for Fmt
var tempConv = Fn.new { |k|
var c = k - 273.15
var f = c * 1.8 + 32
var r = f + 459.67
System.print("%(Fmt.f(7, k, 2))˚ Kelvin")
System.print("%(Fmt.f(7, c, 2))˚ Celsius")
System.print("%(Fmt.f(7, f, 2))˚ Fahrenheit")
System.print("%(Fmt.f(7, r, 2))˚ Rankine")
System.print()
}
var ks = [0, 21, 100]
for (k in ks) tempConv.call(k) |
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers | Suffixation of decimal numbers | Suffixation: a letter or a group of letters added to the end of a word to change its meaning.
───── or, as used herein ─────
Suffixation: the addition of a metric or "binary" metric suffix to a number, with/without rounding.
Task
Write a function(s) to append (if possible) a metric or a "binary" metric suffix to a
number (displayed in decimal).
The number may be rounded (as per user specification) (via shortening of the number when the number of
digits past the decimal point are to be used).
Task requirements
write a function (or functions) to add (if possible) a suffix to a number
the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
the sign should be preserved (if present)
the number may have commas within the number (the commas need not be preserved)
the number may have a decimal point and/or an exponent as in: -123.7e-01
the suffix that might be appended should be in uppercase; however, the i should be in lowercase
support:
the metric suffixes: K M G T P E Z Y X W V U
the binary metric suffixes: Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui
the (full name) suffix: googol (lowercase) (equal to 1e100) (optional)
a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits
validation of the (supplied/specified) arguments is optional but recommended
display (with identifying text):
the original number (with identifying text)
the number of digits past the decimal point being used (or none, if not specified)
the type of suffix being used (metric or "binary" metric)
the (new) number with the appropriate (if any) suffix
all output here on this page
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
"Binary" suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
For instance, with this pseudo─code
/* 1st arg: the number to be transformed.*/
/* 2nd arg: # digits past the dec. point.*/
/* 3rd arg: the type of suffix to use. */
/* 2 indicates "binary" suffix.*/
/* 10 indicates decimal suffix.*/
a = '456,789,100,000,000' /* "A" has eight trailing zeros. */
say ' aa=' suffize(a) /* Display a suffized number to terminal.*/
/* The "1" below shows one decimal ···*/
/* digit past the decimal point. */
n = suffize(a, 1) /* SUFFIZE is the function name. */
n = suffize(a, 1, 10) /* (identical to the above statement.) */
say ' n=' n /* Display value of N to terminal. */
/* Note the rounding that occurs. */
f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */
say ' f=' f /* Display value of F to terminal. */
/* Display value in "binary" metric. */
bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */
say 'bin=' bin /* Display value of BIN to terminal. */
win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */
say 'win=' win /* Display value of WIN to terminal. */
xvi = ' +16777216 ' /* this used to be a big computer ··· */
big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */
say 'big=' big /* Display value of BIG to terminal. */
would display:
aa= 456.7891T
n= 456.8T
f= 415.4Ti
bin= 415.44727Ti
win= 415Ti
big= 16Mi
Use these test cases
87,654,321
-998,877,665,544,332,211,000 3
+112,233 0
16,777,216 1
456,789,100,000,000 2
456,789,100,000,000 2 10
456,789,100,000,000 5 2
456,789,100,000.000e+00 0 10
+16777216 , 2
1.2e101
(your primary disk free space) 1 ◄■■■■■■■ optional
Use whatever parameterizing your computer language supports, and it's permitted to create as many
separate functions as are needed (if needed) if function arguments aren't allowed to
be omitted or varied.
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
| #Raku | Raku | sub sufficate ($val is copy, $type is copy = 'M', $round is copy = Any) {
if +$type ~~ Int { $round = $type; $type = 'M' }
my $s = '';
if $val.substr(0,1) eq '-' { $s = '-'; $val.=substr(1) }
$val.=subst(',', '', :g);
if $val ~~ m:i/'e'/ {
my ($m,$e) = $val.split(/<[eE]>/);
$val = ($e < 0)
?? $m * FatRat.new(1,10**-$e)
!! $m * 10**$e;
}
my %s = do given $type {
when 'M' { <K M G T P E Z Y X W V U> Z=> (1000, * * 1000 … *) }
when 'B' { <Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui> Z=> (1024, * * 1024 … *) }
when 'G' { googol => 10**100 }
default { return 'What we have here is a failure to communicate...' }
}
my $k = do given $val {
when .abs < (my $m = min %s.values) { %s.first( *.value == $m ).key };
when .abs > (my $x = max %s.values) { %s.first( *.value == $x ).key };
default { %s.sort(*.value).first({$val.abs/%s{$_.key} < min %s.values}).key}
}
$round.defined
?? $s ~ comma(($val.abs/%s{$k}).round(10**-$round)) ~ $k
!! $s ~ comma($val.abs/%s{$k}) ~ $k
}
sub comma ($i is copy) {
my $s = $i < 0 ?? '-' !! '';
my ($whole, $frac) = $i.split('.');
$frac = $frac.defined ?? ".$frac" !! '';
$s ~ $whole.abs.flip.comb(3).join(',').flip ~ $frac
}
## TESTING
my @tests =
'87,654,321',
'-998,877,665,544,332,211,000 3',
'+112,233 0',
'16,777,216 1',
'456,789,100,000,000',
'456,789,100,000,000 M 2',
'456,789,100,000,000 B 5',
'456,789,100,000.000e+00 M 0',
'+16777216 B',
'1.2e101 G',
"{run('df', '/', :out).out.slurp.words[10] * 1024} B 2", # Linux df returns Kilobytes by default
'347,344 M -2', # round to -2 past the decimal
'1122334455 Q', # bad unit type example
;
printf "%33s : %s\n", $_, sufficate(|.words) for @tests; |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #ALGOL_68 | ALGOL 68 | MODE RANGE = STRUCT(INT lwb, upb);
PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:(
LONG REAL sum := LENG 0.0;
FOR i FROM lwb OF range TO upb OF range DO
sum := sum + f(i)
OD;
sum
);
test:(
RANGE range = (1,1000);
PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2;
print(("Sum of f(x) from ", whole(lwb OF range, 0), " to ",whole(upb OF range, 0)," is ", fixed(SHORTEN sum(f,range),-8,5),".", new line))
) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Swift | Swift | import Foundation
var ⌚️ = NSDate()
println(⌚️) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Tcl | Tcl | puts [clock seconds] |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #APL | APL |
Sum ← +/∘⍸1<15∨⍳
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #APL | APL | sd←+/⊥⍣¯1 |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Aime | Aime | real
squaredsum(list l)
{
integer i;
real s;
s = 0;
i = -~l;
while (i) {
s += sq(l[i += 1]);
}
s;
}
integer
main(void)
{
list l;
l = list(0, 1, 2, 3);
o_form("~\n", squaredsum(l));
o_form("~\n", squaredsum(list()));
o_form("~\n", squaredsum(list(.5, -.5, 2)));
0;
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #ALGOL_68 | ALGOL 68 | PROC sum of squares = ([]REAL argv)REAL:(
REAL sum := 0;
FOR i FROM LWB argv TO UPB argv DO
sum +:= argv[i]**2
OD;
sum
);
test:(
printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
) |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #4D | 4D | ARRAY INTEGER($list;0)
For ($i;1;5)
APPEND TO ARRAY($list;$i)
End for
$sum:=0
$product:=1
For ($i;1;Size of array($list))
$sum:=$var+$list{$i}
$product:=$product*$list{$i}
End for
// since 4D v13
$sum:=sum($list)
|
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #ACL2 | ACL2 | (defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
(defun prod (xs)
(if (endp xs)
1
(* (first xs)
(prod (rest xs))))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.