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)
| #NetRexx | NetRexx |
import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date()) |
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]]
| #AutoHotkey | AutoHotkey | matrx :=[[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]]
sumA := sumB := sumD := sumAll := 0
for r, obj in matrx
for c, val in obj
sumAll += val
,sumA += r<c ? val : 0
,sumB += r>c ? val : 0
,sumD += r=c ? val : 0
MsgBox % result := "sum above diagonal = " sumA
. "`nsum below diagonal = " sumB
. "`nsum on diagonal = " sumD
. "`nsum all = " sumAll |
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]]
| #AWK | AWK |
# syntax: GAWK -f SUM_OF_ELEMENTS_BELOW_MAIN_DIAGONAL_OF_MATRIX.AWK
BEGIN {
arr1[++n] = "1,3,7,8,10"
arr1[++n] = "2,4,16,14,4"
arr1[++n] = "3,1,9,18,11"
arr1[++n] = "12,14,17,18,20"
arr1[++n] = "7,1,3,9,5"
for (i=1; i<=n; i++) {
x = split(arr1[i],arr2,",")
if (x != n) {
printf("error: row %d has %d elements; S/B %d\n",i,x,n)
errors++
continue
}
for (j=1; j<i; j++) { # below main diagonal
sum_b += arr2[j]
cnt_b++
}
for (j=i+1; j<=n; j++) { # above main diagonal
sum_a += arr2[j]
cnt_a++
}
for (j=1; j<=i; j++) { # on main diagonal
if (j == i) {
sum_o += arr2[j]
cnt_o++
}
}
}
if (errors > 0) { exit(1) }
printf("%5g Sum of the %d elements below main diagonal\n",sum_b,cnt_b)
printf("%5g Sum of the %d elements above main diagonal\n",sum_a,cnt_a)
printf("%5g Sum of the %d elements on main diagonal\n",sum_o,cnt_o)
printf("%5g Sum of the %d elements in the matrix\n",sum_b+sum_a+sum_o,cnt_b+cnt_a+cnt_o)
exit(0)
}
|
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Racket | Racket |
#lang racket
(define A (set "John" "Bob" "Mary" "Serena"))
(define B (set "Jim" "Mary" "John" "Bob"))
(set-symmetric-difference A B)
(set-subtract A B)
(set-subtract B A)
|
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Raku | Raku | my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;
say A ∖ B; # Set subtraction
say B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations
say A ⊖ B; # Symmetric difference, via dedicated operator |
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
| #PARI.2FGP | PARI/GP | f(x)=[x,x-273.15,1.8*x-459.67,1.8*x] |
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
| #Pascal | Pascal | program TemperatureConvert;
type
TemperatureType = (C, F, K, R);
var
kelvin: real;
function ConvertTemperature(temperature: real; fromType, toType: TemperatureType): real;
var
initial, result: real;
begin
(* We are going to first convert whatever we're given into Celsius.
Then we'll convert that into whatever we're asked to convert into.
Maybe not the most efficient way to do this, but easy to understand
and should make it easier to add any additional temperature units. *)
if fromType <> toType then
begin
case fromType of (* first convert the temperature into Celsius *)
C:
initial := temperature;
F:
initial := (temperature - 32) / 1.8;
K:
initial := temperature - 273.15;
R:
initial := (temperature - 491.67) / 1.8;
end;
case toType of (* now convert from Celsius into whatever degree type was asked for *)
C:
result := initial;
F:
result := (initial * 1.8) + 32;
K:
result := initial + 273.15;
R:
result := (initial * 1.8) + 491.67;
end;
end
else (* no point doing all that math if we're asked to convert from and to the same type *)
result := temperature;
ConvertTemperature := result;
end;
begin
write('Temperature to convert (in kelvins): ');
readln(kelvin);
writeln(kelvin : 3 : 2, ' in kelvins is ');
writeln(' ', ConvertTemperature(kelvin, K, C) : 3 : 2, ' in degrees Celsius.');
writeln(' ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.');
writeln(' ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.');
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)
| #NewLISP | NewLISP | > (date)
"Sun Sep 28 20:17:55 2014" |
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)
| #Nim | Nim | import times
echo getDateStr()
echo getClockStr()
echo getTime()
echo now() # shorthand for "getTime().local" |
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]]
| #BASIC | BASIC | arraybase 1
dim 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}}
ind = diag[?,]
sumDiag = 0
for x = 1 to diag[?,]
for y = 1 to diag[,?]-ind
sumDiag += diag[x, y]
next y
ind -= 1
next x
print "Sum of elements below main diagonal of matrix is "; sumDiag
end |
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]]
| #BQN | BQN | SumBelowDiagonal ← +´∘⥊⊢×(>⌜´)∘(↕¨≢)
matrix ← >⟨⟨ 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⟩⟩
SumBelowDiagonal matrix |
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
| #11l | 11l | F counter(arr)
DefaultDict[Int, Int] d
L(a) arr
d[a]++
R d
F decompose_sum(s)
R (2 .< Int(s / 2 + 1)).map(a -> (a, @s - a))
Set[(Int, Int)] all_pairs_set
L(a) 2..99
L(b) a + 1 .< 100
I a + b < 100
all_pairs_set.add((a, b))
V all_pairs = Array(all_pairs_set)
V product_counts = counter(all_pairs.map((c, d) -> c * d))
V unique_products = Set(all_pairs.filter((a, b) -> :product_counts[a * b] == 1))
V s_pairs = all_pairs.filter((a, b) -> all(decompose_sum(a + b).map((x, y) -> (x, y) !C :unique_products)))
product_counts = counter(s_pairs.map((c, d) -> c * d))
V p_pairs = s_pairs.filter((a, b) -> :product_counts[a * b] == 1)
V sum_counts = counter(p_pairs.map((c, d) -> c + d))
V final_pairs = p_pairs.filter((a, b) -> :sum_counts[a + b] == 1)
print(final_pairs) |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #REBOL | REBOL | a: [John Serena Bob Mary Serena]
b: [Jim Mary John Jim Bob]
difference a b |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #REXX | REXX | /*REXX program finds symmetric difference and symmetric AND (between two lists). */
a= '["John", "Serena", "Bob", "Mary", "Serena"]' /*note the duplicate element: Serena */
b= '["Jim", "Mary", "John", "Jim", "Bob"]' /* " " " " Jim */
a.=0; SD.=0; SA.=0; SD=; SA= /*falsify booleans; zero & nullify vars*/
a.1=a; say '──────────────list A =' a /*assign a list and display it to term.*/
a.2=b; say '──────────────list B =' b /* " " " " " " " " */
/* [↓] parse the two lists. */
do k=1 for 2 /*process both lists (stemmed array). */
a.k=strip( strip(a.k, , "["), ,']') /*strip leading and trailing brackets. */
do j=1 until a.k='' /*parse names [they may have blanks]. */
a.k=strip(a.k, , ',') /*strip all commas (if there are any). */
parse var a.k '"' _ '"' a.k /*obtain the name of the list. */
a.k.j=_ /*store the name of the list. */
a.k._=1 /*make a boolean value. */
end /*j*/
a.k.0=j-1 /*the number of this list (of names). */
end /*k*/
say /* [↓] find the symmetric difference. */
do k=1 for 2; ko=word(2 1, k) /*process both lists; KO=other list. */
do j=1 for a.k.0; _=a.k.j /*process the list names. */
if \a.ko._ & \SD._ then do; SD._=1 /*if not in both, then ··· */
SD=SD '"'_'",' /*add to symmetric difference list. */
end
end /*j*/
end /*k*/
/* [↓] SD ≡ symmetric difference. */
SD= "["strip( strip(SD), 'T', ",")']' /*clean up and add brackets [ ] to it.*/
say 'symmetric difference =' SD /*display the symmetric difference. */
/* [↓] locate the symmetric AND. */
do j=1 for a.1.0; _=a.1.j /*process the A list names. */
if a.1._ & a.2._ & \SA._ then do; SA._=1 /*if it's common to both, then ··· */
SA=SA '"'_'",' /*add to symmetric AND list. */
end
end /*j*/
say /* [↓] SA ≡ symmetric AND. */
SA= "["strip( strip(SA), 'T', ",")']' /*clean up and add brackets [ ] to it.*/
say ' symmetric AND =' SA /*stick a fork in it, we're all done. */ |
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
| #Perl | Perl | my %scale = (
Celcius => { factor => 1 , offset => -273.15 },
Rankine => { factor => 1.8, offset => 0 },
Fahrenheit => { factor => 1.8, offset => -459.67 },
);
print "Enter a temperature in Kelvin: ";
chomp(my $kelvin = <STDIN>);
die "No such temperature!\n" unless $kelvin > 0;
foreach (sort keys %scale) {
printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
} |
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)
| #Objeck | Objeck | function : Time() ~ Nil {
t := Time->New();
IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds());
} |
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)
| #Objective-C | Objective-C | NSLog(@"%@", [NSDate date]); |
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]]
| #C | C |
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,"r");
matrix rosetta;
int i,j;
fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,"%d",&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf("\n");
for(j=0;j<rosetta.cols;j++)
printf("%3d",rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf("Usage : %s <filename>",argV[0]);
matrix data = readMatrix(argV[1]);
printf("\n\nMatrix is : \n\n");
printMatrix(data);
printf("\n\nSum below main diagonal : %d",findSum(data));
return 0;
}
|
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
| #AWK | AWK |
# syntax: GAWK -f SUM_AND_PRODUCT_PUZZLE.AWK
BEGIN {
for (s=2; s<=100; s++) {
if ((a=satisfies_statement3(s)) != 0) {
printf("%d (%d+%d)\n",s,a,s-a)
}
}
exit(0)
}
function satisfies_statement1(s, a) { # S says: P does not know the two numbers.
# Given s, for all pairs (a,b), a+b=s, 2 <= a,b <= 99, true if at least one of a or b is composite
for (a=2; a<=int(s/2); a++) {
if (is_prime(a) && is_prime(s-a)) {
return(0)
}
}
return(1)
}
function satisfies_statement2(p, i,j,winner) { # P says: Now I know the two numbers.
# Given p, for all pairs (a,b), a*b=p, 2 <= a,b <= 99, true if exactly one pair satisfies statement 1
for (i=2; i<=int(sqrt(p)); i++) {
if (p % i == 0) {
j = int(p/i)
if (!(2 <= j && j <= 99)) { # in range
continue
}
if (satisfies_statement1(i+j)) {
if (winner) {
return(0)
}
winner = 1
}
}
}
return(winner)
}
function satisfies_statement3(s, a,b,winner) { # S says: Now I know the two numbers.
# Given s, for all pairs (a,b), a+b=s, 2 <= a,b <= 99, true if exactly one pair satisfies statements 1 and 2
if (!satisfies_statement1(s)) {
return(0)
}
for (a=2; a<=int(s/2); a++) {
b = s - a
if (satisfies_statement2(a*b)) {
if (winner) {
return(0)
}
winner = a
}
}
return(winner)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Ring | Ring |
alist = []
blist = []
alist = ["john", "bob", "mary", "serena"]
blist = ["jim", "mary", "john", "bob"]
alist2 = []
for i = 1 to len(alist)
flag = 0
for j = 1 to len(blist)
if alist[i] = blist[j] flag = 1 ok
next
if (flag = 0) add(alist2, alist[i]) ok
next
blist2 = []
for j = 1 to len(alist)
flag = 0
for i = 1 to len(blist)
if alist[i] = blist[j] flag = 1 ok
next
if (flag = 0) add(blist2, blist[j]) ok
next
see "a xor b :" see nl
see alist2
see blist2 see nl
see "a-b :" see nl
see alist2 see nl
see "b-a :" see nl
see blist2 see nl
|
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Ruby | Ruby | a = ["John", "Serena", "Bob", "Mary", "Serena"]
b = ["Jim", "Mary", "John", "Jim", "Bob"]
# the union minus the intersection:
p sym_diff = (a | b)-(a & b) # => ["Serena", "Jim"] |
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
| #Phix | Phix | atom K = prompt_number("Enter temperature in Kelvin >=0: ",{0,1e307})
printf(1," Kelvin: %5.2f\n Celsius: %5.2f\nFahrenheit: %5.2f\n Rankine: %5.2f\n\n",
{K, K-273.15, K*1.8-459.67, K*1.8})
|
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)
| #OCaml | OCaml | #load "unix.cma";;
open Unix;;
let {tm_sec = sec;
tm_min = min;
tm_hour = hour;
tm_mday = mday;
tm_mon = mon;
tm_year = year;
tm_wday = wday;
tm_yday = yday;
tm_isdst = isdst} = localtime (time ());;
Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hour min sec; |
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]]
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
template<typename T>
T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {
T sum = 0;
for (std::size_t y = 0; y < matrix.size(); y++)
for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)
sum += matrix[y][x];
return sum;
}
int main() {
std::vector<std::vector<int>> matrix = {
{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}
};
std::cout << sum_below_diagonal(matrix) << std::endl;
return 0;
} |
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
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf("no candidates\n");
} else if (c == 1) {
printf("one candidate\n");
} else {
printf("%d candidates\n", c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
// numbers must be greater than 1
for (x = 2; x <= 98; x++) {
// numbers must be unique, and sum no more than 100
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Run_BASIC | Run BASIC |
setA$ = "John,Bob,Mary,Serena"
setB$ = "Jim,Mary,John,Bob"
x$ = b$(setA$,setB$)
print word$(x$,1,",")
c$ = c$ + x$
x$ = b$(setB$,setA$)
print word$(x$,1,",")
print c$;x$
end
function b$(a$,b$)
i = 1
while word$(a$,i,",") <> ""
a1$ = word$(a$,i,",")
j = instr(b$,a1$)
if j <> 0 then b$ = left$(b$,j-1) + mid$(b$,j+len(a1$)+1)
i = i + 1
wend
end function |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Rust | Rust | use std::collections::HashSet;
fn main() {
let a: HashSet<_> = ["John", "Bob", "Mary", "Serena"]
.iter()
.collect();
let b = ["Jim", "Mary", "John", "Bob"]
.iter()
.collect();
let diff = a.symmetric_difference(&b);
println!("{:?}", diff);
}
|
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
| #PHP | PHP |
while (true) {
echo "\nEnter a value in kelvin (q to quit): ";
if ($kelvin = trim(fgets(STDIN))) {
if ($kelvin == 'q') {
echo 'quitting';
break;
}
if (is_numeric($kelvin)) {
$kelvin = floatVal($kelvin);
if ($kelvin >= 0) {
printf(" K %2.2f\n", $kelvin);
printf(" C %2.2f\n", $kelvin - 273.15);
printf(" F %2.2f\n", $kelvin * 1.8 - 459.67);
printf(" R %2.2f\n", $kelvin * 1.8);
} else printf(" %2.2f K is below absolute zero\n", $kelvin);
}
}
} |
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)
| #Oforth | Oforth | System.tick println
#[ #sqrt 1000000 seq map sum println ] bench |
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)
| #Oz | Oz | {Show {OS.time}} %% posix time (seconds since 1970-01-01)
{Show {OS.gmTime}} %% current UTC as a record
{Show {OS.localTime}} %% current local time as record
%% Also interesting: undocumented module OsTime
%% When did posix time reach 1 billion?
{Show {OsTime.gmtime 1000000000}}
{Show {OsTime.localtime 1000000000}} |
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]]
| #Excel | Excel | =LAMBDA(isUpper,
LAMBDA(matrix,
LET(
nCols, COLUMNS(matrix),
nRows, ROWS(matrix),
ixs, SEQUENCE(nRows, nCols, 0, 1),
x, MOD(ixs, nCols),
y, QUOTIENT(ixs, nRows),
IF(nCols=nRows,
LET(
p, LAMBDA(x, y,
IF(isUpper, x > y, x < y)
),
IF(p(x, y),
INDEX(matrix, 1 + y, 1 + x),
0
)
),
"Matrix not square"
)
)
)
) |
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]]
| #F.23 | F# |
// Sum below leading diagnal. Nigel Galloway: July 21st., 2021
let _,n=[[ 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]]|>List.fold(fun(n,g) i->let i,_=i|>List.splitAt n in (n+1,g+(i|>List.sum)))(0,0) in printfn "%d" n
|
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
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
for (auto &p : v) {
auto sum = p.first + p.second;
auto prod = p.first * p.second;
os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod;
}
return os << '\n';
}
void print_count(const std::vector<std::pair<int, int>> &candidates) {
auto c = candidates.size();
if (c == 0) {
std::cout << "no candidates\n";
} else if (c == 1) {
std::cout << "one candidate\n";
} else {
std::cout << c << " candidates\n";
}
}
auto setup() {
std::vector<std::pair<int, int>> candidates;
// numbers must be greater than 1
for (int x = 2; x <= 98; x++) {
// numbers must be unique, and sum no more than 100
for (int y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
candidates.push_back(std::make_pair(x, y));
}
}
}
return candidates;
}
void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[sum](const std::pair<int, int> &pair) {
auto s = pair.first + pair.second;
return s == sum;
}
), candidates.end());
}
void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[prod](const std::pair<int, int> &pair) {
auto p = pair.first * pair.second;
return p == prod;
}
), candidates.end());
}
void statement1(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] == 1) {
auto sum = pair.first + pair.second;
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
void statement2(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] > 1) {
remove_by_prod(candidates, prod);
loop = true;
break;
}
}
} while (loop);
}
void statement3(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto sum = pair.first + pair.second;
uniqueMap[sum]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto sum = pair.first + pair.second;
if (uniqueMap[sum] > 1) {
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
int main() {
auto candidates = setup();
print_count(candidates);
statement1(candidates);
print_count(candidates);
statement2(candidates);
print_count(candidates);
statement3(candidates);
print_count(candidates);
std::cout << candidates;
return 0;
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Scala | Scala | scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena")
s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary)
scala> val s2 = Set("Jim", "Mary", "John", "Jim", "Bob")
s2: scala.collection.immutable.Set[java.lang.String] = Set(Jim, Mary, John, Bob)
scala> (s1 diff s2) union (s2 diff s1)
res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim) |
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
| #PicoLisp | PicoLisp | (scl 2)
(de convertKelvin (Kelvin)
(for X
(quote
(K . prog)
(C (K) (- K 273.15))
(F (K) (- (*/ K 1.8 1.0) 459.67))
(R (K) (*/ K 1.8 1.0)) )
(tab (-3 8)
(car X)
(format ((cdr X) Kelvin) *Scl) ) ) ) |
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
| #PL.2FI | PL/I | *process source attributes xref;
/* PL/I **************************************************************
* 15.08.2013 Walter Pachl translated from NetRexx
* temperatures below 0K are considered invalid
*********************************************************************/
temperature: Proc Options(main);
Dcl sysin record Input;
On Endfile(sysin) Goto eoj;
On Record(sysin);
Dcl 1 dat,
2 t Pic'SSSS9V.99',
2 * char( 1),
2 from char(10),
2 * char( 1),
2 to char(10);
Do Forever;
Read File(sysin) Into(dat);
If tc(t,from,'KELVIN')<0 Then
Put Edit('Input (',t,from,') invalid. Below absolute zero')
(Skip,a,f(8,2),x(1),a,a);
Else
Put edit(t,from,' -> ',tc(t,from,to),to)
(skip,f(8,2),x(1),a(10),a,f(8,2),x(1),a(10));
End;
eoj: Return;
tc: Procedure(T,scaleFrom,scaleTo) Returns(Dec Fixed(8,2));
Dcl t Pic'SSSS9V.99';
Dcl (val) Dec Fixed(8,2);
Dcl (scaleFrom,scaleTo) Char(10);
select(scaleFrom);
when('KELVIN ') do;
select(scaleTo);
when('KELVIN ') val = T;
when('CELSIUS ') val = T - 273.15;
when('FAHRENHEIT') val = T * 9 / 5 - 459.67;
when('RANKINE ') val = T * 9 / 5;
when('DELISLE ') val = (373.15 - T) * 3 / 2;
when('NEWTON ') val = (T - 273.15) * 33 / 100;
when('REAUMUR ') val = (T - 273.15) * 4 / 5;
when('ROEMER ') val = (T - 273.15) * 21 / 40 + 7.5;
otherwise Do;
Put Edit('scaleTo=',scaleTo)(Skip,a,a);
Call err(1);
End;
end;
end;
when('CELSIUS') do;
select(scaleTo);
when('KELVIN ') val = T + 273.15;
when('CELSIUS ') val = T;
when('FAHRENHEIT') val = T * 9 / 5 + 32;
when('RANKINE ') val = (T + 273.15) * 9 / 5;
when('DELISLE ') val = (100 - T) * 3 / 2;
when('NEWTON ') val = T * 33 / 100;
when('REAUMUR ') val = T * 4 / 5;
when('ROEMER ') val = T * 21 / 40 + 7.5;
otherwise Call err(2);
end;
end;
when('FAHRENHEIT') do;
select(scaleTo);
when('KELVIN ') val = (T + 459.67) * 5 / 9;
when('CELSIUS ') val = (T - 32) * 5 / 9;
when('FAHRENHEIT') val = T;
when('RANKINE ') val = T + 459.67;
when('DELISLE ') val = (212 - T) * 5 / 6;
when('NEWTON ') val = (T - 32) * 11 / 60;
when('REAUMUR ') val = (T - 32) * 4 / 9;
when('ROEMER ') val = (T - 32) * 7 / 24 + 7.5;
otherwise Call err(3);
end;
end;
when('RANKINE') do;
select(scaleTo);
when('KELVIN ') val = T * 5 / 9;
when('CELSIUS ') val = (T - 491.67) * 5 / 9;
when('FAHRENHEIT') val = T - 459.67;
when('RANKINE ') val = T;
when('DELISLE ') val = (671.67 - T) * 5 / 6;
when('NEWTON ') val = (T - 491.67) * 11 / 60;
when('REAUMUR ') val = (T - 491.67) * 4 / 9;
when('ROEMER ') val = (T - 491.67) * 7 / 24 + 7.5;
otherwise Call err(4);
end;
end;
when('DELISLE') do;
select(scaleTo);
when('KELVIN ') val = 373.15 - T * 2 / 3;
when('CELSIUS ') val = 100 - T * 2 / 3;
when('FAHRENHEIT') val = 212 - T * 6 / 5;
when('RANKINE ') val = 671.67 - T * 6 / 5;
when('DELISLE ') val = T;
when('NEWTON ') val = 33 - T * 11 / 50;
when('REAUMUR ') val = 80 - T * 8 / 15;
when('ROEMER ') val = 60 - T * 7 / 20;
otherwise Call err(5);
end;
end;
when('NEWTON') do;
select(scaleTo);
when('KELVIN ') val = T * 100 / 33 + 273.15;
when('CELSIUS ') val = T * 100 / 33;
when('FAHRENHEIT') val = T * 60 / 11 + 32;
when('RANKINE ') val = T * 60 / 11 + 491.67;
when('DELISLE ') val = (33 - T) * 50 / 11;
when('NEWTON ') val = T;
when('REAUMUR ') val = T * 80 / 33;
when('ROEMER ') val = T * 35 / 22 + 7.5;
otherwise Call err(6);
end;
end;
when('REAUMUR') do;
select(scaleTo);
when('KELVIN ') val = T * 5 / 4 + 273.15;
when('CELSIUS ') val = T * 5 / 4;
when('FAHRENHEIT') val = T * 9 / 4 + 32;
when('RANKINE ') val = T * 9 / 4 + 491.67;
when('DELISLE ') val = (80 - T) * 15 / 8;
when('NEWTON ') val = T * 33 / 80;
when('REAUMUR ') val = T;
when('ROEMER ') val = T * 21 / 32 + 7.5;
otherwise Call err(7);
end;
end;
when('ROEMER') do;
select(scaleTo);
when('KELVIN ') val = (T - 7.5) * 40 / 21 + 273.15;
when('CELSIUS ') val = (T - 7.5) * 40 / 21;
when('FAHRENHEIT') val = (T - 7.5) * 24 / 7 + 32;
when('RANKINE ') val = (T - 7.5) * 24 / 7 + 491.67;
when('DELISLE ') val = (60 - T) * 20 / 7;
when('NEWTON ') val = (T - 7.5) * 22 / 35;
when('REAUMUR ') val = (T - 7.5) * 32 / 21;
when('ROEMER ') val = T;
otherwise Call err(8);
end;
end;
otherwise Call err(9);
end;
return(val);
err: Proc(e);
Dcl e Dec fixed(1);
Put Edit('error ',e,' invalid input')(Skip,a,f(1),a);
val=0;
End;
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)
| #PARI.2FGP | PARI/GP | system("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)
| #Pascal | Pascal | type
timeStamp = packed record
dateValid: Boolean;
year: integer;
month: 1..12;
day: 1..31;
timeValid: Boolean;
hour: 0..23;
minute: 0..59;
second: 0..59;
end; |
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]]
| #Factor | Factor | USING: kernel math math.matrices prettyprint sequences ;
: sum-below-diagonal ( matrix -- sum )
dup square-matrix? [ "Matrix must be square." throw ] unless
0 swap [ head sum + ] each-index ;
{
{ 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-below-diagonal . |
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]]
| #Go | Go | package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{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 len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("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
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const int maxSum = 100;
var pairs = (
from X in 2.To(maxSum / 2 - 1)
from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
select new { X, Y, S = X + Y, P = X * Y }
).ToHashSet();
Console.WriteLine(pairs.Count);
var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
foreach (var pair in pairs) Console.WriteLine(pair);
}
}
public static class Extensions
{
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i <= end; i++) yield return i;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Scheme | Scheme |
(import (scheme base)
(scheme write))
;; -- given two sets represented as lists, return (A \ B)
(define (a-without-b a b)
(cond ((null? a)
'())
((member (car a) (cdr a)) ; drop head of a if it's a duplicate
(a-without-b (cdr a) b))
((member (car a) b) ; head of a is in b so drop it
(a-without-b (cdr a) b))
(else ; head of a not in b, so keep it
(cons (car a) (a-without-b (cdr a) b)))))
;; -- given two sets represented as lists, return symmetric difference
(define (symmetric-difference a b)
(append (a-without-b a b)
(a-without-b b a)))
;; -- test case
(define A '(John Bob Mary Serena))
(define B '(Jim Mary John Bob))
(display "A\\B: ") (display (a-without-b A B)) (newline)
(display "B\\A: ") (display (a-without-b B A)) (newline)
(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline)
;; -- extra test as we are using lists
(display "Symmetric difference 2: ")
(display (symmetric-difference '(John Serena Bob Mary Serena)
'(Jim Mary John Jim Bob))) (newline)
|
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
| #Plain_English | Plain English | To run:
Start up.
Put 21 into a kelvin temperature.
Show the kelvin temperature in various temperature scales.
Wait for the escape key.
Shut down.
A temperature is a fraction.
A kelvin temperature is a temperature.
A celsius temperature is a temperature.
A rankine temperature is a temperature.
A fahrenheit temperature is a temperature.
To convert a kelvin temperature to a celsius temperature:
Put the kelvin temperature minus 273-15/100 into the celsius temperature.
To convert a kelvin temperature to a rankine temperature:
Put the kelvin temperature times 9/5 into the rankine temperature.
To convert a kelvin temperature to a fahrenheit temperature:
Convert the kelvin temperature to a rankine temperature.
Put the rankine temperature minus 459-67/100 into the fahrenheit temperature.
To show a temperature given a temperature scale string:
Write the temperature scale then " = " then the temperature then " degrees" on the console.
To show a kelvin temperature in various temperature scales:
Convert the kelvin temperature to a celsius temperature.
Convert the kelvin temperature to a fahrenheit temperature.
Convert the kelvin temperature to a rankine temperature.
Show the kelvin temperature given "K".
Show the celsius temperature given "C".
Show the fahrenheit temperature given "F".
Show the rankine temperature given "R". |
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)
| #Perl | Perl | print scalar localtime, "\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)
| #Phix | Phix | include timedate.e
?format_timedate(date(),"Dddd, Mmmm dth, YYYY, h:mm:ss pm")
atom t0 = time()
sleep(0.9)
?time()-t0
|
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]]
| #Haskell | Haskell | ----------------- UPPER OR LOWER TRIANGLE ----------------
matrixTriangle :: Bool -> [[a]] -> Either String [[a]]
matrixTriangle upper matrix
| upper = go drop id
| otherwise = go take pred
where
go f g
| isSquare matrix =
(Right . snd) $
foldr
(\xs (n, rows) -> (pred n, f n xs : rows))
(g $ length matrix, [])
matrix
| otherwise = Left "Defined only for a square matrix."
isSquare :: [[a]] -> Bool
isSquare rows = all ((n ==) . length) rows
where
n = length rows
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_ putStrLn $
zipWith
( flip ((<>) . (<> " triangle:\n\t"))
. either id (show . sum . concat)
)
( [matrixTriangle] <*> [False, True]
<*> [ [ [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]
]
]
)
["Lower", "Upper"] |
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
| #Common_Lisp | Common Lisp |
;;; Calculate all x's and their possible y's.
(defparameter *x-possibleys*
(loop for x from 2 to 49
collect (cons x (loop for y from (- 100 x) downto (1+ x)
collect y)))
"For every x there are certain y's, with respect to the rules of the puzzle")
(defun xys-operation (op x-possibleys)
"returns an alist of ((x possible-y) . (op x possible-y))"
(let ((x (car x-possibleys))
(ys (cdr x-possibleys)))
(mapcar #'(lambda (y) (cons (list x y) (funcall op x y))) ys)))
(defun sp-numbers (op x-possibleys)
"generates all possible sums or products of the puzzle"
(loop for xys in x-possibleys
append (xys-operation op xys)))
(defun group-sp (sp-numbers)
"sp: Sum or Product"
(loop for sp-number in (remove-duplicates sp-numbers :key #'cdr)
collect (cons (cdr sp-number)
(mapcar #'car
(remove-if-not
#'(lambda (sp) (= sp (cdr sp-number)))
sp-numbers
:key #'cdr)))))
(defun statement-1a (sum-groups)
"remove all sums with a single possible xy"
(remove-if
#'(lambda (xys) (= (list-length xys) 1))
sum-groups
:key #'cdr))
(defun statement-1b (x-possibleys)
"S says: P does not know X and Y."
(let ((multi-xy-sums (statement-1a (group-sp (sp-numbers #'+ x-possibleys))))
(products (group-sp (sp-numbers #'* x-possibleys))))
(flet ((sum-has-xy-which-leads-to-unique-prod (sum-xys)
;; is there any product with a single possible xy?
(some #'(lambda (prod-xys) (= (list-length (cdr prod-xys)) 1))
;; all possible xys of the sum's (* x ys)
(mapcar #'(lambda (xy) (assoc (apply #'* xy) products))
(cdr sum-xys)))))
;; remove sums with even one xy which leads to a unique product
(remove-if #'sum-has-xy-which-leads-to-unique-prod multi-xy-sums))))
(defun remaining-products (remaining-sums-xys)
"P's number is one of these"
(loop for sum-xys in remaining-sums-xys
append (loop for xy in (cdr sum-xys)
collect (apply #'* xy))))
(defun statement-2 (remaining-sums-xys)
"P says: Now I know X and Y."
(let ((remaining-products (remaining-products remaining-sums-xys)))
(mapcar #'(lambda (a-sum-unit)
(cons (car a-sum-unit)
(mapcar #'(lambda (xy)
(list (count (apply #'* xy) remaining-products)
xy))
(cdr a-sum-unit))))
remaining-sums-xys)))
(defun statement-3 (remaining-sums-with-their-products-occurrences-info)
"S says: Now I also know X and Y."
(remove-if
#'(lambda (sum-xys)
;; remove those sums which have more than 1 product, that
;; appear only once amongst all remaining products
(> (count 1 sum-xys :key #'car) 1))
remaining-sums-with-their-products-occurrences-info
:key #'cdr))
(defun solution (survivor-sum-and-its-xys)
"Now we know X and Y too :-D"
(let* ((sum (caar survivor-sum-and-its-xys))
(xys (cdar survivor-sum-and-its-xys))
(xy (second (find 1 xys :key #'car))))
(pairlis '(x y sum product)
(list (first xy) (second xy) sum (apply #'* xy)))))
(solution
(statement-3
(statement-2
(statement-1b *x-possibleys*)))) ;; => ((PRODUCT . 52) (SUM . 17) (Y . 13) (X . 4))
|
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: striSet is set of string;
enable_output(striSet);
const proc: main is func
local
const striSet: setA is {"John", "Bob" , "Mary", "Serena"};
const striSet: setB is {"Jim" , "Mary", "John", "Bob" };
begin
writeln(setA >< setB);
end func; |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Sidef | Sidef | var a = ["John", "Serena", "Bob", "Mary", "Serena"];
var b = ["Jim", "Mary", "John", "Jim", "Bob"];
a ^ b -> unique.dump.say; |
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
| #PowerShell | PowerShell | function temp($k){
try{
$c = $k - 273.15
$r = $k / 5 * 9
$f = $r - 459.67
} catch {
Write-host "Input error."
return
}
Write-host ""
Write-host " TEMP (Kelvin) : " $k
Write-host " TEMP (Celsius) : " $c
Write-host " TEMP (Fahrenheit): " $f
Write-host " TEMP (Rankine) : " $r
Write-host ""
}
$input=Read-host "Enter a temperature in Kelvin"
temp $input |
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)
| #Phixmonti | Phixmonti | def printList len for get print endfor enddef
time
"Actual time is " swap 1 get " hour, " rot 2 get " minutes, " rot 3 get nip " seconds, "
"and elapsed " msec " seconds of running time." 10 tolist printList |
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)
| #PHP | PHP | echo time(), "\n"; |
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]]
| #J | J | sum_below_diagonal =: [:+/@,[*>/~@i.@# |
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]]
| #JavaScript | JavaScript | (() => {
"use strict";
// -------- LOWER TRIANGLE OF A SQUARE MATRIX --------
// lowerTriangle :: [[a]] -> Either String [[a]]
const lowerTriangle = matrix =>
// Either a message, if the matrix is not square,
// or the lower triangle of the matrix.
isSquare(matrix) ? (
Right(
matrix.reduce(
([n, rows], xs) => [
1 + n,
rows.concat([xs.slice(0, n)])
],
[0, []]
)[1]
)
) : Left("Not a square matrix");
// isSquare :: [[a]] -> Bool
const isSquare = rows => {
// True if the length of every row in the matrix
// matches the number of rows in the matrix.
const n = rows.length;
return rows.every(x => n === x.length);
};
// ---------------------- TEST -----------------------
const main = () =>
either(
msg => `Lower triangle undefined :: ${msg}`
)(
rows => sum([].concat(...rows))
)(
lowerTriangle([
[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]
])
);
// --------------------- GENERIC ---------------------
// Left :: a -> Either a b
const Left = x => ({
type: "Either",
Left: x
});
// Right :: b -> Either a b
const Right = x => ({
type: "Either",
Right: x
});
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = fl =>
// Application of the function fl to the
// contents of any Left value in e, or
// the application of fr to its Right value.
fr => e => e.Left ? (
fl(e.Left)
) : fr(e.Right);
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// MAIN ---
return main();
})(); |
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
| #D | D | void main() {
import std.stdio, std.algorithm, std.range, std.typecons;
const s1 = cartesianProduct(iota(1, 101), iota(1, 101))
.filter!(p => 1 < p[0] && p[0] < p[1] && p[0] + p[1] < 100)
.array;
alias P = const Tuple!(int, int);
enum add = (P p) => p[0] + p[1];
enum mul = (P p) => p[0] * p[1];
enum sumEq = (P p) => s1.filter!(q => add(q) == add(p));
enum mulEq = (P p) => s1.filter!(q => mul(q) == mul(p));
const s2 = s1.filter!(p => sumEq(p).all!(q => mulEq(q).walkLength != 1)).array;
const s3 = s2.filter!(p => mulEq(p).setIntersection(s2).walkLength == 1).array;
s3.filter!(p => sumEq(p).setIntersection(s3).walkLength == 1).writeln;
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Smalltalk | Smalltalk | |A B|
A := Set new.
B := Set new.
A addAll: #( 'John' 'Bob' 'Mary' 'Serena' ).
B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ).
( (A - B) + (B - A) ) displayNl. |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #SQL.2FPostgreSQL | SQL/PostgreSQL | CREATE OR REPLACE FUNCTION arrxor(anyarray,anyarray) RETURNS anyarray AS $$
SELECT ARRAY(
(
SELECT r.elements
FROM (
(SELECT 1,unnest($1))
UNION ALL
(SELECT 2,unnest($2))
) AS r (arr, elements)
GROUP BY 1
HAVING MIN(arr) = MAX(arr)
)
)
$$ LANGUAGE SQL strict immutable; |
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
| #Pure_Data | Pure Data | #N canvas 200 200 640 600 10;
#X floatatom 130 54 8 0 0 2 Kelvin chgk -;
#X obj 130 453 rnd2;
#X floatatom 130 493 8 0 0 1 K - -;
#X floatatom 251 54 8 0 0 2 Celsius chgc -;
#X obj 251 453 rnd2;
#X floatatom 251 493 8 0 0 1 °C - -;
#X floatatom 374 54 8 0 0 2 Fahrenheit chgf -;
#X obj 374 453 rnd2;
#X floatatom 374 493 8 0 0 1 °F - -;
#X floatatom 498 54 8 0 0 2 Rankine chgr -;
#X obj 498 453 rnd2;
#X floatatom 498 493 8 0 0 1 °Ra - -;
#X obj 65 133 - 273.15;
#X obj 65 244 * 1.8;
#X obj 65 267 + 32;
#X obj 65 363 + 459.67;
#X obj 186 133 * 1.8;
#X obj 186 156 + 32;
#X obj 186 268 + 459.67;
#X obj 186 310 / 1.8;
#X obj 309 133 + 459.67;
#X obj 309 215 / 1.8;
#X obj 309 291 - 273.15;
#X obj 433 133 / 1.8;
#X obj 433 223 - 273.15;
#X obj 433 294 * 1.8;
#X obj 433 317 + 32;
#X text 20 53 Input:;
#X text 20 492 Output:;
#X connect 0 0 1 0;
#X connect 0 0 12 0;
#X connect 1 0 2 0;
#X connect 3 0 4 0;
#X connect 3 0 16 0;
#X connect 4 0 5 0;
#X connect 6 0 7 0;
#X connect 6 0 20 0;
#X connect 7 0 8 0;
#X connect 9 0 10 0;
#X connect 9 0 23 0;
#X connect 10 0 11 0;
#X connect 12 0 13 0;
#X connect 12 0 4 0;
#X connect 13 0 14 0;
#X connect 14 0 15 0;
#X connect 14 0 7 0;
#X connect 15 0 10 0;
#X connect 16 0 17 0;
#X connect 17 0 18 0;
#X connect 17 0 7 0;
#X connect 18 0 19 0;
#X connect 18 0 10 0;
#X connect 19 0 1 0;
#X connect 20 0 21 0;
#X connect 20 0 10 0;
#X connect 21 0 22 0;
#X connect 21 0 1 0;
#X connect 22 0 4 0;
#X connect 23 0 24 0;
#X connect 23 0 1 0;
#X connect 24 0 25 0;
#X connect 24 0 4 0;
#X connect 25 0 26 0;
#X connect 26 0 7 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
| #PureBasic | PureBasic | Procedure.d Kelvin2Celsius(tK.d) : ProcedureReturn tK-273.15 : EndProcedure
Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure
Procedure.d Kelvin2Rankine(tK.d) : ProcedureReturn tK*1.8 : EndProcedure
OpenConsole()
Repeat
Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input())
PrintN("Conversion:")
PrintN(#TAB$+"Celsius "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Rankine "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32)))
PrintN("ESC = End.")
Repeat
k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf
Until RawKey()
ForEver |
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)
| #PicoLisp | PicoLisp | (stamp) |
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)
| #Pike | Pike | write( ctime(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]]
| #jq | jq |
def add(s): reduce s as $x (null; . + $x);
# input: a square matrix
def sum_below_diagonal:
add( range(0;length) as $i | .[$i][:$i][] ) ;
|
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]]
| #Julia | Julia | using LinearAlgebra
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 ]
@show tril(A)
@show tril(A, -1)
@show sum(tril(A, -1)) # 69
|
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
| #Elixir | Elixir | defmodule Puzzle do
def sum_and_product do
s1 = for x <- 2..49, y <- x+1..99, x+y<100, do: {x,y}
s2 = Enum.filter(s1, fn p ->
Enum.all?(sumEq(s1,p), fn q -> length(mulEq(s1,q)) != 1 end)
end)
s3 = Enum.filter(s2, fn p -> only1?(mulEq(s1,p), s2) end)
Enum.filter(s3, fn p -> only1?(sumEq(s1,p), s3) end) |> IO.inspect
end
defp add({x,y}), do: x + y
defp mul({x,y}), do: x * y
defp sumEq(s, p), do: Enum.filter(s, fn q -> add(p) == add(q) end)
defp mulEq(s, p), do: Enum.filter(s, fn q -> mul(p) == mul(q) end)
defp only1?(a, b) do
MapSet.size(MapSet.intersection(MapSet.new(a), MapSet.new(b))) == 1
end
end
Puzzle.sum_and_product |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Swift | Swift | let setA : Set<String> = ["John", "Bob", "Mary", "Serena"]
let setB : Set<String> = ["Jim", "Mary", "John", "Bob"]
println(setA.exclusiveOr(setB)) // symmetric difference of A and B
println(setA.subtract(setB)) // elements in A that are not in B |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Tcl | Tcl | package require struct::set
set A {John Bob Mary Serena}
set B {Jim Mary John Bob}
set AnotB [struct::set difference $A $B]
set BnotA [struct::set difference $B $A]
set SymDiff [struct::set union $AnotB $BnotA]
puts "A\\B = $AnotB"
puts "B\\A = $BnotA"
puts "A\u2296B = $SymDiff"
# Of course, the library already has this operation directly...
puts "Direct Check: [struct::set symdiff $A $B]" |
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
| #Python | Python | >>> while True:
k = float(input('K ? '))
print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
% (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))
K ? 21.0
21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees.
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
K ? |
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)
| #PL.2FI | PL/I | put (datetime()); /* writes out the date and time */
/* The time is given to thousandths of a second, */
/* in the format hhmiss999 */
put (time()); /* gives the time in the format hhmiss999. */ |
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)
| #PowerShell | PowerShell | Get-Date |
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]]
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 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}};
Total[LowerTriangularize[m, -1], 2] |
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]]
| #MiniZinc | MiniZinc |
% Sum below leading diagnal. Nigel Galloway: July 22nd., 2021
array [1..5,1..5] of int: N=[|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|];
int: res=sum(n,g in 1..5 where n>g)(N[n,g]);
output([show(res)])
|
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
| #Factor | Factor | USING: combinators.short-circuit fry kernel literals math
math.ranges memoize prettyprint sequences sets tools.time ;
IN: rosetta-code.sum-and-product
CONSTANT: s1 $[
2 100 [a,b] dup cartesian-product concat
[ first2 { [ < ] [ + 100 < ] } 2&& ] filter
]
: quot-eq ( pair quot -- seq )
[ s1 ] 2dip tuck '[ @ _ @ = ] filter ; inline
MEMO: sum-eq ( pair -- seq ) [ first2 + ] quot-eq ;
MEMO: mul-eq ( pair -- seq ) [ first2 * ] quot-eq ;
: s2 ( -- seq )
s1 [ sum-eq [ mul-eq length 1 = not ] all? ] filter ;
: only-1 ( seq quot -- newseq )
over '[ @ _ intersect length 1 = ] filter ; inline
: sum-and-product ( -- )
[ s2 [ mul-eq ] [ sum-eq ] [ only-1 ] bi@ . ] time ;
MAIN: sum-and-product |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
a="John'Bob'Mary'Serena"
b="Jim'Mary'John'Bob"
DICT names CREATE
SUBMACRO checknames
!var,val
PRINT val,": ",var
LOOP n=var
DICT names APPEND/QUIET n,num,cnt,val;" "
ENDLOOP
ENDSUBMACRO
CALL checknames (a,"a")
CALL checknames (b,"b")
DICT names UNLOAD names,num,cnt,val
LOOP n=names,v=val
PRINT n," in: ",v
ENDLOOP |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #UNIX_Shell | UNIX Shell | uniq() {
u=("$@")
for ((i=0;i<${#u[@]};i++)); do
for ((j=i+1;j<=${#u[@]};j++)); do
[ "${u[$i]}" = "${u[$j]}" ] && unset u[$i]
done
done
u=("${u[@]}")
}
a=(John Serena Bob Mary Serena)
b=(Jim Mary John Jim Bob)
uniq "${a[@]}"
au=("${u[@]}")
uniq "${b[@]}"
bu=("${u[@]}")
ab=("${au[@]}")
for ((i=0;i<=${#au[@]};i++)); do
for ((j=0;j<=${#bu[@]};j++)); do
[ "${ab[$i]}" = "${bu[$j]}" ] && unset ab[$i]
done
done
ab=("${ab[@]}")
ba=("${bu[@]}")
for ((i=0;i<=${#bu[@]};i++)); do
for ((j=0;j<=${#au[@]};j++)); do
[ "${ba[$i]}" = "${au[$j]}" ] && unset ba[$i]
done
done
ba=("${ba[@]}")
sd=("${ab[@]}" "${ba[@]}")
echo "Set A = ${a[@]}"
echo " = ${au[@]}"
echo "Set B = ${b[@]}"
echo " = ${bu[@]}"
echo "A - B = ${ab[@]}"
echo "B - A = ${ba[@]}"
echo "Symmetric difference = ${sd[@]}" |
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
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ 5 9 v* ] is r->k ( n/d --> n/d )
[ 1/v r->k 1/v ] is k->r ( n/d --> n/d )
[ 45967 100 v- ] is r->f ( n/d --> n/d )
[ -v r->f -v ] is f->r ( n/d --> n/d )
[ 5463 20 v- ] is k->c ( n/d --> n/d )
[ -v k->c -v ] is c->k ( n/d --> n/d )
[ k->r r->f ] is k->f ( n/d --> n/d )
[ f->r r->k ] is f->k ( n/d --> n/d )
[ r->k k->c ] is r->c ( n/d --> n/d )
[ c->k k->r ] is c->r ( n/d --> n/d )
[ f->k k->c ] is f->c ( n/d --> n/d )
[ c->r r->f ] is c->f ( n/d --> n/d )
[ $->v drop
2dup 10 point$ echo$
say " Kelvins is equal to" cr
k->c 2dup 10 point$ echo$
say " degrees Celcius" cr
c->f 2dup 10 point$ echo$
say " degrees Fahrenheit" cr
f->r 10 point$ echo$
say " degrees Rankine" cr ] is task ( $ --> )
$ "21.00" task |
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
| #R | R | convert_Kelvin <- function(K){
if (!is.numeric(K))
stop("\n Input has to be numeric")
return(list(
Kelvin = K,
Celsius = K - 273.15,
Fahreneit = K * 1.8 - 459.67,
Rankine = K * 1.8
))
}
convert_Kelvin(21)
|
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)
| #Prolog | Prolog | date_time(H). |
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)
| #PureBasic | PureBasic | time=Date() ; Unix timestamp
time$=FormatDate("%mm.%dd.%yyyy %hh:%ii:%ss",time)
; following value is only reasonable accurate, on Windows it can differ by +/- 20 ms
ms_counter=ElapsedMilliseconds()
; could use API like QueryPerformanceCounter_() on Windows for more accurate values |
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]]
| #Nim | Nim | type SquareMatrix[T: SomeNumber; N: static Positive] = array[N, array[N, T]]
func sumBelowDiagonal[T, N](m: SquareMatrix[T, N]): T =
for i in 1..<N:
for j in 0..<i:
result += m[i][j]
const 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]]
echo sumBelowDiagonal(M) |
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]]
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use List::Util qw( sum );
my $matrix =
[[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]];
my $lowersum = sum map @{ $matrix->[$_] }[0 .. $_ - 1], 1 .. $#$matrix;
print "lower sum = $lowersum\n"; |
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
| #Go | Go | package main
import "fmt"
type pair struct{ x, y int }
func main() {
//const max = 100
// Use 1685 (the highest with a unique answer) instead
// of 100 just to make it work a little harder :).
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all)
// Those for which no sum decomposition has unique product to are
// S mathimatician's possible pairs.
var sPairs []pair
pairs:
for _, p := range all {
s := p.x + p.y
// foreach a+b=s (a<b)
for a := 2; a < s/2+s&1; a++ {
b := s - a
if products[a*b] == 1 {
// Excluded because P would have a unique product
continue pairs
}
}
sPairs = append(sPairs, p)
}
fmt.Println("S starts with", len(sPairs), "possible pairs.")
//fmt.Println("S pairs:", sPairs)
sProducts := countProducts(sPairs)
// Look in sPairs for those with a unique product to get
// P mathimatician's possible pairs.
var pPairs []pair
for _, p := range sPairs {
if sProducts[p.x*p.y] == 1 {
pPairs = append(pPairs, p)
}
}
fmt.Println("P then has", len(pPairs), "possible pairs.")
//fmt.Println("P pairs:", pPairs)
pSums := countSums(pPairs)
// Finally, look in pPairs for those with a unique sum
var final []pair
for _, p := range pPairs {
if pSums[p.x+p.y] == 1 {
final = append(final, p)
}
}
// Nicely show any answers.
switch len(final) {
case 1:
fmt.Println("Answer:", final[0].x, "and", final[0].y)
case 0:
fmt.Println("No possible answer.")
default:
fmt.Println(len(final), "possible answers:", final)
}
}
func countProducts(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x*p.y]++
}
return m
}
func countSums(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x+p.y]++
}
return m
}
// not used, manually inlined above
func decomposeSum(s int) []pair {
pairs := make([]pair, 0, s/2)
for a := 2; a < s/2+s&1; a++ {
pairs = append(pairs, pair{a, s - a})
}
return pairs
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Ursala | Ursala | a = <'John','Bob','Mary','Serena'>
b = <'Jim','Mary','John','Bob'>
#cast %sLm
main =
<
'a': a,
'b': b,
'a not b': ~&j/a b,
'b not a': ~&j/b a,
'symmetric difference': ~&jrljTs/a b> |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Wren | Wren | import "/set" for Set
var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) }
var a = Set.new(["John", "Bob", "Mary", "Serena"])
var b = Set.new(["Jim", "Mary", "John", "Bob"])
System.print("A = %(a)")
System.print("B = %(b)")
System.print("A - B = %(a.except(b))")
System.print("B - A = %(b.except(a))")
System.print("A △ B = %(symmetricDifference.call(a, b))") |
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
| #Racket | Racket | #lang racket
(define (converter temp init final)
(define to-k
(case init
('k temp)
('c (+ 273.15 temp))
('f (* (+ temp 459.67) 5/9))
('r (* temp 5/9))))
(case final
('k to-k)
('c (- to-k 273.15))
('f (- (* to-k 9/5) 459.67))
('r (* to-k 1.8))))
(define (kelvin-to-all temp)
(display (format "Kelvin: ~a \nCelsius: ~a \nFahrenheit: ~a \nRankine: ~a \n"
temp
(converter temp 'k 'c)
(converter temp 'k 'f)
(converter temp 'k 'r))))
(kelvin-to-all 21)
;Kelvin: 21
;Celsius: -252.14999999999998
;Fahrenheit: -421.87
;Rankine: 37.800000000000004
|
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
| #Raku | Raku | my %scale =
Celcius => { factor => 1 , offset => -273.15 },
Rankine => { factor => 1.8, offset => 0 },
Fahrenheit => { factor => 1.8, offset => -459.67 },
;
my $kelvin = +prompt "Enter a temperature in Kelvin: ";
die "No such temperature!" if $kelvin < 0;
for %scale.sort {
printf "%12s: %7.2f\n", .key, $kelvin * .value<factor> + .value<offset>;
} |
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)
| #Python | Python | import time
print time.ctime() |
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)
| #Q | Q | q).z.D
2010.01.25
q).z.N
0D14:17:45.519682000
q).z.P
2010.01.25D14:17:46.962375000
q).z.T
14:17:47.817
q).z.Z
2010.01.25T14:17:48.711
q).z.z
2010.01.25T19:17:59.445 |
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]]
| #Phix | Phix | constant 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}}
atom res = 0
integer height = length(M)
for row=1 to height do
integer width = length(M[row])
if width!=height then crash("not square") end if
for col=1 to row-1 do
res += M[row][col]
end for
end for
?res
|
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
| #Haskell | Haskell | import Data.List (intersect)
s1, s2, s3, s4 :: [(Int, Int)]
s1 = [(x, y) | x <- [1 .. 100], y <- [1 .. 100], 1 < x && x < y && x + y < 100]
add, mul :: (Int, Int) -> Int
add (x, y) = x + y
mul (x, y) = x * y
sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
sumEq p = filter (\q -> add q == add p) s1
mulEq p = filter (\q -> mul q == mul p) s1
s2 = filter (\p -> all (\q -> (length $ mulEq q) /= 1) (sumEq p)) s1
s3 = filter (\p -> length (mulEq p `intersect` s2) == 1) s2
s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3
main = print s4 |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #XPL0 | XPL0 | def John, Bob, Mary, Serena, Jim; \enumerate set items (0..4)
proc SetOut(S); \Output the elements in set
int S;
int Name, I;
[Name:= ["John", "Bob", "Mary", "Serena", "Jim"];
for I:= 0 to 31 do
if S & 1<<I then
[Text(0, Name(I)); ChOut(0, ^ )];
CrLf(0);
];
int A, B;
[A:= 1<<John ! 1<<Bob ! 1<<Mary ! 1<<Serena;
B:= 1<<Jim ! 1<<Mary ! 1<<John ! 1<<Bob;
Text(0, "A xor B = "); SetOut(A | B);
Text(0, "A\B = "); SetOut(A & ~B);
Text(0, "B\A = "); SetOut(B & ~A);
Text(0, "A\B U B\A = "); SetOut(A&~B ! B&~A);
] |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Yabasic | Yabasic | lista1$ = "John Serena Bob Mary Serena"
lista2$ = "Jim Mary John Jim Bob"
lista1$ = quitadup$(lista1$)
lista2$ = quitadup$(lista2$)
res$ = quitacomun$(lista1$, lista2$)
res$ = res$ + quitacomun$(lista2$, lista1$)
print res$
sub quitadup$(l$)
l$ = l$ + " "
return quitarep$(l$)
end sub
sub quitacomun$(l1$, l2$)
l1$ = l1$ + " "
l2$ = l2$ + " "
return quitarep$(l1$, l2$)
end sub
sub quitarep$(l1$, l2$)
local pos, n, x, listar$, nombre$, largo
largo = len(l1$)
pos = 1
while(true)
n = instr(l1$, " ", pos)
if n > 0 then
nombre$ = mid$(l1$, pos, n-pos)
if numparams = 1 then
x = instr(listar$, nombre$)
else
x = instr(l2$, nombre$)
end if
if x = 0 listar$ = listar$ + nombre$ + " "
pos = n + 1
else
return listar$
end if
wend
end sub
|
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
| #REXX | REXX | /*REXX program converts temperatures for a number (8) of temperature scales. */
numeric digits 120 /*be able to support some huge numbers.*/
parse arg tList /*get the specified temperature list. */
do until tList='' /*process the list of temperatures. */
parse var tList x ',' tList /*temps are separated by commas. */
x= translate(x, '((', "[{") /*support other grouping symbols. */
x= space(x); parse var x z '(' /*handle any comments (if any). */
parse upper var z z ' TO ' ! . /*separate the TO option from number.*/
if !=='' then != 'ALL'; all= !=='ALL' /*allow specification of "TO" opt*/
if z=='' then call serr "no arguments were specified." /*oops-ay. */
_= verify(z, '+-.0123456789') /*list of valid numeral/number thingys.*/
n= z
if _\==0 then do
if _==1 then call serr 'illegal temperature:' z
n= left(z, _ - 1) /*pick off the number (hopefully). */
u= strip( substr(z, _) ) /*pick off the temperature unit. */
end
else u= 'k' /*assume kelvin as per task requirement*/
if \datatype(n, 'N') then call serr 'illegal number:' n
if \all then do /*is there is a TO ααα scale? */
call name ! /*process the TO abbreviation. */
!= s n /*assign the full name to ! */
end /*!: now contains temperature full name*/
call name u /*allow alternate scale (miss)spellings*/
select /*convert ──► °Fahrenheit temperatures.*/
when sn=='CELSIUS' then F= n * 9/5 + 32
when sn=='DELISLE' then F= 212 -(n * 6/5)
when sn=='FAHRENHEIT' then F= n
when sn=='KELVIN' then F= n * 9/5 - 459.67
when sn=='NEWTON' then F= n * 60/11 + 32
when sn=='RANKINE' then F= n - 459.67 /*a single R is taken as Rankine.*/
when sn=='REAUMUR' then F= n * 9/4 + 32
when sn=='ROMER' then F= (n-7.5) * 27/4 + 32
otherwise call serr 'illegal temperature scale: ' u
end /*select*/
K = (F + 459.67) * 5/9 /*compute temperature to kelvins. */
say right(' ' x, 79, "─") /*show the original value, scale, sep. */
if all | !=='CELSIUS' then say $( ( F - 32 ) * 5/9 ) 'Celsius'
if all | !=='DELISLE' then say $( ( 212 - F ) * 5/6 ) 'Delisle'
if all | !=='FAHRENHEIT' then say $( F ) 'Fahrenheit'
if all | !=='KELVIN' then say $( K ) 'kelvin's(K)
if all | !=='NEWTON' then say $( ( F - 32 ) * 11/60 ) 'Newton'
if all | !=='RANKINE' then say $( F + 459.67 ) 'Rankine'
if all | !=='REAUMUR' then say $( ( F - 32 ) * 4/9 ) 'Reaumur'
if all | !=='ROMER' then say $( ( F - 32 ) * 4/27 + 7.5 ) 'Romer'
end /*until*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1)
serr: say; say '***error!***'; say; say arg(1); say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
$: procedure; showDig= 8 /*only show eight significant digits.*/
_= format( arg(1), , showDig) / 1 /*format number 8 digs past dec, point.*/
p= pos(., _); L= length(_) /*find position of the decimal point. */
/* [↓] align integers with FP numbers.*/
if p==0 then _= _ || left('', 5+showDig+1) /*the number has no decimal point. */
else _= _ || left('', 5+showDig-L+p) /* " " " a " " */
return right(_, 50) /*return the re-formatted number (arg).*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
name: parse arg y /*abbreviations ──► shortname.*/
yU= translate(y, 'eE', "éÉ"); upper yU /*uppercase the temperature unit*/
if left(yU, 7)=='DEGREES' then yU= substr(yU, 8) /*redundant "degrees" after #? */
if left(yU, 6)=='DEGREE' then yU= substr(yU, 7) /* " "degree" " " */
yU= strip(yU) /*elide blanks at front and back*/
_= length(yU) /*obtain the yU length. */
if right(yU,1)=='S' & _>1 then yU= left(yU, _-1) /*elide trailing plural, if any.*/
select /*abbreviations ──► shortname.*/
when abbrev('CENTIGRADE' , yU) |,
abbrev('CENTRIGRADE', yU) |, /* 50% misspelled.*/
abbrev('CETIGRADE' , yU) |, /* 50% misspelled.*/
abbrev('CENTINGRADE', yU) |,
abbrev('CENTESIMAL' , yU) |,
abbrev('CELCIU' , yU) |, /* 82% misspelled.*/
abbrev('CELCIOU' , yU) |, /* 4% misspelled.*/
abbrev('CELCUI' , yU) |, /* 4% misspelled.*/
abbrev('CELSUI' , yU) |, /* 2% misspelled.*/
abbrev('CELCEU' , yU) |, /* 2% misspelled.*/
abbrev('CELCU' , yU) |, /* 2% misspelled.*/
abbrev('CELISU' , yU) |, /* 1% misspelled.*/
abbrev('CELSU' , yU) |, /* 1% misspelled.*/
abbrev('CELSIU' , yU) then sn= 'CELSIUS'
when abbrev('DELISLE' , yU,2) then sn= 'DELISLE'
when abbrev('FARENHEIT' , yU) |, /* 39% misspelled.*/
abbrev('FARENHEIGHT', yU) |, /* 15% misspelled.*/
abbrev('FARENHITE' , yU) |, /* 6% misspelled.*/
abbrev('FARENHIET' , yU) |, /* 3% misspelled.*/
abbrev('FARHENHEIT' , yU) |, /* 3% misspelled.*/
abbrev('FARINHEIGHT', yU) |, /* 2% misspelled.*/
abbrev('FARENHIGHT' , yU) |, /* 2% misspelled.*/
abbrev('FAHRENHIET' , yU) |, /* 2% misspelled.*/
abbrev('FERENHEIGHT', yU) |, /* 2% misspelled.*/
abbrev('FEHRENHEIT' , yU) |, /* 2% misspelled.*/
abbrev('FERENHEIT' , yU) |, /* 2% misspelled.*/
abbrev('FERINHEIGHT', yU) |, /* 1% misspelled.*/
abbrev('FARIENHEIT' , yU) |, /* 1% misspelled.*/
abbrev('FARINHEIT' , yU) |, /* 1% misspelled.*/
abbrev('FARANHITE' , yU) |, /* 1% misspelled.*/
abbrev('FAHRENHEIT' , yU) then sn= 'FAHRENHEIT'
when abbrev('KALVIN' , yU) |, /* 27% misspelled.*/
abbrev('KERLIN' , yU) |, /* 18% misspelled.*/
abbrev('KEVEN' , yU) |, /* 9% misspelled.*/
abbrev('KELVIN' , yU) then sn= 'KELVIN'
when abbrev('NEUTON' , yU) |, /*100% misspelled.*/
abbrev('NEWTON' , yU) then sn= 'NEWTON'
when abbrev('RANKINE' , yU, 1) then sn= 'RANKINE'
when abbrev('REAUMUR' , yU, 2) then sn= 'REAUMUR'
when abbrev('ROEMER' , yU, 2) |,
abbrev('ROMER' , yU, 2) then sn= 'ROMER'
otherwise call serr 'illegal temperature scale:' y
end /*select*/
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)
| #Quackery | Quackery | time 1000000 / echo say " seconds since the Unix epoch." |
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)
| #R | R | Sys.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]]
| #PL.2FI | PL/I |
trap: procedure options (main); /* 17 December 2021 */
declare n fixed binary;
get (n);
put ('The order of the matrix is ' || trim(n));
begin;
declare A (n,n) fixed binary;
declare sum fixed binary;
declare (i, j) fixed binary;
get (A);
sum = 0;
do i = 2 to n;
do j = 1 to i-1;
sum = sum + a(i,j);
end;
end;
put edit (A) (skip, (n) f(4) );
put skip data (sum);
end;
end trap;
|
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]]
| #PL.2FM | PL/M | 100H: /* SUM THE ELEMENTS BELOW THE MAIN DIAGONAL OF A MATRIX */
/* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* RETURNS THE SUM OF THE ELEMENTS BELOW THE MAIN DIAGONAL OF MX */
/* MX WOULD BE DECLARED AS ''( UB, UB )ADDRESS'' IF PL/M SUPPORTED */
/* 2-DIMENSIONAL ARRAYS, IT DOESN'T SO MX MUST ACTULLY BE DECLARED */
/* ''( UB * UB )ADDRESS'' - EXCEPT THE BOUND MUST BE A CONSTANT, NOT AN */
/* EXPRESSION */
/* NOTE ''ADDRESS'' MEANS UNSIGNED 16-BIT QUANTITY, WHICH CAN BE USED FOR */
/* OTHER PURPOSES THAN JUST POINTERS */
LOWER$SUM: PROCEDURE( MX, UB )ADDRESS;
DECLARE ( MX, UB ) ADDRESS;
DECLARE ( SUM, R, C, STRIDE, R$PTR ) ADDRESS;
DECLARE M$PTR ADDRESS, M$VALUE BASED M$PTR ADDRESS;
SUM = 0;
STRIDE = UB + UB;
R$PTR = MX + STRIDE; /* ADDRESS OF ROW 1 ( THE FIRST ROW IS 0 ) */
DO R = 1 TO UB - 1;
M$PTR = R$PTR;
DO C = 0 TO R - 1;
SUM = SUM + M$VALUE;
M$PTR = M$PTR + 2;
END;
R$PTR = R$PTR + STRIDE; /* ADDRESS OF THE NEXT ROW */
END;
RETURN SUM;
END LOWER$SUM ;
/* TASK TEST CASE */
DECLARE T ( 25 )ADDRESS
INITIAL( 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
);
CALL PR$NUMBER( LOWER$SUM( .T, 5 ) );
EOF |
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
| #Java | Java | package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
/**
* This program applies the logic in the Sum and Product Puzzle for the value
* provided by systematically applying each requirement to all number pairs in
* range. Note that the requirements: (x, y different), (x < y), and
* (x, y > MIN_VALUE) are baked into the loops in run(), sumAddends(), and
* productFactors(), so do not need a separate test. Also note that to test a
* solution to this logic puzzle, it is suggested to test the condition with
* maxSum = 1685 to ensure that both the original solution (4, 13) and the
* additional solution (4, 61), and only these solutions, are found. Note
* also that at 1684 only the original solution should be found!
*/
public class SumAndProductPuzzle {
private final long beginning;
private final int maxSum;
private static final int MIN_VALUE = 2;
private List<int[]> firstConditionExcludes = new ArrayList<>();
private List<int[]> secondConditionExcludes = new ArrayList<>();
public static void main(String... args){
if (args.length == 0){
new SumAndProductPuzzle(100).run();
new SumAndProductPuzzle(1684).run();
new SumAndProductPuzzle(1685).run();
} else {
for (String arg : args){
try{
new SumAndProductPuzzle(Integer.valueOf(arg)).run();
} catch (NumberFormatException e){
System.out.println("Please provide only integer arguments. " +
"Provided argument " + arg + " was not an integer. " +
"Alternatively, calling the program with no arguments " +
"will run the puzzle where maximum sum equals 100, 1684, and 1865.");
}
}
}
}
public SumAndProductPuzzle(int maxSum){
this.beginning = System.currentTimeMillis();
this.maxSum = maxSum;
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" started at " + String.valueOf(beginning) + ".");
}
public void run(){
for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
for (int y = x + 1; y < maxSum - MIN_VALUE; y++){
if (isSumNoGreaterThanMax(x,y) &&
isSKnowsPCannotKnow(x,y) &&
isPKnowsNow(x,y) &&
isSKnowsNow(x,y)
){
System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
" in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
}
}
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
public boolean isSumNoGreaterThanMax(int x, int y){
return x + y <= maxSum;
}
public boolean isSKnowsPCannotKnow(int x, int y){
if (firstConditionExcludes.contains(new int[] {x, y})){
return false;
}
for (int[] addends : sumAddends(x, y)){
if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
firstConditionExcludes.add(new int[] {x, y});
return false;
}
}
return true;
}
public boolean isPKnowsNow(int x, int y){
if (secondConditionExcludes.contains(new int[] {x, y})){
return false;
}
int countSolutions = 0;
for (int[] factors : productFactors(x, y)){
if (isSKnowsPCannotKnow(factors[0], factors[1])){
countSolutions++;
}
}
if (countSolutions == 1){
return true;
} else {
secondConditionExcludes.add(new int[] {x, y});
return false;
}
}
public boolean isSKnowsNow(int x, int y){
int countSolutions = 0;
for (int[] addends : sumAddends(x, y)){
if (isPKnowsNow(addends[0], addends[1])){
countSolutions++;
}
}
return countSolutions == 1;
}
public List<int[]> sumAddends(int x, int y){
List<int[]> list = new ArrayList<>();
int sum = x + y;
for (int addend = MIN_VALUE; addend < sum - addend; addend++){
if (isSumNoGreaterThanMax(addend, sum - addend)){
list.add(new int[]{addend, sum - addend});
}
}
return list;
}
public List<int[]> productFactors(int x, int y){
List<int[]> list = new ArrayList<>();
int product = x * y;
for (int factor = MIN_VALUE; factor < product / factor; factor++){
if (product % factor == 0){
if (isSumNoGreaterThanMax(factor, product / factor)){
list.add(new int[]{factor, product / factor});
}
}
}
return list;
}
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #zkl | zkl | fcn setCommon(list1,list2){ list1.filter(list2.holds); }
fcn sdiff(list1,list2)
{ list1.extend(list2).copy().removeEach(setCommon(list1,list2)) } |
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
| #Ring | Ring |
k = 21.0 c = 0 r = 0 f = 0
convertTemp(k)
see "Kelvin : " + k + nl +
"Celcius : " + c + nl +
"Rankine : " + r + nl +
"Fahrenheit : " + f + nl
func convertTemp k
c = k - 273.15
r = k * 1.8
f = r - 459.67
|
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)
| #Racket | Racket | #lang racket
(require racket/date)
(date->string (current-date)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.