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/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #R | R | library(Rmpfr)
options(scipen = 999)
find_super_d_number <- function(d, N = 10){
super_number <- c(NA)
n = 0
n_found = 0
while(length(super_number) < N){
n = n + 1
test = d * mpfr(n, precBits = 200) ** d #Here I augment precision
test_formatted = .mpfr2str(test)$str #and I extract the... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Raku | Raku | sub super (\d) {
my \run = d x d;
^∞ .hyper.grep: -> \n { (d * n ** d).Str.contains: run }
}
(2..9).race(:1batch).map: {
my $now = now;
put "\nFirst 10 super-$_ numbers:\n{.&super[^10]}\n{(now - $now).round(.1)} sec."
} |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #HicEst | HicEst | SYSTEM(RUN) ! start this script in RUN-mode
CHARACTER notes="Notes.txt", txt*1000
! Remove file name from the global variable $CMD_LINE:
EDIT(Text=$CMD_LINE, Mark1, Right=".hic ", Right=4, Mark2, Delete)
IF($CMD_LINE == ' ') THEN
READ(FIle=notes, LENgth=Lnotes)
IF( Lnotes ) THEN
WINDOW(WINdowhandle=hdl, T... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Icon_and_Unicon | Icon and Unicon |
procedure write_out_notes (filename)
file := open (filename, "rt") | stop ("no notes file yet")
every write (!file)
end
procedure add_to_notes (filename, strs)
file := open (filename, "at") | # append to file if it exists
open (filename, "cat") | # create the file if not there
stop ("unab... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Liberty_BASIC | Liberty BASIC |
[start]
nomainwin
UpperLeftX=1:UpperLeftY=1
WindowWidth=800:WindowHeight=600
open "Super Ellipse" for graphics_nf_nsb as #1
#1 "trapclose [q];down;fill black;flush;color green;size 1"
n=1.5
a=200
b=200
for n = 0.1 to 5 step .1
na=2/n
t=.01
for i = 0 to 3... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Perl | Perl | my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift);
my $lim = 1e14; # Ought to be dynamic as should segment size
my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1));
my $paira = 2; # We're looking for Ta(2) and larger
my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0);
... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Racket | Racket | #lang racket/base
(require racket/list racket/format)
(define (index-of1 x l) (for/first ((i (in-naturals 1)) (m (in-list l)) #:when (equal? m x)) i))
(define (sprprm n)
(define n-1 (- n 1))
(define sp:n-1 (superperm n-1))
(let loop ((subs (let loop ((sp sp:n-1) (i (- (length sp:n-1) n-1 -1)) (rv null))
... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Raku | Raku | for 1..8 -> $len {
my $pre = my $post = my $t = '';
for ('a'..'z')[^$len].permutations -> @p {
$t = @p.join('');
$post ~= $t unless index($post, $t);
$pre = $t ~ $pre unless index($pre, $t);
}
printf "%1d: %8d %8d\n", $len, $pre.chars, $post.chars;
} |
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 z... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. temp-conversion.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Kelvin-Rankine-Ratio VALUE 0.5556. *> 5 / 9 to 4 d.p.
78 Kelvin-Celsius-Diff VALUE 273.15.
78 Rankine-Fahrenheit-Diff VALUE 459.67.
01 temp-kelvin ... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Ring | Ring |
see "The tau functions for the first 100 positive integers are:" + nl
n = 0
num = 0
limit = 100
while num < limit
n = n + 1
tau = 0
for m = 1 to n
if n%m = 0
tau = tau + 1
ok
next
num = num + 1
if num%10 = 1
see nl
ok
tau = s... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Ruby | Ruby | require 'prime'
def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}
(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Rust | Rust | // returns the highest power of i that is a factor of n,
// and n divided by that power of i
fn factor_exponent(n: i32, i: i32) -> (i32, i32) {
if n % i == 0 {
let (a, b) = factor_exponent(n / i, i);
(a + 1, b)
} else {
(0, n)
}
}
fn tau(n: i32) -> i32 {
for i in 2..(n+1) {
if n % i == 0 {
let (count, ... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #SmileBASIC | SmileBASIC | CLS |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #SPL | SPL | #.clear() |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Standard_ML | Standard ML | fun clearScreen () =
let
val strm = TextIO.openOut (Posix.ProcEnv.ctermid ())
in
TextIO.output (strm, "\^[[H\^[[2J");
TextIO.closeOut strm
end |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Stata | Stata | puts -nonewline "\033\[2J"
flush stdout |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Picat | Picat | main =>
(show_op1('!') ; true),
nl,
foreach(Op in ['/\\','\\/','->','=='])
(show_op2(Op) ; nl,true)
end.
ternary(true,'!') = false.
ternary(maybe,'!') = maybe.
ternary(false,'!') = true.
ternary(Cond,'!') = Res =>
C1 = cond(Cond == maybe,maybe,cond(Cond,true,false)),
Res = ternary(C1,'!').
ternar... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #REXX | REXX | /*REXX program to process instrument data from a data file. */
numeric digits 20 /*allow for bigger (precision) numbers.*/
ifid='READINGS.TXT' /*the name of the input file. */
ofid='READINGS.OUT' /* " " " " output " ... |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #Pascal | Pascal | program twelve_days(output);
const
days: array[1..12] of string =
( 'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth' );
gifts: array[1..12] of string =
( 'A partridge in a pear tree.',
'Two turtle doves and',
'T... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Mercury | Mercury | :- module synchronous_concurrency.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module int, list, string, thread, thread.channel, thread.mvar.
:- type line_or_stop
---> line(string)
; stop.
main(!IO) :-
io.open_input("input.txt", ... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Nim | Nim | var msgs: Channel[string]
var count: Channel[int]
const FILE = "input.txt"
proc read() {.thread.} =
for line in FILE.lines:
msgs.send(line)
msgs.send("")
echo count.recv()
count.close()
proc print() {.thread.} =
var n = 0
while true:
var msg = msgs.recv()
if msg.len == 0:
break
e... |
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
Retr... | #AutoIt | AutoIt | MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC) |
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
Retr... | #Avail | Avail | Print: “now”; |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Clojure | Clojure | (defmacro reduce-with
"simplifies form of reduce calls"
[bindings & body]
(assert (and (vector? bindings) (= 4 (count bindings))))
(let [[acc init, item sequence] bindings]
`(reduce (fn [~acc ~item] ~@body) ~init ~sequence)))
(defn digits
"maps e.g. 2345 => [2 3 4 5]"
[n] (->> n str seq (map #(- (int ... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #J | J | primes=: p: i. _1 p: 1000 NB. all prime numbers below 1000
sums=: +/\ primes NB. running sum of those primes
mask=: 1 p: sums NB. array of 0s, 1s where sums are primes
NB. indices of prime sums (incremented for 1-based indexing)
NB. "copy" only the final primes in the prime sums
NB. "copy" o... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #jq | jq | def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Julia | Julia | using Primes
p1000 = primes(1000)
for n in 1:length(p1000)
parray = p1000[1:n]
sparray = sum(parray)
if isprime(sparray)
println("The sum of the $n primes from prime 2 to prime $(p1000[n]) is $sparray, which is prime.")
end
end
|
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | p = Prime[Range[PrimePi[1000]]];
TableForm[
Select[Transpose[{Range[Length[p]], p, Accumulate[p]}], Last /* PrimeQ],
TableHeadings -> {None, {"Prime count", "Prime", "Prime sum"}}
] |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #JavaScript | JavaScript |
<html>
<head>
<script>
function clip (subjectPolygon, clipPolygon) {
var cp1, cp2, s, e;
var inside = function (p) {
return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]);
};
var intersection = 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... | #D | D | import std.stdio, std.algorithm, std.array;
struct Set(T) {
immutable T[] items;
Set opSub(in Set other) const pure nothrow {
return items.filter!(x => !other.items.canFind(x)).array.Set;
}
Set opAdd(in Set other) const pure nothrow {
return Set(this.items ~ (other - this).items);
... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #REXX | REXX | /*REXX program computes and displays the first N super─d numbers for D from LO to HI.*/
numeric digits 100 /*ensure enough decimal digs for calc. */
parse arg n LO HI . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 10 ... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Ruby | Ruby | (2..8).each do |d|
rep = d.to_s * d
print "#{d}: "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).join(", ")
end
|
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #J | J | require 'files strings'
notes=: monad define
if. #y do.
now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY'
'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y
elseif. -. _1 -: txt=. fread 'notes.txt' do.
smoutput txt
end.
)
notes 2}.ARGV
exit 0 |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Java | Java | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Lua | Lua | local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Phix | Phix | -- demo\rosetta\Taxicab_numbers.exw
with javascript_semantics
function cube_sums()
// create cubes and sorted list of cube sums
sequence cubes = {}, sums = {}
for i=1 to 1189 do
atom cube = i * i * i
sums &= sq_add(cubes,cube)
cubes &= cube
end for
sums = sort(sums) -- (706,2... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #REXX | REXX | /*REXX program attempts to find better minimizations for computing superpermutations.*/
parse arg cycles . /*obtain optional arguments from the CL*/
if cycles=='' | cycles=="," then cycles= 7 /*Not specified? Then use the default.*/
do n=0 to cycles
#= 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 z... | #Common_Lisp | Common Lisp |
(defun to-celsius (k)
(- k 273.15))
(defun to-fahrenheit (k)
(- (* k 1.8) 459.67))
(defun to-rankine (k)
(* k 1.8))
(defun temperature-conversion ()
(let ((k (read)))
(if (numberp k)
(format t "Celsius: ~d~%Fahrenheit: ~d~%Rankine: ~d~%"
(to-celsius k) (to-fahrenheit k) (to-rankine ... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Sidef | Sidef | say { .sigma0 }.map(1..100).join(' ') |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Swift | Swift | import Foundation
// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while (n & 1) == 0 {
total += 1
n >>= 1
}
// Odd prime factors up to the square root
var p = 3
whi... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Tiny_BASIC | Tiny BASIC | LET N = 0
10 LET N = N + 1
IF N < 3 THEN GOTO 100
LET T = 2
LET A = 1
20 LET A = A + 1
IF (N/A)*A = N THEN LET T = T + 1
IF A<(N+1)/2 THEN GOTO 20
30 PRINT "Tau(",N,") = ",T
IF N<100 THEN GOTO 10
END
100 LET T = N
GOTO 30 |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Tcl | Tcl | puts -nonewline "\033\[2J"
flush stdout |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #UNIX_Shell | UNIX Shell | clear
# Alternative method using tput
tput clear |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Visual_Basic_.NET | Visual Basic .NET | System.Console.Clear() |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #PicoLisp | PicoLisp | (de 3not (A)
(or (=0 A) (not A)) )
(de 3and (A B)
(cond
((=T A) B)
((=0 A) (and B 0)) ) )
(de 3or (A B)
(cond
((=T A) T)
((=0 A) (or (=T B) 0))
(T B) ) )
(de 3impl (A B)
(cond
((=T A) B)
((=0 A) (or (=T B) 0))
(T T) ) )
(de 3equiv (A B)
(cond
... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Ruby | Ruby | filename = "readings.txt"
total = { "num_readings" => 0, "num_good_readings" => 0, "sum_readings" => 0.0 }
invalid_count = 0
max_invalid_count = 0
invalid_run_end = ""
File.new(filename).each do |line|
num_readings = 0
num_good_readings = 0
sum_readings = 0.0
fields = line.split
fields[1..-1].each_slice(2... |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #Perl | Perl | use v5.10;
my @days = qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth };
chomp ( my @gifts = grep { /\S/ } <DATA> );
while ( my $day = shift @days ) {
say "On the $day day of Christmas,\nMy true love gave to me:";
say for map { $day eq 'first' ? s/And a/A/r : $_ } @g... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #OCaml | OCaml | open Event |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Oforth | Oforth | import: parallel
: printing(chPrint, chCount)
0 while( chPrint receive dup notNull ) [ println 1+ ] drop
chCount send drop ;
: concurrentPrint(aFileName)
| chPrint chCount line |
Channel new ->chPrint
Channel new ->chCount
#[ printing(chPrint, chCount) ] &
aFileName File new forEach: line [ chPr... |
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
Retr... | #AWK | AWK | $ awk 'BEGIN{print systime(),strftime()}' |
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
Retr... | #BaCon | BaCon | ' BaCon time
n = NOW
PRINT n, " seconds since January 1st, 1970"
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d "
PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n" |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #CLU | CLU | summarize = proc (s: string) returns (string) signals (bad_format)
digit_count: array[int] := array[int]$fill(0,10,0)
for c: char in string$chars(s) do
d: int := int$parse(string$c2s(c)) resignal bad_format
digit_count[d] := digit_count[d] + 1
end
out: stream := stream$create_output()
... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Nim | Nim | import math, strformat
const N = 999
func isPrime(n: Positive): bool =
if (n and 1) == 0: return n == 2
if (n mod 3) == 0: return n == 3
var d = 5
var delta = 2
while d <= sqrt(n.toFloat).int:
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
result = true
echo "index prime pr... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Perl | Perl | use strict;
use warnings;
use ntheory <nth_prime is_prime>;
my($n, $s, $limit, @sums) = (0, 0, 1000);
do {
push @sums, sprintf '%3d %8d', $n, $s if is_prime($s += nth_prime ++$n)
} until $n >= $limit;
print "Of the first $limit primes: @{[scalar @sums]} cumulative prime sums:\n", join "\n", @sums; |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Phix | Phix | function sp(integer n) return is_prime(sum(get_primes(-n))) end function
sequence res = apply(filter(tagset(length(get_primes_le(1000))),sp),sprint)
printf(1,"Found %d of em: %s\n",{length(res),join(shorten(res,"",5),", ")})
|
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Julia | Julia | using Luxor
isinside(p, a, b) = (b.x - a.x) * (p.y - a.y) > (b.y - a.y) * (p.x - a.x)
function intersection(a, b, s, f)
dc = [a.x - b.x, a.y - b.y]
dp = [s.x - f.x, s.y - f.y]
n1 = a.x * b.y - a.y * b.x
n2 = s.x * f.y - s.y * f.x
n3 = 1.0 / (dc[1] * dp[2] - dc[2] * dp[1])
Point((n1 * dp[1] -... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.geom.Line2D
import javax.swing.*
class SutherlandHodgman : JPanel() {
private val subject = listOf(
doubleArrayOf( 50.0, 150.0), doubleArrayOf(200.0, 50.0), doubleArrayOf(350.0, 150.0),
doubleArrayOf(350.0, 300.0), doubleArrayOf(250.0, 300.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... | #Datalog | Datalog | .decl A(text: symbol)
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
.output SymmetricDifference
A("this").
A("is").
A("a").
A("test").
B("also").
B("part").
B("of").
B("a").
B("test").
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x). |
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... | #Delphi | Delphi |
PROGRAM Symmetric_difference;
uses
System.Typinfo;
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
TNameHelper = record helper for TName
FUNCTION ToString(): string;
end;
{ TNameHlper }
FUNCTION TNameHelper.ToString: string;
BEGIN
Result := GetEnumName(TypeInfo(TName), O... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Rust | Rust | // [dependencies]
// rug = "1.9"
fn print_super_d_numbers(d: u32, limit: u32) {
use rug::Assign;
use rug::Integer;
println!("First {} super-{} numbers:", limit, d);
let digits = d.to_string().repeat(d as usize);
let mut count = 0;
let mut n = 1;
let mut s = Integer::new();
while coun... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Sidef | Sidef | func super_d(d) {
var D = Str(d)*d
1..Inf -> lazy.grep {|n| Str(d * n**d).contains(D) }
}
for d in (2..8) {
say ("#{d}: ", super_d(d).first(10))
} |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Swift | Swift | import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).r... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #JavaScript | JavaScript | var notes = 'NOTES.TXT';
var args = WScript.Arguments;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;
if (args.length == 0) {
if (fso.FileExists(notes)) {
var f = fso.OpenTextFile(notes, ForReading);
WScript.Echo(f.ReadAll());
... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Julia | Julia | using Dates
const filename = "NOTES.TXT"
if length(ARGS) == 0
fp = open(filename, "r")
println(read(fp, String))
else
fp = open(filename, "a+")
write(fp, string(DateTime(now()), "\n\t", join(ARGS, " "), "\n"))
end
close(fp)
|
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Maple | Maple | plots:-implicitplot(abs((1/200)*x^2.5)+abs((1/200)*y^2.5) = 1, x = -10 .. 10, y = -10 .. 10); |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ContourPlot[Abs[x/200]^2.5 + Abs[y/200]^2.5 == 1, {x, -200, 200}, {y, -200, 200}] |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
(off 'B)
(for L (subsets 2 (range 1 1200))
(let K (sum '((N) (** N 3)) L)
(ifn (lup B K)
(idx 'B (list K 1 (list L)) T)
(inc (cdr @))
(push (cddr @) L) ) ) )
(setq R
(filter
'((L) (>= (cadr L) 2))
(idx 'B)) )
(for L (head 25 R)
(println (car ... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #PureBasic | PureBasic | #MAX=1189
Macro q3(a,b)
a*a*a+b*b*b
EndMacro
Structure Cap
x.i
y.i
s.i
EndStructure
NewList Taxi.Cap()
For i=1 To #MAX
For j=i To #MAX
AddElement(Taxi()) : Taxi()\s=q3(i,j) : Taxi()\x=i : Taxi()\y=j
Next j
Next i
SortStructuredList(Taxi(),#PB_Sort_Ascending,OffsetOf(Cap\s),TypeOf(Cap\s))... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Ruby | Ruby | #A straight forward implementation of N. Johnston's algorithm. I prefer to look at this as 2n+1 where
#the second n is first n reversed, and the 1 is always the second symbol. This algorithm will generate
#just the left half of the result by setting l to [1,2] and looping from 3 to 6. For the purpose of
#this task I am... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Scala | Scala | object SuperpermutationMinimisation extends App {
val nMax = 12
@annotation.tailrec
def factorial(number: Int, acc: Long = 1): Long =
if (number == 0) acc else factorial(number - 1, acc * number)
def factSum(n: Int): Long = (1 to n).map(factorial(_)).sum
for (n <- 0 until nMax) println(f"superPerm($... |
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 z... | #D | D | double kelvinToCelsius(in double k) pure nothrow @safe {
return k - 273.15;
}
double kelvinToFahrenheit(in double k) pure nothrow @safe {
return k * 1.8 - 459.67;
}
double kelvinToRankine(in double k) pure nothrow @safe {
return k * 1.8;
}
unittest {
import std.math: approxEqual;
assert(approx... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Verilog | Verilog | module main;
integer N, T, A;
initial begin
$display("The tau functions for the first 100 positive integers are:\n");
for (N = 1; N <= 100; N=N+1) begin
if (N < 3) T = N;
else begin
T = 2;
for (A = 2; A <= (N+1)/2; A=A+1) begin
if (N % A == 0) T = T ... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
System.print("The tau functions for the first 100 positive integers are:")
for (i in 1..100) {
Fmt.write("$2d ", Int.divisors(i).count)
if (i % 20 == 0) System.print()
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Wren | Wren | System.print("\e[2J") |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #XPL0 | XPL0 | code Clear=40;
Clear; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Yabasic | Yabasic | clear screen |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #zkl | zkl | System.cmd(System.isWindows and "cls" or "clear");
// or, for ANSI terminals: print("\e[2J") |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #PureBasic | PureBasic | DataSection
TLogic:
Data.i -1,0,1
TSymb:
Data.s "F","?","T"
EndDataSection
Structure TL
F.i
M.i
T.i
EndStructure
Structure SYM
TS.s{2}[3]
EndStructure
*L.TL=?TLogic
*S.SYM=?TSymb
Procedure.i NOT3(*x.TL)
ProcedureReturn -*x
EndProcedure
Procedure.i AND3(*x.TL,*y.TL)
If *x>*y : ProcedureRetu... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Scala | Scala | object DataMunging {
import scala.io.Source
def spans[A](list: List[A]) = list.tail.foldLeft(List((list.head, 1))) {
case ((a, n) :: tail, b) if a == b => (a, n + 1) :: tail
case (l, b) => (b, 1) :: l
}
type Flag = ((Boolean, Int), String)
type Flags = List[Flag]
type LineIterator = Iterator[Opt... |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #Phix | Phix | constant days = {"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"},
gifts = {"A partridge in a pear tree.\n",
"Two turtle doves, and\n",
"Three French hens,\n",
"Four calli... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Ol | Ol |
(import (owl parse))
(coroutine 'reader (lambda ()
; lazy line-by-line file reader
(define (not-a-newline x) (not (eq? x #\newline)))
(define parser (let-parse*
((line (greedy* (byte-if not-a-newline)))
(newline (imm #\newline)))
(bytes-... |
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
Retr... | #BASIC | BASIC | PRINT TIMER |
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
Retr... | #BASIC256 | BASIC256 | print month+1; "-"; day; "-"; year
# returns system date in format: mm-dd-yyyy
print hour; ":"; minute; ":"; second
# returns system time in format: hh:mm:ss |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #CoffeeScript | CoffeeScript |
sequence = (n) ->
cnts = {}
for c in n.toString()
d = parseInt(c)
incr cnts, d
seq = []
while true
s = ''
for i in [9..0]
s += "#{cnts[i]}#{i}" if cnts[i]
if s in seq
break
seq.push s
new_cnts = {}
for digit, cnt of cnts
incr new_cnts, cnt
incr new_c... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Python | Python | '''Prime sums of primes up to 1000'''
from itertools import accumulate, chain, takewhile
# primeSums :: [(Int, (Int, Int))]
def primeSums():
'''Non finite stream of enumerated tuples,
in which the first value is a prime,
and the second the sum of that prime and all
preceding primes.
... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Lua | Lua | subjectPolygon = {
{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}
}
clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}
function inside(p, cp1, cp2)
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end
function intersection(cp1... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | set :setA set{ :John :Bob :Mary :Serena }
set :setB set{ :Jim :Mary :John :Bob }
symmetric-difference A B:
}
for a in keys A:
if not has B a:
a
for b in keys B:
if not has A b:
b
set{
!. symmetric-difference setA setB |
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... | #E | E | ? def symmDiff(a, b) { return (a &! b) | (b &! a) }
# value: <symmDiff>
? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet())
# value: ["Jim", "Serena"].asSet() |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var start = System.clock
var rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888"]
for (i in 2..8) {
Fmt.print("First 10 super-$d numbers:", i)
var count = 0
var j = BigInt.three
while (true) {
var k = j.pow(i) * i
var ix = ... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import java.util.Date
import java.text.SimpleDateFormat
fun main(args: Array<String>) {
val f = File("NOTES.TXT")
// create file if it doesn't exist already
f.createNewFile()
if (args.size == 0) {
println(f.readText())
}
else {
val df = S... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Lasso | Lasso | #!/usr/bin/lasso9
local(
arguments = $argv -> asarray,
notesfile = file('notes.txt')
)
#arguments -> removefirst
if(#arguments -> size) => {
#notesfile -> openappend
#notesfile -> dowithclose => {
#notesfile -> writestring(date -> format(`YYYY-MM-dd HH:mm:SS`) + '\n')
#notesfile -> writestring('\t' + #a... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Nim | Nim | import math
import imageman
const
Size = 600
X0 = Size div 2
Y0 = Size div 2
Background = ColorRGBU [byte 0, 0, 0]
Foreground = ColorRGBU [byte 255, 255, 255]
proc drawSuperEllipse(img: var Image; n: float; a, b: int) =
var yList = newSeq[int](a + 1)
for x in 0..a:
let an = pow(a.toFloat, n)
... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #ooRexx | ooRexx | This program draws 5 super ellipses:
black 120,120,1.5
blue 160,160,2
red 200,200,2.5
green 240,240,3
black 280,280,4 |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Python | Python | from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.i... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Sidef | Sidef | for len in (1..8) {
var (pre="", post="")
@^len -> permutations {|*p|
var t = p.join
post.append!(t) if !post.contains(t)
pre.prepend!(t) if !pre.contains(t)
}
printf("%2d: %8d %8d\n", len, pre.len, post.len)
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Wren | Wren | import "/fmt" for Fmt
var max = 12
var sp = []
var count = List.filled(max, 0)
var pos = 0
var factSum = Fn.new { |n|
var s = 0
var x = 0
var f = 1
while (x < n) {
x = x + 1
f = f * x
s = s + f
}
return s
}
var r // recursive
r = Fn.new { |n|
if (n == 0) return... |
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 z... | #Delphi | Delphi |
program Temperature;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TTemp = class
private
fCelsius, fFahrenheit, fRankine: double;
public
constructor Create(aKelvin: double);
property AsCelsius: double read fCelsius;
property AsFahrenheit: double read fFahrenheit;
property AsRankine: double ... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #XPL0 | XPL0 | int N, D, C;
[Format(3, 0);
for N:= 1 to 100 do
[C:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then C:= C+1;
RlOut(0, float(C));
if rem(N/20) = 0 then CrLf(0);
];
] |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Python | Python | class Trit(int):
def __new__(cls, value):
if value == 'TRUE':
value = 1
elif value == 'FALSE':
value = 0
elif value == 'MAYBE':
value = -1
return super(Trit, cls).__new__(cls, value // (abs(value) or 1))
def __repr__(self):
if self >... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.