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/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink |
a = "Monkey"
b = a
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FutureBasic | FutureBasic |
include "NSLog.incl"
CFStringRef original, copy
original = @"Hello!"
copy = fn StringWithString( original )
NSLog( @"%@", copy )
HandleEvents
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Ada | Ada | with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Circle is
-- extreme coordinate values are -15:0, 15:0, 0:-15, 0:15
subtype Coordinate is Integer range -15 .. 15;
type Point is record
X, Y : Coordinate;
end record;
type Point_List is array (Positive range <>) of Point;
function Acceptable (Position : Point) return Boolean is
Squared_Sum : Natural := Position.X ** 2 + Position.Y ** 2;
begin
return 10 ** 2 <= Squared_Sum and Squared_Sum <= 15 ** 2;
end Acceptable;
-- first algorithm
function Generate_Random_Points
(Count : Positive := 100)
return Point_List
is
package RNG is new Ada.Numerics.Discrete_Random (Coordinate);
Generator : RNG.Generator;
Next_Point : Point;
Result : Point_List (1 .. Count);
begin
RNG.Reset (Generator);
for N in Result'Range loop
loop
Next_Point.X := RNG.Random (Generator);
Next_Point.Y := RNG.Random (Generator);
exit when Acceptable (Next_Point);
end loop;
Result (N) := Next_Point;
end loop;
return Result;
end Generate_Random_Points;
-- second algorithm
function Choose_Precalculated
(Count : Positive := 100)
return Point_List
is
subtype Possible_Points is Positive range 1 .. 404;
package RNG is new Ada.Numerics.Discrete_Random (Possible_Points);
Generator : RNG.Generator;
Point_Pool : Point_List (Possible_Points);
Next_Point : Point;
Next_Index : Possible_Points := 1;
Result : Point_List (1 .. Count);
begin
-- precalculate
Precalculate : for X in Coordinate'Range loop
Next_Point.X := X;
for Y in Coordinate'Range loop
Next_Point.Y := Y;
if Acceptable (Next_Point) then
Point_Pool (Next_Index) := Next_Point;
exit Precalculate when Next_Index = Possible_Points'Last;
Next_Index := Next_Index + 1;
end if;
end loop;
end loop Precalculate;
-- choose
RNG.Reset (Generator);
for N in Result'Range loop
Result (N) := Point_Pool (RNG.Random (Generator));
end loop;
return Result;
end Choose_Precalculated;
procedure Print_Points (Points : Point_List) is
Output_String : array (Coordinate, Coordinate) of Character :=
(others => (others => ' '));
begin
for N in Points'Range loop
Output_String (Points (N).X, Points (N).Y) := '*';
end loop;
for Line in Output_String'Range (2) loop
for Column in Output_String'Range (1) loop
Ada.Text_IO.Put (Output_String (Column, Line));
end loop;
Ada.Text_IO.New_Line;
end loop;
end Print_Points;
My_Circle_Randomly : Point_List := Generate_Random_Points;
My_Circle_Precalculated : Point_List := Choose_Precalculated;
begin
Ada.Text_IO.Put_Line ("Randomly generated:");
Print_Points (My_Circle_Randomly);
Ada.Text_IO.Put_Line ("Chosen from precalculated:");
Print_Points (My_Circle_Precalculated);
end Circle; |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #ATS | ATS | //
// Convex hulls by Andrew's monotone chain algorithm.
//
// For a description of the algorithm, see
// https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169
//
//
// The implementation is designed for use with a garbage collector.
// In other words, some of the memory is allowed to leak.
//
// Sometimes, where it is slightly easier if one does so, we do try to
// free memory. Boehm GC sometimes cannot free allocated memory
// itself, so perhaps it is just as well if an ATS program explicitly
// frees some of its memory.
//
#include "share/atspre_staload.hats"
#define NIL list_nil ()
#define :: list_cons
(* Make the floating point type big, so use of a boxed representation
for points makes some sense. *)
typedef floatpt = ldouble
extern castfn int2floatpt : int -<> floatpt
overload i2fp with int2floatpt
(*------------------------------------------------------------------*)
//
// Enough plane geometry for our purpose.
//
(* Let us make the point type boxed. Here is one way to do that. The
name of the type will be "plane_point_t". The constructor will be
named "plane_point". *)
datatype plane_point_t =
| plane_point of (floatpt, floatpt)
fn {}
plane_point_x (p : plane_point_t) :<> floatpt =
let
val+ plane_point (x, _) = p
in
x
end
fn {}
plane_point_y (p : plane_point_t) :<> floatpt =
let
val+ plane_point (_, y) = p
in
y
end
fn {}
plane_point_eq (p : plane_point_t,
q : plane_point_t) :<> bool =
let
val+ plane_point (xp, yp) = p
val+ plane_point (xq, yq) = q
in
xp = xq && yp = yq
end
(* Impose a total order on points, making it one that will work for
Andrew's monotone chain algorithm. *)
fn {}
plane_point_order (p : plane_point_t,
q : plane_point_t) :<> bool =
let
val+ plane_point (xp, yp) = p
val+ plane_point (xq, yq) = q
in
xp < xq || (xp = xq && yp < yq)
end
(* Subtraction is really a vector or multivector operation. *)
fn {}
plane_point_sub (p : plane_point_t,
q : plane_point_t) :<> plane_point_t =
let
val+ plane_point (xp, yp) = p
val+ plane_point (xq, yq) = q
in
plane_point (xp - xq, yp - yq)
end
(* Cross product is really a multivector operation. *)
fn {}
plane_point_cross (p : plane_point_t,
q : plane_point_t) :<> floatpt =
let
val+ plane_point (xp, yp) = p
val+ plane_point (xq, yq) = q
in
(xp * yq) - (yp * xq)
end
overload .x with plane_point_x
overload .y with plane_point_y
overload = with plane_point_eq
overload order with plane_point_order
overload < with plane_point_order
overload - with plane_point_sub
(* Make "cross" a left-associative infix operator with the same
precedence as "*". *)
infixl ( * ) cross
overload cross with plane_point_cross
(*------------------------------------------------------------------*)
//
// Sorting an array of points.
//
fn
plane_point_array_sort
{n : int}
(arr : &(@[plane_point_t][n]) >> _,
n : size_t n) :<!wrt> void =
let
(* The comparison will be inlined by template expansion. *)
implement
array_quicksort$cmp<plane_point_t> (p, q) =
if order (p, q) then (* An overload for plane_point_order. *)
~1
else if q < p then (* Another overload for plane_point_order. *)
1
else
0
in
(* The following sort routine is in the ATS2 prelude. *)
array_quicksort<plane_point_t> (arr, n)
end
(*------------------------------------------------------------------*)
//
// Removing duplicates from a sorted array. Returns a new array.
//
extern fun {a : t@ype}
array_delete_neighbor_dups$eq (p : a, q : a) :<> bool
fn {a : t@ype}
array_delete_neighbor_dups
{n : int}
(arr : &(@[a][n]),
n : size_t n)
:<!wrt> [m : nat | m <= n]
[parr1 : addr]
@(@[a][m] @ parr1,
mfree_gc_v parr1 |
ptr parr1,
size_t m) =
let
macdef eq = array_delete_neighbor_dups$eq<a>
fn
nondups_list {n : int}
(arr : &(@[a][n]),
n : size_t n)
:<> [m : nat | m <= n] list (a, m) =
let
fun
loop {i : nat | i < n}
{k : nat | k < n - i}
.<i>. (* <-- proof of termination. *)
(arr : &(@[a][n]),
i : size_t i,
lst : list (a, k))
:<> [m : nat | m <= n] list (a, m) =
(* Cons a list of non-duplicates, going backwards through
the array so the list will be in forwards order. (The
order does not really matter in ATS, though, because in
the prelude there are both array_initize_list *and*
array_initize_rlist. *)
if i = i2sz 0 then
arr[i] :: lst
(* The "\" in the following line makes eq temporarily
infix. *)
else if arr[i - 1] \eq arr[i] then
loop (arr, pred i, lst)
else
loop (arr, pred i, arr[i] :: lst)
prval () = lemma_array_param arr
in
if n = i2sz 0 then
NIL
else
loop (arr, pred n, NIL)
end
val lst = nondups_list (arr, n)
prval () = lemma_list_param lst
val m = i2sz (length lst)
val @(pfarr1, pfgc1 | parr1) = array_ptr_alloc<a> (m)
val () = array_initize_list<a> (!parr1, sz2i m, lst)
in
@(pfarr1, pfgc1 | parr1, m)
end
(*------------------------------------------------------------------*)
//
// Removing duplicates from a sorted plane_point_t array. Returns a
// new array.
//
fn
plane_point_array_delete_neighbor_dups
{n : int}
(arr : &(@[plane_point_t][n]),
n : size_t n)
:<!wrt> [m : nat | m <= n]
[parr1 : addr]
@(@[plane_point_t][m] @ parr1,
mfree_gc_v parr1 |
ptr parr1,
size_t m) =
let
implement
array_delete_neighbor_dups$eq<plane_point_t> (p, q) =
p = q (* Here = is an overload for plane_point_eq. *)
in
array_delete_neighbor_dups<plane_point_t> (arr, n)
end
(*------------------------------------------------------------------*)
//
// The convex hull algorithm.
//
fn
cross_test {m, k : int | 1 <= k; k < m}
(pt_i : plane_point_t,
hull : &(@[plane_point_t][m]),
k : size_t k) :<> bool =
let
val hull_k = hull[k]
and hull_k1 = hull[k - 1]
in
i2fp 0 < (hull_k - hull_k1) cross (pt_i - hull_k1)
end
fn
construct_lower_hull {n : int | 2 <= n}
(pt : &(@[plane_point_t][n]),
n : size_t n)
:<!wrt> [m : int | 2 <= m; m <= n]
[phull : addr]
@(@[plane_point_t][n] @ phull,
mfree_gc_v phull |
ptr phull,
size_t m) =
let
val @(pfhull, pfgc | phull) = array_ptr_alloc<plane_point_t> n
(* It is easier to work with an array if it is fully
initialized. (Yes, there are also ways to cheat and so merely
pretend the array has been initialized.) *)
val arbitrary_point = plane_point (i2fp 0, i2fp 0)
val () = array_initize_elt<plane_point_t> (!phull, n,
arbitrary_point)
(* The macro "hull" can be used with index notation "[]". *)
macdef hull = !phull
val () = hull[0] := pt[0]
val () = hull[1] := pt[1]
fun
outer_loop {i : int | 0 <= i; i <= n}
{j : int | 1 <= j; j < n}
.<n - i>. (* <-- proof of termination. *)
(pt : &(@[plane_point_t][n]),
hull : &(@[plane_point_t][n]),
i : size_t i,
j : size_t j)
:<!wrt> [m : int | 2 <= m; m <= n] size_t m =
if i = n then
succ j
else
let
val pt_i = pt[i]
fun
inner_loop {k : int | 0 <= k; k < n - 1}
.<k>. (* <-- proof of termination. *)
(hull : &(@[plane_point_t][n]),
k : size_t k)
:<!wrt> [j : int | 1 <= j; j < n] size_t j =
if k = i2sz 0 then
begin
hull[succ k] := pt_i;
succ k
end
else if cross_test (pt_i, hull, k) then
begin
hull[succ k] := pt_i;
succ k
end
else
inner_loop (hull, pred k)
(* I do not know how to write a proof of the following, so
let us test it at runtime. *)
val () = $effmask_exn assertloc (j < n - 1)
in
outer_loop (pt, hull, succ i, inner_loop (hull, j))
end
val hull_size = outer_loop (pt, hull, i2sz 2, i2sz 1)
in
@(pfhull, pfgc | phull, hull_size)
end
fn
construct_upper_hull {n : int | 2 <= n}
(pt : &(@[plane_point_t][n]),
n : size_t n)
:<!wrt> [m : int | 2 <= m; m <= n]
[phull : addr]
@(@[plane_point_t][n] @ phull,
mfree_gc_v phull |
ptr phull,
size_t m) =
let
val @(pfhull, pfgc | phull) = array_ptr_alloc<plane_point_t> n
(* It is easier to work with an array if it is fully
initialized. (Yes, there are also ways to cheat and so merely
pretend the array has been initialized.) *)
val arbitrary_point = plane_point (i2fp 0, i2fp 0)
val () = array_initize_elt<plane_point_t> (!phull, n,
arbitrary_point)
(* The macro "hull" can be used with index notation "[]". *)
macdef hull = !phull
val () = hull[0] := pt[n - 1]
val () = hull[1] := pt[n - 2]
fun
outer_loop {i1 : int | 0 <= i1; i1 <= n - 2}
{j : int | 1 <= j; j < n}
.<i1>. (* <-- proof of termination. *)
(pt : &(@[plane_point_t][n]),
hull : &(@[plane_point_t][n]),
i1 : size_t i1,
j : size_t j)
:<!wrt> [m : int | 2 <= m; m <= n] size_t m =
if i1 = i2sz 0 then
succ j
else
let
val i = pred i1
val pt_i = pt[i]
fun
inner_loop {k : int | 0 <= k; k < n - 1}
.<k>. (* <-- proof of termination. *)
(hull : &(@[plane_point_t][n]),
k : size_t k)
:<!wrt> [j : int | 1 <= j; j < n] size_t j =
if k = i2sz 0 then
begin
hull[succ k] := pt_i;
succ k
end
else if cross_test (pt_i, hull, k) then
begin
hull[succ k] := pt_i;
succ k
end
else
inner_loop (hull, pred k)
(* I do not know how to write a proof of the following, so
let us test it at runtime. *)
val () = $effmask_exn assertloc (j < n - 1)
in
outer_loop (pt, hull, pred i1, inner_loop (hull, j))
end
val hull_size = outer_loop (pt, hull, n - i2sz 2, i2sz 1)
in
@(pfhull, pfgc | phull, hull_size)
end
fn
construct_hull {n : int | 2 <= n}
(pt : &(@[plane_point_t][n]),
n : size_t n)
:<!wrt> [hull_size : int | 2 <= hull_size]
[phull : addr]
@(@[plane_point_t][hull_size] @ phull,
mfree_gc_v phull |
ptr phull,
size_t hull_size) =
(* The following implementation demonstrates slightly complicated
"safe" initialization. By "safe" I mean so one never *reads* from
an uninitialized entry. Elsewhere in the program I did this more
simply, with prelude routines.
I also demonstrate freeing of a linear object. If you remove the
calls to array_ptr_free, you cannot compile the program. *)
let
(* Side note: Construction of the lower and upper hulls can be
done in parallel. *)
val [lower_hull_size : int]
[p_lower_hull : addr]
@(pf_lower_hull, pfgc_lower | p_lower_hull, lower_hull_size) =
construct_lower_hull (pt, n)
and [upper_hull_size : int]
[p_upper_hull : addr]
@(pf_upper_hull, pfgc_upper | p_upper_hull, upper_hull_size) =
construct_upper_hull (pt, n)
stadef hull_size = lower_hull_size + upper_hull_size - 2
val hull_size : size_t hull_size =
lower_hull_size + upper_hull_size - i2sz 2
val [phull : addr] @(pfhull, pfgc_hull | phull) =
array_ptr_alloc<plane_point_t> hull_size
(* Split off the part of each partial hull's view that we actually
will use. *)
prval @(pf_lower, pf_lower_rest) =
array_v_split {plane_point_t} {p_lower_hull} {n}
{lower_hull_size - 1}
pf_lower_hull
prval @(pf_upper, pf_upper_rest) =
array_v_split {plane_point_t} {p_upper_hull} {n}
{upper_hull_size - 1}
pf_upper_hull
(* Split the new array's view in two. The question mark means
that the array elements are uninitialized. *)
prval @(pfleft, pfright) =
array_v_split {plane_point_t?} {phull} {hull_size}
{lower_hull_size - 1}
pfhull
(* Copy the lower hull, thus initializing the left side of the new
array. *)
val () = array_copy<plane_point_t> (!phull, !p_lower_hull,
pred lower_hull_size)
(* Copy the upper hull, thus initializing the left side of the new
array. *)
val phull_right =
ptr_add<plane_point_t> (phull, pred lower_hull_size)
val () = array_copy<plane_point_t> (!phull_right, !p_upper_hull,
pred upper_hull_size)
(* Join the views of the initialized halves. *)
prval pfhull = array_v_unsplit (pfleft, pfright)
(* Restore the views of the partial hulls. *)
prval () = pf_lower_hull :=
array_v_unsplit (pf_lower, pf_lower_rest)
prval () = pf_upper_hull :=
array_v_unsplit (pf_upper, pf_upper_rest)
(* We do not need the lower and upper hulls anymore, and so can
free them. (Of course, if there is a garbage collector, you
could make freeing be a no-operation.) *)
val () = array_ptr_free (pf_lower_hull, pfgc_lower | p_lower_hull)
val () = array_ptr_free (pf_upper_hull, pfgc_upper | p_upper_hull)
in
@(pfhull, pfgc_hull | phull, hull_size)
end
fn
plane_convex_hull {num_points : int}
(points_lst : list (plane_point_t, num_points))
:<!wrt> [hull_size : int | 0 <= hull_size]
[phull : addr]
@(@[plane_point_t][hull_size] @ phull,
mfree_gc_v phull |
ptr phull,
size_t hull_size) =
(* Takes an arbitrary list of points, which may be in any order and
may contain duplicates. Returns an ordered array of points that
make up the convex hull. If the initial list of points is empty,
the returned array is empty. *)
let
prval () = lemma_list_param points_lst
val num_points = i2sz (length points_lst)
(* Copy the list to an array. *)
val @(pf_points, pfgc_points | p_points) =
array_ptr_alloc<plane_point_t> num_points
val () =
array_initize_list<plane_point_t> (!p_points, sz2i num_points,
points_lst)
(* Sort the array. *)
val () = plane_point_array_sort (!p_points, num_points)
(* Create a new sorted array that has the duplicates removed. *)
val @(pf_pt, pfgc_pt | p_pt, n) =
plane_point_array_delete_neighbor_dups (!p_points, num_points)
(* The original array no longer is needed. *)
val () = array_ptr_free (pf_points, pfgc_points | p_points)
in
if n <= 2 then
@(pf_pt, pfgc_pt | p_pt, n)
else
let
val @(pfhull, pfgc_hull | phull, hull_size) =
construct_hull (!p_pt, n)
val () = array_ptr_free (pf_pt, pfgc_pt | p_pt)
in
@(pfhull, pfgc_hull | phull, hull_size)
end
end
(*------------------------------------------------------------------*)
implement
main0 () =
{
val example_points =
$list (plane_point (i2fp 16, i2fp 3),
plane_point (i2fp 12, i2fp 17),
plane_point (i2fp 0, i2fp 6),
plane_point (i2fp ~4, i2fp ~6),
plane_point (i2fp 16, i2fp 6),
plane_point (i2fp 16, i2fp ~7),
plane_point (i2fp 16, i2fp ~3),
plane_point (i2fp 17, i2fp ~4),
plane_point (i2fp 5, i2fp 19),
plane_point (i2fp 19, i2fp ~8),
plane_point (i2fp 3, i2fp 16),
plane_point (i2fp 12, i2fp 13),
plane_point (i2fp 3, i2fp ~4),
plane_point (i2fp 17, i2fp 5),
plane_point (i2fp ~3, i2fp 15),
plane_point (i2fp ~3, i2fp ~9),
plane_point (i2fp 0, i2fp 11),
plane_point (i2fp ~9, i2fp ~3),
plane_point (i2fp ~4, i2fp ~2),
plane_point (i2fp 12, i2fp 10))
val (pf_hull, pfgc_hull | p_hull, hull_size) =
plane_convex_hull example_points
macdef hull = !p_hull
val () =
let
var i : [i : nat] size_t i
in
for (i := i2sz 0; i < hull_size; i := succ i)
println! ("(", hull[i].x(), " ", hull[i].y(), ")")
end
val () = array_ptr_free (pf_hull, pfgc_hull | p_hull)
}
(*------------------------------------------------------------------*) |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #EasyLang | EasyLang | func split sec . s$ .
divs[] = [ 60 60 24 7 ]
n$[] = [ "sec" "min" "hr" "d" "wk" ]
len r[] 5
for i range 4
r[i] = sec mod divs[i]
sec = sec div divs[i]
.
r[4] = sec
s$ = ""
for i = 4 downto 0
if r[i] <> 0
if s$ <> ""
s$ &= ", "
.
s$ &= r[i] & " " & n$[i]
.
.
.
call split 7259 s$
print s$
call split 86400 s$
print s$
call split 6000000 s$
print s$ |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Ruby | Ruby | class Foodbox
def initialize (*food)
raise ArgumentError, "food must be eadible" unless food.all?{|f| f.respond_to?(:eat)}
@box = food
end
end
class Fruit
def eat; end
end
class Apple < Fruit; end
p Foodbox.new(Fruit.new, Apple.new)
# => #<Foodbox:0x00000001420c88 @box=[#<Fruit:0x00000001420cd8>, #<Apple:0x00000001420cb0>]>
p Foodbox.new(Apple.new, "string can't eat")
# => test1.rb:3:in `initialize': food must be eadible (ArgumentError)
|
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Rust | Rust |
// This declares the "Eatable" constraint. It could contain no function.
trait Eatable {
fn eat();
}
// This declares the generic "FoodBox" type,
// whose parameter must satisfy the "Eatable" constraint.
// The objects of this type contain a vector of eatable objects.
struct FoodBox<T: Eatable> {
_data: Vec<T>,
}
// This implements the functions associated with the "FoodBox" type.
// This statement is not required, but here it is used
// to declare a handy "new" constructor.
impl<T: Eatable> FoodBox<T> {
fn new() -> FoodBox<T> {
FoodBox::<T> { _data: Vec::<T>::new() }
}
}
// This declares a simple type.
struct Banana {}
// This makes the "Banana" type satisfy the "Eatable" constraint.
// For that, every declaration inside the declaration of "Eatable"
// must be implemented here.
impl Eatable for Banana {
fn eat() {}
}
// This makes also the primitive "char" type satisfy the "Eatable" constraint.
impl Eatable for char {
fn eat() {}
}
fn main() {
// This instantiate a "FoodBox" parameterized by the "Banana" type.
// It is allowed as "Banana" implements "Eatable".
let _fb1 = FoodBox::<Banana>::new();
// This instantiate a "FoodBox" parameterized by the "char" type.
// It is allowed, as "char" implements "Eatable".
let _fb2 = FoodBox::<char>::new();
// This instantiate a "FoodBox" parameterized by the "bool" type.
// It is NOT allowed, as "bool" does not implement "Eatable".
//let _fb3 = FoodBox::<bool>::new();
}
|
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Sather | Sather | abstract class $EDIBLE is
eat;
end;
class FOOD < $EDIBLE is
readonly attr name:STR;
eat is
#OUT + "eating " + self.name + "\n";
end;
create(name:STR):SAME is
res ::= new;
res.name := name;
return res;
end;
end;
class CAR is
readonly attr name:STR;
create(name:STR):SAME is
res ::= new;
res.name := name;
return res;
end;
end;
class FOODBOX{T < $EDIBLE} is
private attr list:LLIST{T};
create:SAME is
res ::= new;
res.list := #;
return res;
end;
add(c :T) is
self.list.insert_back(c);
end;
elt!:T is loop yield self.list.elt!; end; end;
end;
class MAIN is
main is
box ::= #FOODBOX{FOOD}; -- ok
box.add(#FOOD("Banana"));
box.add(#FOOD("Amanita Muscaria"));
box2 ::= #FOODBOX{CAR}; -- not ok
box2.add(#CAR("Punto")); -- but compiler let it pass!
-- eat everything
loop box.elt!.eat; end;
end;
end; |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Scala | Scala | type Eatable = { def eat: Unit }
class FoodBox(coll: List[Eatable])
case class Fish(name: String) {
def eat {
println("Eating "+name)
}
}
val foodBox = new FoodBox(List(new Fish("salmon"))) |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Phix | Phix | integer pn = 1, -- prime numb
lp = 2, -- last prime
lg = 0, -- last gap
pd = 0 -- prev d
sequence cr = {0,0}, -- curr run [a,d]
mr = {{0},{0}} -- max runs ""
while true do
pn += 1
integer p = get_prime(pn), gap = p-lp,
d = compare(gap,lg)
if p>1e6 then exit end if
if d then
integer i = (3-d)/2
cr[i] = iff(d=pd?cr[i]:lp!=2)+1
if cr[i]>mr[i][1] then mr[i] = {cr[i],pn} end if
end if
{pd,lp,lg} = {d,p,gap}
end while
for run=1 to 2 do
integer {l,e} = mr[run]
sequence p = apply(tagset(e,e-l),get_prime),
g = sq_sub(p[2..$],p[1..$-1])
printf(1,"longest %s run length %d: %v gaps: %v\n",
{{"ascending","descending"}[run],length(p),p,g})
end for
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #CoffeeScript | CoffeeScript | # Compute a continuous fraction of the form
# a0 + b1 / (a1 + b2 / (a2 + b3 / ...
continuous_fraction = (f) ->
a = f.a
b = f.b
c = 1
for n in [100000..1]
c = b(n) / (a(n) + c)
a(0) + c
# A little helper.
p = (a, b) ->
console.log a
console.log b
console.log "---"
do ->
fsqrt2 =
a: (n) -> if n is 0 then 1 else 2
b: (n) -> 1
p Math.sqrt(2), continuous_fraction(fsqrt2)
fnapier =
a: (n) -> if n is 0 then 2 else n
b: (n) -> if n is 1 then 1 else n - 1
p Math.E, continuous_fraction(fnapier)
fpi =
a: (n) ->
return 3 if n is 0
6
b: (n) ->
x = 2*n - 1
x * x
p Math.PI, continuous_fraction(fpi) |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Gambas | Gambas | Public Sub main()
Dim src As String
Dim dst As String
src = "Hello"
dst = src
Print src
Print dst
End |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #GAP | GAP | #In GAP strings are lists of characters. An affectation simply copy references
a := "more";
b := a;
b{[1..4]} := "less";
a;
# "less"
# Here is a true copy
a := "more";
b := ShallowCopy(a);
b{[1..4]} := "less";
a;
# "more" |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #ALGOL_68 | ALGOL 68 | PROC clrscr = VOID:
printf(($g"[2J"$,REPR 27)); # ansi.sys #
PROC gotoxy = (INT x,y)VOID:
printf(($g"["g(0)";"g(0)"H"$,REPR 27, y,x)); # ansi.sys #
MODE POINT = STRUCT(
INT x,y
);
INT radius = 15;
INT inside radius = 10;
POINT center = (radius+1, radius+1);
FLEX[0]POINT set;
PROC swap with last set = (INT position,INT where last set)VOID:
(
INT temp := x OF set[position];
x OF set[position]:=x OF set[where last set];
x OF set[where last set] := temp;
temp := y OF set[position];
y OF set[position]:=y OF set[where last set];
y OF set[where last set] := temp
);
PROC create set = VOID:
(
set := HEAP[(2*radius+1)**2]POINT;
INT x,y,i:=LWB set;
FOR x FROM -radius TO radius DO
FOR y FROM -radius TO radius DO
IF sqrt(x*x+y*y)>=inside radius AND sqrt(x*x+y*y)<=radius THEN
x OF set[i] := x;
y OF set[i] := y;
i+:=1
FI
OD
OD;
set:=set[:i-1]
);
PROC plot fuzzy set = (CHAR ch)VOID:
(
INT pos,i;
TO UPB set DO
pos := ENTIER(random * UPB set) + 1;
gotoxy(x OF center + x OF set[pos],y OF center + y OF set[pos]);
print(ch);
swap with last set(pos,UPB set)
OD
);
main:
(
# srand((INT)time(NIL)); #
clrscr;
create set;
plot fuzzy set("*");
gotoxy(2*radius+1, 2*radius+1);
newline(stand in)
) |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #C | C | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct tPoint {
int x, y;
} Point;
bool ccw(const Point *a, const Point *b, const Point *c) {
return (b->x - a->x) * (c->y - a->y)
> (b->y - a->y) * (c->x - a->x);
}
int comparePoints(const void *lhs, const void *rhs) {
const Point* lp = lhs;
const Point* rp = rhs;
if (lp->x < rp->x)
return -1;
if (rp->x < lp->x)
return 1;
if (lp->y < rp->y)
return -1;
if (rp->y < lp->y)
return 1;
return 0;
}
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void printPoints(const Point* points, int len) {
printf("[");
if (len > 0) {
const Point* ptr = points;
const Point* end = points + len;
printf("(%d, %d)", ptr->x, ptr->y);
++ptr;
for (; ptr < end; ++ptr)
printf(", (%d, %d)", ptr->x, ptr->y);
}
printf("]");
}
Point* convexHull(Point p[], int len, int* hsize) {
if (len == 0) {
*hsize = 0;
return NULL;
}
int i, size = 0, capacity = 4;
Point* hull = xmalloc(capacity * sizeof(Point));
qsort(p, len, sizeof(Point), comparePoints);
/* lower hull */
for (i = 0; i < len; ++i) {
while (size >= 2 && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))
--size;
if (size == capacity) {
capacity *= 2;
hull = xrealloc(hull, capacity * sizeof(Point));
}
assert(size >= 0 && size < capacity);
hull[size++] = p[i];
}
/* upper hull */
int t = size + 1;
for (i = len - 1; i >= 0; i--) {
while (size >= t && !ccw(&hull[size - 2], &hull[size - 1], &p[i]))
--size;
if (size == capacity) {
capacity *= 2;
hull = xrealloc(hull, capacity * sizeof(Point));
}
assert(size >= 0 && size < capacity);
hull[size++] = p[i];
}
--size;
assert(size >= 0);
hull = xrealloc(hull, size * sizeof(Point));
*hsize = size;
return hull;
}
int main() {
Point points[] = {
{16, 3}, {12, 17}, { 0, 6}, {-4, -6}, {16, 6},
{16, -7}, {16, -3}, {17, -4}, { 5, 19}, {19, -8},
{ 3, 16}, {12, 13}, { 3, -4}, {17, 5}, {-3, 15},
{-3, -9}, { 0, 11}, {-9, -3}, {-4, -2}, {12, 10}
};
int hsize;
Point* hull = convexHull(points, sizeof(points)/sizeof(Point), &hsize);
printf("Convex Hull: ");
printPoints(hull, hsize);
printf("\n");
free(hull);
return 0;
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Elixir | Elixir | defmodule Convert do
@minute 60
@hour @minute*60
@day @hour*24
@week @day*7
@divisor [@week, @day, @hour, @minute, 1]
def sec_to_str(sec) do
{_, [s, m, h, d, w]} =
Enum.reduce(@divisor, {sec,[]}, fn divisor,{n,acc} ->
{rem(n,divisor), [div(n,divisor) | acc]}
end)
["#{w} wk", "#{d} d", "#{h} hr", "#{m} min", "#{s} sec"]
|> Enum.reject(fn str -> String.starts_with?(str, "0") end)
|> Enum.join(", ")
end
end
Enum.each([7259, 86400, 6000000], fn sec ->
:io.fwrite "~10w sec : ~s~n", [sec, Convert.sec_to_str(sec)]
end) |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Sidef | Sidef | class FoodBox(*food { .all { .respond_to(:eat) } }) { }
class Fruit { method eat { ... } }
class Apple < Fruit { }
say FoodBox(Fruit(), Apple()).dump #=> FoodBox(food: [Fruit(), Apple()])
say FoodBox(Apple(), "foo") #!> ERROR: class `FoodBox` !~ (Apple, String) |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Swift | Swift | protocol Eatable {
func eat()
} |
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #Wren | Wren | // abstract class
class Eatable {
eat() { /* override in child class */ }
}
class FoodBox {
construct new(contents) {
if (contents.any { |e| !(e is Eatable) }) {
Fiber.abort("All FoodBox elements must be eatable.")
}
_contents = contents
}
contents { _contents }
}
// Inherits from Eatable and overrides eat() method.
class Pie is Eatable {
construct new(filling) { _filling = filling }
eat() { System.print("%(_filling) pie, yum!") }
}
// Not an Eatable.
class Bicycle {
construct new() {}
}
var items = [Pie.new("Apple"), Pie.new("Gooseberry")]
var fb = FoodBox.new(items)
fb.contents.each { |item| item.eat() }
System.print()
items.add(Bicycle.new())
fb = FoodBox.new(items) // throws an error because Bicycle not eatable |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Python | Python |
from sympy import sieve
primelist = list(sieve.primerange(2,1000000))
listlen = len(primelist)
# ascending
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
while pindex < listlen:
diff = primelist[pindex] - primelist[pindex-1]
if diff > old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
# descending
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
while pindex < listlen:
diff = primelist[pindex] - primelist[pindex-1]
if diff < old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
|
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Raku | Raku | use Math::Primesieve;
use Lingua::EN::Numbers;
my $sieve = Math::Primesieve.new;
my $limit = 1000000;
my @primes = $sieve.primes($limit);
sub runs (&op) {
my $diff = 1;
my $run = 1;
my @diff = flat 1, (1..^@primes).map: {
my $next = @primes[$_] - @primes[$_ - 1];
if &op($next, $diff) { ++$run } else { $run = 1 }
$diff = $next;
$run;
}
my $max = max @diff;
my @runs = @diff.grep: * == $max, :k;
@runs.map( {
my @run = (0..$max).reverse.map: -> $r { @primes[$_ - $r] }
flat roundrobin(@run».&comma, @run.rotor(2 => -1).map({[R-] $_})».fmt('(%d)'));
} ).join: "\n"
}
say "Longest run(s) of ascending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«>»);
say "\nLongest run(s) of descending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«<»); |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Common_Lisp | Common Lisp | (defun estimate-continued-fraction (generator n)
(let ((temp 0))
(loop for n1 from n downto 1
do (multiple-value-bind (a b)
(funcall generator n1)
(setf temp (/ b (+ a temp)))))
(+ (funcall generator 0) temp)))
(format t "sqrt(2) = ~a~%" (coerce (estimate-continued-fraction
(lambda (n)
(values (if (> n 0) 2 1) 1)) 20)
'double-float))
(format t "napier's = ~a~%" (coerce (estimate-continued-fraction
(lambda (n)
(values (if (> n 0) n 2)
(if (> n 1) (1- n) 1))) 15)
'double-float))
(format t "pi = ~a~%" (coerce (estimate-continued-fraction
(lambda (n)
(values (if (> n 0) 6 3)
(* (1- (* 2 n))
(1- (* 2 n))))) 10000)
'double-float)) |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #GML | GML | src = "string";
dest = src; |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | src := "Hello"
dst := src |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #AutoHotkey | AutoHotkey | z=100 ; x = x-coord; y = y-coord; z = count; pBitmap = a pointer to the image; f = filename
pToken := Gdip_Startup()
pBitmap := Gdip_CreateBitmap(31, 32)
While z
{
Random, x, -20, 20
Random, y, -20,20
If ( t := sqrt(x**2 + y**2) ) >= 10 && t <= 15
Gdip_SetPixel(pBitmap, x+15, y+16, 255<<24), z--
}
Gdip_SaveBitmapToFile(pBitmap, f := A_ScriptDir "\ahk_fuzzycircle.png")
run % f
Gdip_DisposeImage(pBitmap)
Gdip_Shutdown(pToken) |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace ConvexHull {
class Point : IComparable<Point> {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int X { get => x; set => x = value; }
public int Y { get => y; set => y = value; }
public int CompareTo(Point other) {
return x.CompareTo(other.x);
}
public override string ToString() {
return string.Format("({0}, {1})", x, y);
}
}
class Program {
private static List<Point> ConvexHull(List<Point> p) {
if (p.Count == 0) return new List<Point>();
p.Sort();
List<Point> h = new List<Point>();
// lower hull
foreach (var pt in p) {
while (h.Count >= 2 && !Ccw(h[h.Count - 2], h[h.Count - 1], pt)) {
h.RemoveAt(h.Count - 1);
}
h.Add(pt);
}
// upper hull
int t = h.Count + 1;
for (int i = p.Count - 1; i >= 0; i--) {
Point pt = p[i];
while (h.Count >= t && !Ccw(h[h.Count - 2], h[h.Count - 1], pt)) {
h.RemoveAt(h.Count - 1);
}
h.Add(pt);
}
h.RemoveAt(h.Count - 1);
return h;
}
private static bool Ccw(Point a, Point b, Point c) {
return ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X));
}
static void Main(string[] args) {
List<Point> points = new List<Point>() {
new Point(16, 3),
new Point(12, 17),
new Point(0, 6),
new Point(-4, -6),
new Point(16, 6),
new Point(16, -7),
new Point(16, -3),
new Point(17, -4),
new Point(5, 19),
new Point(19, -8),
new Point(3, 16),
new Point(12, 13),
new Point(3, -4),
new Point(17, 5),
new Point(-3, 15),
new Point(-3, -9),
new Point(0, 11),
new Point(-9, -3),
new Point(-4, -2),
new Point(12, 10)
};
List<Point> hull = ConvexHull(points);
Console.Write("Convex Hull: [");
for (int i = 0; i < hull.Count; i++) {
if (i > 0) {
Console.Write(", ");
}
Point pt = hull[i];
Console.Write(pt);
}
Console.WriteLine("]");
}
}
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Erlang | Erlang |
-module(convert_seconds).
-export([test/0]).
test() ->
lists:map(fun convert/1, [7259, 86400, 6000000]),
ok.
convert(Seconds) ->
io:format(
"~7s seconds = ~s\n",
[integer_to_list(Seconds), compoundDuration(Seconds)] ).
% Compound duration of t seconds. The argument is assumed to be positive.
compoundDuration(Seconds) ->
intercalate(
", ",
lists:map(
fun({D,L}) -> io_lib:format("~p ~s",[D, L]) end,
compdurs(Seconds) ) ).
% Time broken down into non-zero durations and their labels.
compdurs(T) ->
Ds =
reduceBy(
T,
lists:map(
fun(Dl) -> element(1,Dl) end,
tl(durLabs()) ) ),
lists:filter(
fun(Dl) -> element(1,Dl) /= 0 end,
lists:zip(
Ds,
lists:map(
fun(Dl) -> element(2,Dl) end,
durLabs() ) ) ).
% Duration/label pairs.
durLabs() ->
[
{undefined, "wk"},
{7, "d"},
{24, "hr"},
{60, "min"},
{60, "sec"}
].
reduceBy(N, Xs) ->
{N_, Ys} = mapaccumr(fun quotRem/2, N, Xs),
[N_ | Ys].
quotRem(X1, X2) ->
{X1 div X2, X1 rem X2}.
% **************************************************
% Adapted from http://lpaste.net/edit/47875
% **************************************************
mapaccuml(_,I,[]) ->
{I, []};
mapaccuml(F,I,[H|T]) ->
{Accum, NH} = F(I,H),
{FAccum, NT} = mapaccuml(F,Accum,T),
{FAccum, [NH | NT]}.
mapaccumr(_,I,[]) ->
{I, []};
mapaccumr(F,I,L) ->
{Acc, Ys} = mapaccuml(F,I,lists:reverse(L)),
{Acc, lists:reverse(Ys)}.
% **************************************************
% **************************************************
% Copied from https://github.com/tim/erlang-oauth/blob/master/src/oauth.erl
% **************************************************
intercalate(Sep, Xs) ->
lists:concat(intersperse(Sep, Xs)).
intersperse(_, []) ->
[];
intersperse(_, [X]) ->
[X];
intersperse(Sep, [X | Xs]) ->
[X, Sep | intersperse(Sep, Xs)].
% **************************************************
|
http://rosettacode.org/wiki/Constrained_genericity | Constrained genericity | Constrained genericity or bounded quantification means
that a parametrized type or function (see parametric polymorphism)
can only be instantiated on types fulfilling some conditions,
even if those conditions are not used in that function.
Say a type is called "eatable" if you can call the function eat on it.
Write a generic type FoodBox which contains a collection of objects of
a type given as parameter, but can only be instantiated on eatable types.
The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).
The specification of a type being eatable should be as generic as possible
in your language (i.e. the restrictions on the implementation of eatable types
should be as minimal as possible).
Also explain the restrictions, if any, on the implementation of eatable types,
and show at least one example of an eatable type.
| #zkl | zkl | class Eatable{ var v;
fcn eat{ println("munching ",self.topdog.name); }
}
class FoodBox{
fcn init(food1,food2,etc){
editable,garbage:=vm.arglist.filter22("isChildOf",Eatable);
var contents=editable;
if(garbage) println("Rejecting: ",garbage);
}
} |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #REXX | REXX | /*REXX program finds the longest sequence of consecutive primes where the differences */
/*──────────── between the primes are strictly ascending; also for strictly descending.*/
parse arg hi cols . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 1000000 /* " " " " " " */
if cols=='' | cols=="," then cols= 10 /* " " " " " " */
call genP /*build array of semaphores for primes.*/
w= 10 /*width of a number in any column. */
call fRun 1; call show 1 /*find runs with ascending prime diffs.*/
call fRun 0; call show 0 /* " " " descending " " */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
fRun: parse arg ?; mxrun=0; seq.= /*max run length; lists of prime runs.*/
/*search for consecutive primes < HI.*/
do j=2 for #-2; cp= @.j; jn= j+1 /*CP: current prime; JN: next j */
diff= @.jn - cp /*get difference between last 2 primes.*/
cnt= 1; run= /*initialize the CNT and RUN. */
do k= jn+1 to #-2; km= k-1 /*look for more primes in this run. */
if ? then if @[email protected]<=diff then leave /*Diff. too small? Stop looking*/
else nop
else if @[email protected]>=diff then leave /* " " large? " " */
run= run @.k; cnt= cnt+1 /*append a prime to the run; bump count*/
diff= @.k - @.km /*calculate difference for next prime. */
end /*k*/
if cnt<=mxrun then iterate /*This run too short? Then keep looking*/
mxrun= max(mxrun, cnt) /*define a new maximum run (seq) length*/
seq.mxrun= cp @.jn run /*full populate the sequence (RUN). */
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*define low primes.*/
#=8; sq.#= @.# ** 2 /*number of primes so far; prime sqiare*/
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 to hi; parse var j '' -1 _ /*find odd primes from here on.*/
if _==5 then iterate; if j// 3==0 then iterate /*J ÷ 5? J ÷ by 3? */
if j// 7==0 then iterate; if j//11==0 then iterate /*" " 7? " " " 11? */
if j//13==0 then iterate; if j//17==0 then iterate /*" " 13? " " " 17? */
do k=8 while sq.k<=j /* [↓] divide by the known odd primes.*/
if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; sq.#= j*j /*bump # of Ps; assign next P; P square*/
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg ?; if ? then AorD= 'ascending' /*choose which literal for display.*/
else AorD= 'descending' /* " " " " " */
title= ' longest run of consecutive primes whose differences between primes are' ,
'strictly' AorD "and < " commas(hi)
say; say; say
if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
found= 0; idx= 1 /*initialize # of consecutive primes. */
$= /*a list of consecutive primes (so far)*/
do o=1 for words(seq.mxrun) /*show all consecutive primes in seq. */
c= commas( word(seq.mxrun, o) ) /*obtain the next prime in the sequence*/
found= found + 1 /*bump the number of consecutive primes*/
if cols<=0 then iterate /*build the list (to be shown later)? */
$= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/
if found//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2) /*display what we have so far (cols). */
idx= idx + cols; $= /*bump the index count for the output*/
end /*o*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*maybe show residual output*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say; say commas(Cprimes) ' was the'title; return |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #D | D | import std.stdio, std.functional, std.traits;
FP calc(FP, F)(in F fun, in int n) pure nothrow if (isCallable!F) {
FP temp = 0;
foreach_reverse (immutable ni; 1 .. n + 1) {
immutable p = fun(ni);
temp = p[1] / (FP(p[0]) + temp);
}
return fun(0)[0] + temp;
}
int[2] fSqrt2(in int n) pure nothrow {
return [n > 0 ? 2 : 1, 1];
}
int[2] fNapier(in int n) pure nothrow {
return [n > 0 ? n : 2, n > 1 ? (n - 1) : 1];
}
int[2] fPi(in int n) pure nothrow {
return [n > 0 ? 6 : 3, (2 * n - 1) ^^ 2];
}
alias print = curry!(writefln, "%.19f");
void main() {
calc!real(&fSqrt2, 200).print;
calc!real(&fNapier, 200).print;
calc!real(&fPi, 200).print;
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | def string = 'Scooby-doo-bee-doo' // assigns string object to a variable reference
def stringRef = string // assigns another variable reference to the same object
def stringCopy = new String(string) // copies string value into a new object, and assigns to a third variable reference |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #GUISS | GUISS | Start.Programs,Accessories,Notepad,
Type:Hello world[pling],Highlight:Hello world[pling],
Menu,Edit,Copy,Menu,Edit,Paste |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #BASIC | BASIC | graphsize 31, 31
for i = 1 to 100
do
x = int(rand * 30) - 15
y = int(rand * 30) - 15
r = sqr(x*x + y*y)
until 10 <= r and r <= 15
color rgb(255, 0, 0)
plot(x+15, y+15)
next i
end |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
#include <tuple>
typedef std::tuple<int, int> point;
std::ostream& print(std::ostream& os, const point& p) {
return os << "(" << std::get<0>(p) << ", " << std::get<1>(p) << ")";
}
std::ostream& print(std::ostream& os, const std::vector<point>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
print(os, *it);
it = std::next(it);
}
while (it != end) {
os << ", ";
print(os, *it);
it = std::next(it);
}
return os << "]";
}
// returns true if the three points make a counter-clockwise turn
bool ccw(const point& a, const point& b, const point& c) {
return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))
> ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));
}
std::vector<point> convexHull(std::vector<point> p) {
if (p.size() == 0) return std::vector<point>();
std::sort(p.begin(), p.end(), [](point& a, point& b){
if (std::get<0>(a) < std::get<0>(b)) return true;
return false;
});
std::vector<point> h;
// lower hull
for (const auto& pt : p) {
while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
h.pop_back();
}
h.push_back(pt);
}
// upper hull
auto t = h.size() + 1;
for (auto it = p.crbegin(); it != p.crend(); it = std::next(it)) {
auto pt = *it;
while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
h.pop_back();
}
h.push_back(pt);
}
h.pop_back();
return h;
}
int main() {
using namespace std;
vector<point> points = {
make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),
make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),
make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),
make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)
};
auto hull = convexHull(points);
auto it = hull.cbegin();
auto end = hull.cend();
cout << "Convex Hull: ";
print(cout, hull);
cout << endl;
return 0;
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #F.23 | F# | open System
let convert seconds =
let span = TimeSpan.FromSeconds(seconds |> float)
let (wk, day) = Math.DivRem(span.Days, 7)
let parts =
[(wk, "wk"); (day, "day"); (span.Hours, "hr"); (span.Minutes, "min"); (span.Seconds, "sec")]
let result =
List.foldBack (fun (n, u) acc ->
(if n > 0 then n.ToString() + " " + u else "")
+ (if n > 0 && acc.Length > 0 then ", " else "")
+ acc
) parts ""
if result.Length > 0 then result else "0 sec"
[<EntryPoint>]
let main argv =
argv
|> Seq.map (fun str -> let sec = UInt32.Parse str in (sec, convert sec))
|> Seq.iter (fun (s, v) -> printfn "%10i = %s" s v)
0 |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Ruby | Ruby | require "prime"
limit = 1_000_000
puts "First found longest run of ascending prime gaps up to #{limit}:"
p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq
puts "\nFirst found longest run of descending prime gaps up to #{limit}:"
p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 > j2-i2 }.max_by(&:size).flatten.uniq |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Rust | Rust | // [dependencies]
// primal = "0.3"
fn print_diffs(vec: &[usize]) {
for i in 0..vec.len() {
if i > 0 {
print!(" ({}) ", vec[i] - vec[i - 1]);
}
print!("{}", vec[i]);
}
println!();
}
fn main() {
let limit = 1000000;
let mut asc = Vec::new();
let mut desc = Vec::new();
let mut max_asc = Vec::new();
let mut max_desc = Vec::new();
let mut max_asc_len = 0;
let mut max_desc_len = 0;
for p in primal::Sieve::new(limit)
.primes_from(2)
.take_while(|x| *x < limit)
{
let alen = asc.len();
if alen > 1 && p - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2] {
asc = asc.split_off(alen - 1);
}
asc.push(p);
if asc.len() >= max_asc_len {
if asc.len() > max_asc_len {
max_asc_len = asc.len();
max_asc.clear();
}
max_asc.push(asc.clone());
}
let dlen = desc.len();
if dlen > 1 && p - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2] {
desc = desc.split_off(dlen - 1);
}
desc.push(p);
if desc.len() >= max_desc_len {
if desc.len() > max_desc_len {
max_desc_len = desc.len();
max_desc.clear();
}
max_desc.push(desc.clone());
}
}
println!("Longest run(s) of ascending prime gaps up to {}:", limit);
for v in max_asc {
print_diffs(&v);
}
println!("\nLongest run(s) of descending prime gaps up to {}:", limit);
for v in max_desc {
print_diffs(&v);
}
} |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Sidef | Sidef | func runs(f, arr) {
var run = 0
var diff = 0
var diffs = []
arr.each_cons(2, {|p1,p2|
var curr_diff = (p2 - p1)
f(curr_diff, diff) ? ++run : (run = 1)
diff = curr_diff
diffs << run
})
var max = diffs.max
var runs = []
diffs.indices_by { _ == max }.each {|i|
runs << arr.slice(i - max + 1, i + 1)
}
return runs
}
var limit = 1e6
var primes = limit.primes
say "Longest run(s) of ascending prime gaps up to #{limit.commify}:"
say runs({|a,b| a > b }, primes).join("\n")
say "\nLongest run(s) of descending prime gaps up to #{limit.commify}:"
say runs({|a,b| a < b }, primes).join("\n") |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Erlang | Erlang |
-module(continued).
-compile([export_all]).
pi_a (0) -> 3;
pi_a (_N) -> 6.
pi_b (N) ->
(2*N-1)*(2*N-1).
sqrt2_a (0) ->
1;
sqrt2_a (_N) ->
2.
sqrt2_b (_N) ->
1.
nappier_a (0) ->
2;
nappier_a (N) ->
N.
nappier_b (1) ->
1;
nappier_b (N) ->
N-1.
continued_fraction(FA,_FB,0) -> FA(0);
continued_fraction(FA,FB,N) ->
continued_fraction(FA,FB,N-1,FB(N)/FA(N)).
continued_fraction(FA,_FB,0,Acc) -> FA(0) + Acc;
continued_fraction(FA,FB,N,Acc) ->
continued_fraction(FA,FB,N-1,FB(N)/ (FA(N) + Acc)).
test_pi (N) ->
continued_fraction(fun pi_a/1,fun pi_b/1,N).
test_sqrt2 (N) ->
continued_fraction(fun sqrt2_a/1,fun sqrt2_b/1,N).
test_nappier (N) ->
continued_fraction(fun nappier_a/1,fun nappier_b/1,N).
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Harbour | Harbour | cSource := "Hello World"
cDestination := cSource |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | src = "Hello World"
dst = src |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #C | C | #include <stdio.h>
#include <stdlib.h>
inline
int randn(int m)
{
int rand_max = RAND_MAX - (RAND_MAX % m);
int r;
while ((r = rand()) > rand_max);
return r / (rand_max / m);
}
int main()
{
int i, x, y, r2;
unsigned long buf[31] = {0}; /* could just use 2d array */
for (i = 0; i < 100; ) {
x = randn(31) - 15;
y = randn(31) - 15;
r2 = x * x + y * y;
if (r2 >= 100 && r2 <= 225) {
buf[15 + y] |= 1 << (x + 15);
i++;
}
}
for (y = 0; y < 31; y++) {
for (x = 0; x < 31; x++)
printf((buf[y] & 1 << x) ? ". " : " ");
printf("\n");
}
return 0;
} |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Common_Lisp | Common Lisp | #!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp(ql:quickload '() :silent t)
)
(defpackage :ros.script.convex-hull-task.3861520611
(:use :cl))
(in-package :ros.script.convex-hull-task.3861520611)
;;;
;;; Convex hulls by Andrew's monotone chain algorithm.
;;;
;;; For a description of the algorithm, see
;;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169
;;;
;;; This program is translated rather faithfully from the Scheme,
;;; complete with tail recursions.
;;;
;; x and y coordinates of a "point". A "point" is represented by a
;; list of length 2.
(defun x@ (u) (car u))
(defun y@ (u) (cadr u))
(defun cross (u v)
;; Cross product (as a signed scalar).
(- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))
(defun point- (u v)
(list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))
(defun sort-points-vector (points-vector)
;; Ascending sort on x-coordinates, followed by ascending sort
;; on y-coordinates.
(sort points-vector #'(lambda (u v)
(or (< (x@ u) (x@ v))
(and (= (x@ u) (x@ v))
(< (y@ u) (y@ v)))))))
(defun construct-lower-hull (sorted-points-vector)
(let* ((pt sorted-points-vector)
(n (length pt))
(hull (make-array n))
(j 1))
(setf (aref hull 0) (aref pt 0))
(setf (aref hull 1) (aref pt 1))
(loop for i from 2 to (1- n)
do (progn
(defun inner-loop ()
(if (or (zerop j)
(plusp
(cross (point- (aref hull j)
(aref hull (1- j)))
(point- (aref pt i)
(aref hull (1- j))))))
(progn
(setf j (1+ j))
(setf (aref hull j) (aref pt i)))
(progn
(setf j (1- j))
(inner-loop))))
(inner-loop)))
(values (+ j 1) hull))) ; Hull size, hull points.
(defun construct-upper-hull (sorted-points-vector)
(let* ((pt sorted-points-vector)
(n (length pt))
(hull (make-array n))
(j 1))
(setf (aref hull 0) (aref pt (- n 1)))
(setf (aref hull 1) (aref pt (- n 2)))
(loop for i from (- n 3) downto 0
do (progn
(defun inner-loop ()
(if (or (zerop j)
(plusp
(cross (point- (aref hull j)
(aref hull (1- j)))
(point- (aref pt i)
(aref hull (1- j))))))
(progn
(setf j (1+ j))
(setf (aref hull j) (aref pt i)))
(progn
(setf j (1- j))
(inner-loop))))
(inner-loop)))
(values (+ j 1) hull))) ; Hull size, hull points.
(defun construct-hull (sorted-points-vector)
;; Notice that the lower and upper hulls could be constructed in
;; parallel. (The Scheme "let-values" macro made this apparent,
;; despite not actually doing the computation in parallel. The
;; coding here makes it less obvious.)
(multiple-value-bind (lower-hull-size lower-hull)
(construct-lower-hull sorted-points-vector)
(multiple-value-bind (upper-hull-size upper-hull)
(construct-upper-hull sorted-points-vector)
(let* ((hull-size (+ lower-hull-size upper-hull-size -2))
(hull (make-array hull-size)))
(loop for i from 0 to (- lower-hull-size 2)
do (setf (aref hull i) (aref lower-hull i)))
(loop for i from 0 to (- upper-hull-size 2)
do (setf (aref hull (+ i (1- lower-hull-size)))
(aref upper-hull i)))
hull))))
(defun vector-delete-neighbor-dups (elt= v)
;; A partial clone of the SRFI-132 procedure of the same name. This
;; implementation is similar to the reference implementation for
;; SRFI-132, and may use a bunch of stack space. That reference
;; implementation is by Olin Shivers and rests here:
;; https://github.com/scheme-requests-for-implementation/srfi-132/blob/master/sorting/delndups.scm
;; The license is:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This code is
;;; Copyright (c) 1998 by Olin Shivers.
;;; The terms are: You may do as you please with this code, as long as
;;; you do not delete this notice or hold me responsible for any outcome
;;; related to its use.
;;;
;;; Blah blah blah. Don't you think source files should contain more lines
;;; of code than copyright notice?
;;;
(let ((start 0)
(end (length v)))
(let ((x (aref v start)))
(defun recur (x i j)
(if (< i end)
(let ((y (aref v i))
(nexti (1+ i)))
(if (funcall elt= x y)
(recur x nexti j)
(let ((ansvec (recur y nexti (1+ j))))
(setf (aref ansvec j) y)
ansvec)))
(make-array j)))
(let ((ans (recur x start 1)))
(setf (aref ans 0) x)
ans))))
(defun vector-convex-hull (points)
(let* ((points-vector (coerce points 'vector))
(sorted-points-vector
(vector-delete-neighbor-dups
#'equalp
(sort-points-vector points-vector))))
(if (<= (length sorted-points-vector) 2)
sorted-points-vector
(construct-hull sorted-points-vector))))
(defun list-convex-hull (points)
(coerce (vector-convex-hull points) 'list))
(defconstant example-points
'((16 3) (12 17) (0 6) (-4 -6) (16 6)
(16 -7) (16 -3) (17 -4) (5 19) (19 -8)
(3 16) (12 13) (3 -4) (17 5) (-3 15)
(-3 -9) (0 11) (-9 -3) (-4 -2) (12 10)))
(defun main (&rest argv)
(declare (ignorable argv))
(write (list-convex-hull example-points))
(terpri))
;;; vim: set ft=lisp lisp: |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Factor | Factor | USING: assocs io kernel math math.parser qw sequences
sequences.generalizations ;
: mod/ ( x y -- w z ) /mod swap ;
: convert ( n -- seq )
60 mod/ 60 mod/ 24 mod/ 7 mod/ 5 narray reverse ;
: .time ( n -- )
convert [ number>string ] map qw{ wk d hr min sec } zip
[ first "0" = ] reject [ " " join ] map ", " join print ;
7259 86400 6000000 [ .time ] tri@ |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #Wren | Wren | import "/math" for Int
var LIMIT = 999999
var primes = Int.primeSieve(LIMIT)
var longestSeq = Fn.new { |dir|
var pd = 0
var longSeqs = [[2]]
var currSeq = [2]
for (i in 1...primes.count) {
var d = primes[i] - primes[i-1]
if ((dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd)) {
if (currSeq.count > longSeqs[0].count) {
longSeqs = [currSeq]
} else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)
currSeq = [primes[i-1], primes[i]]
} else {
currSeq.add(primes[i])
}
pd = d
}
if (currSeq.count > longSeqs[0].count) {
longSeqs = [currSeq]
} else if (currSeq.count == longSeqs[0].count) longSeqs.add(currSeq)
System.print("Longest run(s) of primes with %(dir) differences is %(longSeqs[0].count):")
for (ls in longSeqs) {
var diffs = []
for (i in 1...ls.count) diffs.add(ls[i] - ls[i-1])
for (i in 0...ls.count-1) System.write("%(ls[i]) (%(diffs[i])) ")
System.print(ls[-1])
}
System.print()
}
System.print("For primes < 1 million:\n")
for (dir in ["ascending", "descending"]) longestSeq.call(dir) |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #F.23 | F# |
// I provide four functions:-
// cf2S general purpose continued fraction to sequence of float approximations
// cN2S Normal continued fractions (a-series always 1)
// cfSqRt uses cf2S to calculate sqrt of float
// π takes a sequence of b values returning the next until the list is exhausted after which it injects infinity
// Nigel Galloway: December 19th., 2018
let cf2S α β=let n0,g1,n1,g2=β(),α(),β(),β()
seq{let (Π:decimal)=g1/n1 in yield n0+Π; yield! Seq.unfold(fun(n,g,Π)->let a,b=α(),β() in let Π=Π*g/n in Some(n0+Π,(b+a/n,b+a/g,Π)))(g2+α()/n1,g2,Π)}
let cN2S = cf2S (fun()->1M)
let cfSqRt n=(cf2S (fun()->n-1M) (let mutable n=false in fun()->if n then 2M else (n<-true; 1M)))
let π n=let mutable π=n in (fun ()->match π with h::t->π<-t; h |_->9999999999999999999999999999M)
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #HicEst | HicEst | src = "Hello World"
dst = src |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #i | i | //Strings are immutable in 'i'.
software {
a = "Hello World"
b = a //This copies the string.
a += "s"
print(a)
print(b)
}
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #C.23 | C# | using System;
using System.Diagnostics;
using System.Drawing;
namespace RosettaConstrainedRandomCircle
{
class Program
{
static void Main(string[] args)
{
var points = new Point[404];
int i = 0;
for (int y = -15; y <= 15; y++)
for (int x = -15; x <= 15 && i < 404; x++)
{
var c = Math.Sqrt(x * x + y * y);
if (10 <= c && c <= 15)
{
points[i++] = new Point(x, y);
}
}
var bm = new Bitmap(600, 600);
var g = Graphics.FromImage(bm);
var brush = new SolidBrush(Color.Magenta);
var r = new System.Random();
for (int count = 0; count < 100; count++)
{
var p = points[r.Next(404)];
g.FillEllipse(brush, new Rectangle(290 + 19 * p.X, 290 + 19 * p.Y, 10, 10));
}
const string filename = "Constrained Random Circle.png";
bm.Save(filename);
Process.Start(filename);
}
}
} |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #D | D | import std.algorithm.sorting;
import std.stdio;
struct Point {
int x;
int y;
int opCmp(Point rhs) {
if (x < rhs.x) return -1;
if (rhs.x < x) return 1;
return 0;
}
void toString(scope void delegate(const(char)[]) sink) const {
import std.format;
sink("(");
formattedWrite(sink, "%d", x);
sink(",");
formattedWrite(sink, "%d", y);
sink(")");
}
}
Point[] convexHull(Point[] p) {
if (p.length == 0) return [];
p.sort;
Point[] h;
// lower hull
foreach (pt; p) {
while (h.length >= 2 && !ccw(h[$-2], h[$-1], pt)) {
h.length--;
}
h ~= pt;
}
// upper hull
auto t = h.length + 1;
foreach_reverse (i; 0..(p.length - 1)) {
auto pt = p[i];
while (h.length >= t && !ccw(h[$-2], h[$-1], pt)) {
h.length--;
}
h ~= pt;
}
h.length--;
return h;
}
/* ccw returns true if the three points make a counter-clockwise turn */
auto ccw(Point a, Point b, Point c) {
return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x));
}
void main() {
auto points = [
Point(16, 3), Point(12, 17), Point( 0, 6), Point(-4, -6), Point(16, 6),
Point(16, -7), Point(16, -3), Point(17, -4), Point( 5, 19), Point(19, -8),
Point( 3, 16), Point(12, 13), Point( 3, -4), Point(17, 5), Point(-3, 15),
Point(-3, -9), Point( 0, 11), Point(-9, -3), Point(-4, -2), Point(12, 10)
];
auto hull = convexHull(points);
writeln("Convex Hull: ", hull);
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Forth | Forth | CREATE C 0 ,
: ., C @ IF ." , " THEN 1 C ! ;
: .TIME ( n --)
[ 60 60 24 7 * * * ]L /MOD ?DUP-IF ., . ." wk" THEN
[ 60 60 24 * * ]L /MOD ?DUP-IF ., . ." d" THEN
[ 60 60 * ]L /MOD ?DUP-IF ., . ." hr" THEN
[ 60 ]L /MOD ?DUP-IF ., . ." min" THEN
?DUP-IF ., . ." sec" THEN 0 C ! ; |
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences | Consecutive primes with ascending or descending differences | Task
Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.
Do the same for sequences of primes where the differences are strictly descending.
In both cases, show the sequence for primes < 1,000,000.
If there are multiple sequences of the same length, only the first need be shown.
| #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N > 2 is a prime number
int N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
proc ShowSeq(Dir, Str); \Show longest sequence of distances between primes
int Dir, Str;
int Count, MaxCount, N, P, P0, D, D0, I, AP(1000), MaxAP(1000);
[Count:= 0; MaxCount:= 0;
P0:= 2; D0:= 0; \preceding prime and distance
AP(Count):= P0; Count:= Count+1;
for N:= 3 to 1_000_000-1 do
if IsPrime(N) then
[P:= N; \got a prime number
D:= P - P0; \distance from preceding prime
if D*Dir > D0*Dir then
[AP(Count):= P; Count:= Count+1;
if Count > MaxCount then \save best sequence
[MaxCount:= Count;
for I:= 0 to MaxCount-1 do
MaxAP(I):= AP(I);
];
]
else
[Count:= 0; \restart sequence
AP(Count):= P0; Count:= Count+1; \possible beginning
AP(Count):= P; Count:= Count+1;
];
P0:= P; D0:= D;
];
Text(0, "Longest sequence of "); Text(0, Str);
Text(0, " distances between primes: "); IntOut(0, MaxCount); CrLf(0);
for I:= 0 to MaxCount-2 do
[IntOut(0, MaxAP(I));
Text(0, " (");
IntOut(0, MaxAP(I+1) - MaxAP(I));
Text(0, ") ");
];
IntOut(0, MaxAP(I)); CrLf(0);
];
[ShowSeq(+1, "ascending"); \main
ShowSeq(-1, "descending");
] |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #ALGOL_68 | ALGOL 68 | BEGIN # find composite k with no single digit factors whose factors are all substrings of k #
# returns TRUE if the string representation of f is a substring of k str, FALSE otherwise #
PROC is substring = ( STRING k str, INT f )BOOL:
BEGIN
STRING f str = whole( f, 0 );
INT f len = ( UPB f str - LWB f str ) + 1;
BOOL result := FALSE;
INT f end := ( LWB k str + f len ) - 2;
FOR f pos FROM LWB k str TO ( UPB k str + 1 ) - f len WHILE NOT result DO
f end +:= 1;
result := k str[ f pos : f end ] = f str
OD;
result
END # is substring # ;
# task #
INT required numbers = 20;
INT k count := 0;
# k must be odd and > 9 #
FOR k FROM 11 BY 2 WHILE k count < required numbers DO
IF k MOD 3 /= 0 AND k MOD 5 /= 0 AND k MOD 7 /= 0 THEN
# no single digit odd prime factors #
BOOL is candidate := TRUE;
STRING k str = whole( k, 0 );
INT v := k;
INT f count := 0;
FOR f FROM 11 BY 2 TO ENTIER sqrt( k ) + 1 WHILE v > 1 AND is candidate DO
IF v MOD f = 0 THEN
# have a factor #
is candidate := is substring( k str, f );
IF is candidate THEN
# the digits of f ae a substring of v #
WHILE v OVERAB f;
f count +:= 1;
v MOD f = 0
DO SKIP OD
FI
FI
OD;
IF is candidate AND ( f count > 1 OR ( v /= k AND v > 1 ) ) THEN
# have a composite whose factors are up to the root are substrings #
IF v > 1 THEN
# there was a factor > the root #
is candidate := is substring( k str, v )
FI;
IF is candidate THEN
print( ( " ", whole( k, -8 ) ) );
k count +:= 1;
IF k count MOD 10 = 0 THEN print( ( newline ) ) FI
FI
FI
FI
OD
END |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Factor | Factor | USING: arrays combinators io kernel locals math math.functions
math.ranges prettyprint sequences ;
IN: rosetta.cfrac
! Every continued fraction must implement these two words.
GENERIC: cfrac-a ( n cfrac -- a )
GENERIC: cfrac-b ( n cfrac -- b )
! square root of 2
SINGLETON: sqrt2
M: sqrt2 cfrac-a
! If n is 1, then a_n is 1, else a_n is 2.
drop { { 1 [ 1 ] } [ drop 2 ] } case ;
M: sqrt2 cfrac-b
! Always b_n is 1.
2drop 1 ;
! Napier's constant
SINGLETON: napier
M: napier cfrac-a
! If n is 1, then a_n is 2, else a_n is n - 1.
drop { { 1 [ 2 ] } [ 1 - ] } case ;
M: napier cfrac-b
! If n is 1, then b_n is 1, else b_n is n - 1.
drop { { 1 [ 1 ] } [ 1 - ] } case ;
SINGLETON: pi
M: pi cfrac-a
! If n is 1, then a_n is 3, else a_n is 6.
drop { { 1 [ 3 ] } [ drop 6 ] } case ;
M: pi cfrac-b
! Always b_n is (n * 2 - 1)^2.
drop 2 * 1 - 2 ^ ;
:: cfrac-estimate ( cfrac terms -- number )
terms cfrac cfrac-a ! top = last a_n
terms 1 - 1 [a,b] [ :> n
n cfrac cfrac-b swap / ! top = b_n / top
n cfrac cfrac-a + ! top = top + a_n
] each ;
:: decimalize ( rational prec -- string )
rational 1 /mod ! split whole, fractional parts
prec 10^ * ! multiply fraction by 10 ^ prec
[ >integer unparse ] bi@ ! convert digits to strings
:> fraction
"." ! push decimal point
prec fraction length -
dup 0 < [ drop 0 ] when
"0" <repetition> concat ! push padding zeros
fraction 4array concat ;
<PRIVATE
: main ( -- )
" Square root of 2: " write
sqrt2 50 cfrac-estimate 30 decimalize print
"Napier's constant: " write
napier 50 cfrac-estimate 30 decimalize print
" Pi: " write
pi 950 cfrac-estimate 10 decimalize print ;
PRIVATE>
MAIN: main |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Icon_and_Unicon | Icon and Unicon | procedure main()
a := "qwerty"
b := a
b[2+:4] := "uarterl"
write(a," -> ",b)
end |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | src =: 'hello'
dest =: src |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #C.2B.2B | C++ |
#include <windows.h>
#include <list>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class point
{
public:
int x, y;
point() { x = y = 0; }
point( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
};
//--------------------------------------------------------------------------------------------------
class rndCircle
{
public:
void draw()
{
createPoints();
drawPoints();
}
private:
void createPoints()
{
point pt;
for( int x = 0; x < 200; x++ )
{
int a, b, c;
while( true )
{
a = rand() % 31 - 15;
b = rand() % 31 - 15;
c = a * a + b * b;
if( c >= 100 && c <= 225 ) break;
}
pt.set( a, b );
_ptList.push_back( pt );
}
}
void drawPoints()
{
HDC dc = GetDC( GetConsoleWindow() );
for( list<point>::iterator it = _ptList.begin(); it != _ptList.end(); it++ )
SetPixel( dc, 300 + 10 * ( *it ).x, 300 + 10 * ( *it ).y, RGB( 255, 255, 0 ) );
}
list<point> _ptList;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
rndCircle c;
c.draw();
system( "pause" );
return 0;
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Delphi | Delphi |
program ConvexHulls;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Types,
System.SysUtils,
System.Generics.Defaults,
System.Generics.Collections;
function Ccw(const a, b, c: TPoint): Boolean;
begin
Result := ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X));
end;
function ConvexHull(const p: TList<TPoint>): TList<TPoint>;
var
pt: TPoint;
i, t: Integer;
begin
Result := TList<TPoint>.Create;
if (p.Count = 0) then Exit;
p.Sort(TComparer<TPoint>.Construct(
function(const Left, Right: TPoint): Integer
begin
Result := Left.X - Right.X;
end
));
// lower hull
for i := 0 to p.Count-1 do
begin
pt := p[i];
while ((Result.Count >= 2) and (not Ccw(Result[Result.Count - 2], Result[Result.Count - 1], pt))) do
begin
Result.Delete(Result.Count - 1);
end;
Result.Add(pt);
end;
// upper hull
t := Result.Count + 1;
for i := p.Count-1 downto 0 do
begin
pt := p[i];
while ((Result.Count >= t) and (not Ccw(Result[Result.Count - 2], Result[Result.Count - 1], pt))) do
begin
Result.Delete(Result.Count - 1);
end;
Result.Add(pt);
end;
Result.Delete(Result.Count - 1);
end;
var
points: TList<TPoint>;
hull: TList<TPoint>;
i: Integer;
begin
hull := nil;
points := TList<TPoint>.Create;
try
points.AddRange([
Point(16, 3),
Point(12, 17),
Point(0, 6),
Point(-4, -6),
Point(16, 6),
Point(16, -7),
Point(16, -3),
Point(17, -4),
Point(5, 19),
Point(19, -8),
Point(3, 16),
Point(12, 13),
Point(3, -4),
Point(17, 5),
Point(-3, 15),
Point(-3, -9),
Point(0, 11),
Point(-9, -3),
Point(-4, -2),
Point(12, 10)
]);
hull := ConvexHull(points);
// Output the result
Write('Convex Hull: [');
for i := 0 to hull.Count-1 do
begin
if (i > 0) then Write(', ');
Write(Format('(%d, %d)', [hull[i].X, hull[i].Y]));
end;
WriteLn(']');
finally
hull.Free;
points.Free;
end;
end.
|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Fortran | Fortran |
SUBROUTINE PROUST(T) !Remembrance of time passed.
INTEGER T !The time, in seconds. Positive only, please.
INTEGER NTYPES !How many types of time?
PARAMETER (NTYPES = 5) !This should do.
INTEGER USIZE(NTYPES) !Size of the time unit.
CHARACTER*3 UNAME(NTYPES)!Name of the time unit.
PARAMETER (USIZE = (/7*24*60*60, 24*60*60, 60*60, 60, 1/)) !The compiler does some arithmetic.
PARAMETER (UNAME = (/ "wk", "d", "hr","min","sec"/)) !Approved names, with trailing spaces.
CHARACTER*28 TEXT !A scratchpad.
INTEGER I,L,N,S !Assistants.
S = T !A copy I can mess with.
L = 0 !No text has been generated.
DO I = 1,NTYPES !Step through the types to do so.
N = S/USIZE(I) !Largest first.
IF (N.GT.0) THEN !Above the waterline?
S = S - N*USIZE(I) !Yes! Remove its contribution.
IF (L.GT.0) THEN !Is this the first text to be rolled?
L = L + 2 !No.
TEXT(L - 1:L) = ", " !Cough forth some punctuation.
END IF !Now ready for this count.
WRITE (TEXT(L + 1:),1) N,UNAME(I) !Place, with the unit name.
1 FORMAT (I0,1X,A) !I0 means I only: variable-length, no leading spaces.
L = LEN_TRIM(TEXT) !Find the last non-blank resulting.
END IF !Since I'm not keeping track.
END DO !On to the next unit.
Cast forth the result.
WRITE (6,*) T,">",TEXT(1:L),"<" !With annotation.
END !Simple enough with integers.
PROGRAM MARCEL !Stir the cup.
CALL PROUST(7259)
CALL PROUST(7260)
CALL PROUST(86400)
CALL PROUST(6000000)
CALL PROUST(0)
CALL PROUST(-666)
END
|
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Arturo | Arturo | valid?: function [n][
pf: factors.prime n
every? pf 'f ->
and? [contains? to :string n to :string f]
[1 <> size digits f]
]
cnt: 0
i: new 3
while [cnt < 10][
if and? [not? prime? i][valid? i][
print i
cnt: cnt + 1
]
'i + 2
] |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #F.23 | F# |
// Composite numbers k with no single digit factors whose factors are all substrings of k. Nigel Galloway: January 28th., 2022
let fG n g=let rec fN i g e l=match i<g,g=0L,i%10L=g%10L with (true,_,_)->false |(_,true,_)->true |(_,_,true)->fN(i/10L)(g/10L) e l |_->fN l e e (l/10L) in fN n g g (n/10L)
let fN(g:int64)=Open.Numeric.Primes.Prime.Factors g|>Seq.skip 1|>Seq.distinct|>Seq.forall(fun n->fG g n)
Seq.unfold(fun n->Some(n|>List.filter(fun(n:int64)->not(Open.Numeric.Primes.Prime.Numbers.IsPrime &n) && fN n),n|>List.map((+)210L)))([1L..2L..209L]
|>List.filter(fun n->n%3L>0L && n%5L>0L && n%7L>0L))|>Seq.concat|>Seq.skip 1|>Seq.take 20|>Seq.iter(printfn "%d")
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Felix | Felix | fun pi (n:int) : (double*double) =>
let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in
let b = pow(2.0 * n.double - 1.0, 2.0) in
(a,b);
fun sqrt_2 (n:int) : (double*double) =>
let a = match n with | 0 => 1.0 | _ => 2.0 endmatch in
let b = 1.0 in
(a,b);
fun napier (n:int) : (double*double) =>
let a = match n with | 0 => 2.0 | _ => n.double endmatch in
let b = match n with | 1 => 1.0 | _ => (n.double - 1.0) endmatch in
(a,b);
fun cf_iter (steps:int) (f:int -> double*double) = {
var acc = 0.0;
for var n in steps downto 0 do
var a, b = f(n);
acc = if (n > 0) then (b / (a + acc)) else (acc + a);
done
return acc;
}
println$ cf_iter 200 sqrt_2; // => 1.41421
println$ cf_iter 200 napier; // => 2.71818
println$ cf_iter 1000 pi; // => 3.14159 |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Forth | Forth | : fsqrt2 1 s>f 0> if 2 s>f else fdup then ;
: fnapier dup dup 1 > if 1- else drop 1 then s>f dup 1 < if drop 2 then s>f ;
: fpi dup 2* 1- dup * s>f 0> if 6 else 3 then s>f ;
( n -- f1 f2)
: cont.fraction ( xt n -- f)
1 swap 1+ 0 s>f \ calculate for 1 .. n
do i over execute frot f+ f/ -1 +loop
0 swap execute fnip f+ \ calcucate for 0
; |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | String src = "Hello";
String newAlias = src;
String strCopy = new String(src);
//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy.equals(src)" is true |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | var container = {myString: "Hello"};
var containerCopy = container; // Now both identifiers refer to the same object
containerCopy.myString = "Goodbye"; // container.myString will also return "Goodbye" |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Clojure | Clojure | (ns rosettacode.circle-random-points
(:import [java.awt Color Graphics Dimension]
[javax.swing JFrame JPanel]))
(let [points (->> (for [x (range -15 16), y (range -15 16)
:when (<= 10 (Math/hypot x y) 15)]
[(+ x 15) (+ y 15)])
shuffle
(take 100))]
(doto (JFrame.)
(.add (doto (proxy [JPanel] []
(paint [^Graphics g]
(doseq [[x y] points]
(.fillRect g (* 10 x) (* 10 y) 10 10))))
(.setPreferredSize (Dimension. 310 310))))
(.setResizable false)
(.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
.pack
.show)) |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #F.23 | F# | open System
type Point =
struct
val X : int
val Y : int
new (x : int, y : int ) = {X = x; Y = y}
end
let (poly : Point list) = [ Point(16, 3); Point(12, 17); Point( 0, 6); Point(-4, -6); Point(16, 6);
Point(16, -7); Point(16, -3); Point(17, -4); Point( 5, 19); Point(19, -8);
Point( 3, 16); Point(12, 13); Point( 3, -4); Point(17, 5); Point(-3, 15);
Point(-3, -9); Point( 0, 11); Point(-9, -3); Point(-4, -2); Point(12, 10)]
let affiche (lst : Point list) =
let mutable (str : string) = List.fold (fun acc (p : Point) -> acc + sprintf "(%d, %d) " p.X p.Y) "Convex Hull: [" lst
printfn "%s" (str.[0.. str.Length - 2] + "]")
let ccw (p1 : Point) (p2 : Point) (p3 : Point) =
(p2.X - p1.X) * (p3.Y - p1.Y) > (p2.Y - p1.Y) * (p3.X - p1.X)
let convexHull (poly : Point list) =
let mutable (outHull : Point list) = List.Empty
let mutable (k : int) = 0
for p in poly do
while k >= 2 && not (ccw outHull.[k-2] outHull.[k-1] p) do
k <- k - 1
if k >= outHull.Length
then outHull <- outHull @ [p]
else outHull <- outHull.[0..k - 1] @ [p]
k <- k + 1
let (t : int) = k + 1
for p in List.rev poly do
while k >= t && not (ccw outHull.[k-2] outHull.[k-1] p) do
k <- k - 1
if k >= outHull.Length
then outHull <- outHull @ [p]
else outHull <- outHull.[0..k - 1] @ [p]
k <- k + 1
outHull.[0 .. k - 2]
affiche (convexHull (List.sortBy (fun (x : Point) -> x.X, x.Y) poly))
|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #FreeBASIC | FreeBASIC | 'FreeBASIC version 1.05 32/64 bit
Sub Show(m As Long)
Dim As Long c(1 To 5)={604800,86400,3600,60,1}
Dim As String g(1 To 5)={" Wk"," d"," hr"," min"," sec"},comma
Dim As Long b(1 To 5),flag,m2=m
Redim As Long s(0)
For n As Long=1 To 5
If m>=c(n) Then
Do
Redim Preserve s(Ubound(s)+1)
s(Ubound(s))=c(n)
m=m-c(n)
Loop Until m<c(n)
End If
Next n
For n As Long=1 To Ubound(s)
For m As Long=1 To 5
If s(n)=c(m) Then b(m)+=1
Next m
Next n
Print m2;" seconds = ";
For n As Long=1 To 5
If b(n) Then: comma=Iif(n<5 Andalso b(n+1),","," and"):flag+=1
If flag=1 Then comma=""
Print comma;b(n);g(n);
End If
Next
Print
End Sub
#define seconds
Show 7259 seconds
Show 86400 seconds
Show 6000000 seconds
sleep |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Go | Go | package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func main() {
count := 0
k := 11 * 11
var res []int
for count < 20 {
if k%3 == 0 || k%5 == 0 || k%7 == 0 {
k += 2
continue
}
factors := rcu.PrimeFactors(k)
if len(factors) > 1 {
s := strconv.Itoa(k)
includesAll := true
prev := -1
for _, f := range factors {
if f == prev {
continue
}
fs := strconv.Itoa(f)
if strings.Index(s, fs) == -1 {
includesAll = false
break
}
}
if includesAll {
res = append(res, k)
count++
}
}
k += 2
}
for _, e := range res[0:10] {
fmt.Printf("%10s ", rcu.Commatize(e))
}
fmt.Println()
for _, e := range res[10:20] {
fmt.Printf("%10s ", rcu.Commatize(e))
}
fmt.Println()
} |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #J | J | */2 3 5 7
210
#1+I.0=+/|:4 q:1+i.210
48 |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Fortran | Fortran | module continued_fractions
implicit none
integer, parameter :: long = selected_real_kind(7,99)
type continued_fraction
integer :: a0, b1
procedure(series), pointer, nopass :: a, b
end type
interface
pure function series (n)
integer, intent(in) :: n
integer :: series
end function
end interface
contains
pure function define_cf (a0,a,b1,b) result(x)
integer, intent(in) :: a0
procedure(series) :: a
integer, intent(in), optional :: b1
procedure(series), optional :: b
type(continued_fraction) :: x
x%a0 = a0
x%a => a
if ( present(b1) ) then
x%b1 = b1
else
x%b1 = 1
end if
if ( present(b) ) then
x%b => b
else
x%b => const_1
end if
end function define_cf
pure integer function const_1(n)
integer,intent(in) :: n
const_1 = 1
end function
pure real(kind=long) function output(x,iterations)
type(continued_fraction), intent(in) :: x
integer, intent(in) :: iterations
integer :: i
output = x%a(iterations)
do i = iterations-1,1,-1
output = x%a(i) + (x%b(i+1) / output)
end do
output = x%a0 + (x%b1 / output)
end function output
end module continued_fractions
program examples
use continued_fractions
type(continued_fraction) :: sqr2,napier,pi
sqr2 = define_cf(1,a_sqr2)
napier = define_cf(2,a_napier,1,b_napier)
pi = define_cf(3,a=a_pi,b=b_pi)
write (*,*) output(sqr2,10000)
write (*,*) output(napier,10000)
write (*,*) output(pi,10000)
contains
pure integer function a_sqr2(n)
integer,intent(in) :: n
a_sqr2 = 2
end function
pure integer function a_napier(n)
integer,intent(in) :: n
a_napier = n
end function
pure integer function b_napier(n)
integer,intent(in) :: n
b_napier = n-1
end function
pure integer function a_pi(n)
integer,intent(in) :: n
a_pi = 6
end function
pure integer function b_pi(n)
integer,intent(in) :: n
b_pi = (2*n-1)*(2*n-1)
end function
end program examples |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Joy | Joy | "hello" dup |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | def demo:
"abc" as $s # assignment of a string to a variable
| $s as $t # $t points to the same string as $s
| "def" as $s # This $s shadows the previous $s
| $t # $t still points to "abc"
;
demo
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #COBOL | COBOL |
identification division.
program-id. circle.
environment division.
input-output section.
file-control.
select plot-file assign "circle.txt".
data division.
file section.
fd plot-file report plot.
working-storage section.
1 binary.
2 seed pic 9(18).
2 x pic s9(4).
2 y pic s9(4).
2 i pic 9(4).
2 dot-count pic 9(4) value 0.
2 dot-count-save pic 9(4) value 0.
2 temp-points.
3 pic s9(4) occurs 2.
2 xy-table.
3 point-pair occurs 0 to 404 depending dot-count.
4 x-point pic s9(4).
4 y-point pic s9(4).
1 plot-table value all "0".
2 occurs 31.
3 dot pic 9 occurs 31.
1 cur-date-time.
2 yyyymmdd pic 9(8).
2 hh pic 9(2).
2 mm pic 9(2).
2 ss pic 9(2).
1 plot-work.
2 plot-item pic xb occurs 31.
report section.
rd plot.
1 plot-line type de.
2 line plus 1.
3 column is 1 source is plot-work pic x(62).
procedure division.
begin.
perform compute-seed
perform find-all-valid-points
perform shuffle-point-pairs
perform select-100-dots
perform print-dots
stop run
.
find-all-valid-points.
perform varying x from -15 by 1 until x > +15
perform varying y from -15 by 1 until y > +15
if (function sqrt (x ** 2 + y ** 2))
>= 10 and <= 15
then
move 1 to dot (x + 16 y + 16)
add 1 to dot-count
compute x-point (dot-count) = x + 16
compute y-point (dot-count) = y + 16
end-if
end-perform
end-perform
display "Total points: " dot-count
.
shuffle-point-pairs.
move dot-count to dot-count-save
compute i = function random (seed) * dot-count + 1
perform varying dot-count from dot-count by -1
until dot-count < 2
move point-pair (i) to temp-points
move point-pair (dot-count) to point-pair (i)
move temp-points to point-pair (dot-count)
compute i = function random * dot-count + 1
end-perform
move dot-count-save to dot-count
.
select-100-dots.
perform varying i from 1 by 1
until i > 100
compute x = x-point (i)
compute y = y-point (i)
move 2 to dot (x y)
end-perform
.
print-dots.
open output plot-file
initiate plot
perform varying y from 1 by 1 until y > 31
move spaces to plot-work
perform varying x from 1 by 1 until x > 31
if dot (x y) = 2
move "o" to plot-item (x)
end-if
end-perform
generate plot-line
end-perform
terminate plot
close plot-file
.
compute-seed.
unstring function current-date into
yyyymmdd hh mm ss
compute seed =
(function integer-of-date (yyyymmdd) * 86400)
compute seed = seed
+ (hh * 3600) + (mm * 60) + ss
compute seed = function mod (seed 32768)
.
end program circle.
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Fortran | Fortran | module convex_hulls
!
! Convex hulls by Andrew's monotone chain algorithm.
!
! For a description of the algorithm, see
! https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169
!
! For brevity in the task, I shall use the built-in "complex" type
! to represent objects in the plane. One could have fun rewriting
! this implementation in terms of geometric algebra.
!
implicit none
private
public :: find_convex_hull
contains
elemental function x (u)
complex, intent(in) :: u
real :: x
x = real (u)
end function x
elemental function y (u)
complex, intent(in) :: u
real :: y
y = aimag (u)
end function y
elemental function cross (u, v) result (p)
complex, intent(in) :: u, v
real :: p
! The cross product as a signed scalar.
p = (x (u) * y (v)) - (y (u) * x (v))
end function cross
subroutine sort_points (num_points, points)
integer, intent(in) :: num_points
complex, intent(inout) :: points(0:*)
! Sort first in ascending order by x-coordinates, then in
! ascending order by y-coordinates. Any decent sort algorithm will
! suffice; for the sake of interest, here is the Shell sort of
! https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510
integer, parameter :: gaps(1:8) = (/ 701, 301, 132, 57, 23, 10, 4, 1 /)
integer :: i, j, k, gap, offset
complex :: temp
logical :: done
do k = 1, 8
gap = gaps(k)
do offset = 0, gap - 1
do i = offset, num_points - 1, gap
temp = points(i)
j = i
done = .false.
do while (.not. done)
if (j < gap) then
done = .true.
else if (x (points(j - gap)) < x (temp)) then
done = .true.
else if (x (points(j - gap)) == x (temp) .and. &
& (y (points(j - gap)) <= y (temp))) then
done = .true.
else
points(j) = points(j - gap)
j = j - gap
end if
end do
points(j) = temp
end do
end do
end do
end subroutine sort_points
subroutine delete_neighbor_duplicates (n, pt)
integer, intent(inout) :: n
complex, intent(inout) :: pt(0:*)
call delete_trailing_duplicates
call delete_nontrailing_duplicates
contains
subroutine delete_trailing_duplicates
integer :: i
logical :: done
i = n - 1
done = .false.
do while (.not. done)
if (i == 0) then
n = 1
done = .true.
else if (pt(i - 1) /= pt(i)) then
n = i + 1
done = .true.
else
i = i - 1
end if
end do
end subroutine delete_trailing_duplicates
subroutine delete_nontrailing_duplicates
integer :: i, j, num_deleted
logical :: done
i = 0
do while (i < n - 1)
j = i + 1
done = .false.
do while (.not. done)
if (j == n) then
done = .true.
else if (pt(j) /= pt(i)) then
done = .true.
else
j = j + 1
end if
end do
if (j /= i + 1) then
num_deleted = j - i - 1
do while (j /= n)
pt(j - num_deleted) = pt(j)
j = j + 1
end do
n = n - num_deleted
end if
i = i + 1
end do
end subroutine delete_nontrailing_duplicates
end subroutine delete_neighbor_duplicates
subroutine construct_lower_hull (n, pt, hull_size, hull)
integer, intent(in) :: n ! Number of points.
complex, intent(in) :: pt(0:*)
integer, intent(inout) :: hull_size
complex, intent(inout) :: hull(0:*)
integer :: i, j
logical :: done
j = 1
hull(0:1) = pt(0:1)
do i = 2, n - 1
done = .false.
do while (.not. done)
if (j == 0) then
j = j + 1
hull(j) = pt(i)
done = .true.
else if (0.0 < cross (hull(j) - hull(j - 1), &
& pt(i) - hull(j - 1))) then
j = j + 1
hull(j) = pt(i)
done = .true.
else
j = j - 1
end if
end do
end do
hull_size = j + 1
end subroutine construct_lower_hull
subroutine construct_upper_hull (n, pt, hull_size, hull)
integer, intent(in) :: n ! Number of points.
complex, intent(in) :: pt(0:*)
integer, intent(inout) :: hull_size
complex, intent(inout) :: hull(0:*)
integer :: i, j
logical :: done
j = 1
hull(0:1) = pt(n - 1 : n - 2 : -1)
do i = n - 3, 0, -1
done = .false.
do while (.not. done)
if (j == 0) then
j = j + 1
hull(j) = pt(i)
done = .true.
else if (0.0 < cross (hull(j) - hull(j - 1), &
& pt(i) - hull(j - 1))) then
j = j + 1
hull(j) = pt(i)
done = .true.
else
j = j - 1
end if
end do
end do
hull_size = j + 1
end subroutine construct_upper_hull
subroutine contruct_hull (n, pt, hull_size, hull)
integer, intent(in) :: n ! Number of points.
complex, intent(in) :: pt(0:*)
integer, intent(inout) :: hull_size
complex, intent(inout) :: hull(0:*)
integer :: lower_hull_size, upper_hull_size
complex :: lower_hull(0 : n - 1), upper_hull(0 : n - 1)
integer :: ihull0
ihull0 = lbound (hull, 1)
! A side note: the calls to construct_lower_hull and
! construct_upper_hull could be done in parallel.
call construct_lower_hull (n, pt, lower_hull_size, lower_hull)
call construct_upper_hull (n, pt, upper_hull_size, upper_hull)
hull_size = lower_hull_size + upper_hull_size - 2
hull(:ihull0 + lower_hull_size - 2) = &
& lower_hull(:lower_hull_size - 2)
hull(ihull0 + lower_hull_size - 1 : ihull0 + hull_size - 1) = &
& upper_hull(0 : upper_hull_size - 2)
end subroutine contruct_hull
subroutine find_convex_hull (n, points, hull_size, hull)
integer, intent(in) :: n ! Number of points.
complex, intent(in) :: points(*) ! Input points.
integer, intent(inout) :: hull_size ! The size of the hull.
complex, intent(inout) :: hull(*) ! Points of the hull.
!
! Yes, you can call this with something like
!
! call find_convex_hull (n, points, n, points)
!
! and in the program below I shall demonstrate that.
!
complex :: pt(0 : n - 1)
integer :: ipoints0, ihull0, numpt
ipoints0 = lbound (points, 1)
ihull0 = lbound (hull, 1)
pt = points(:ipoints0 + n - 1)
numpt = n
call sort_points (numpt, pt)
call delete_neighbor_duplicates (numpt, pt)
if (numpt == 0) then
hull_size = 0
else if (numpt <= 2) then
hull_size = numpt
hull(:ihull0 + numpt - 1) = pt(:numpt - 1)
else
call contruct_hull (numpt, pt, hull_size, hull)
end if
end subroutine find_convex_hull
end module convex_hulls
program convex_hull_task
use, non_intrinsic :: convex_hulls
implicit none
complex, parameter :: example_points(20) = &
& (/ (16, 3), (12, 17), (0, 6), (-4, -6), (16, 6), &
& (16, -7), (16, -3), (17, -4), (5, 19), (19, -8), &
& (3, 16), (12, 13), (3, -4), (17, 5), (-3, 15), &
& (-3, -9), (0, 11), (-9, -3), (-4, -2), (12, 10) /)
integer :: n, i
complex :: points(0:100)
character(len = 100) :: fmt
n = 20
points(1:n) = example_points
call find_convex_hull (n, points(1:n), n, points(1:n))
write (fmt, '("(", I20, ''("(", F3.0, 1X, F3.0, ") ")'', ")")') n
write (*, fmt) (points(i), i = 1, n)
end program convex_hull_task |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Frink | Frink |
wk := week
n = eval[input["Enter duration in seconds: "]]
res = n s -> [0, "wk", "d", "hr", "min", "sec", 0]
res =~ %s/, 0[^,]+//g
println[res]
|
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Julia | Julia | using Lazy
using Primes
function containsitsonlytwodigfactors(n)
s = string(n)
return !isprime(n) && all(t -> length(t) > 1 && contains(s, t), map(string, collect(keys(factor(n)))))
end
seq = @>> Lazy.range(2) filter(containsitsonlytwodigfactors)
foreach(p -> print(lpad(last(p), 9), first(p) == 10 ? "\n" : ""), enumerate(take(20, seq)))
|
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[CompositeAndContainsPrimeFactor]
CompositeAndContainsPrimeFactor[k_Integer] := Module[{id, pf},
If[CompositeQ[k],
pf = FactorInteger[k][[All, 1]];
If[AllTrue[pf, GreaterThan[10]],
id = IntegerDigits[k];
AllTrue[pf, SequenceCount[id, IntegerDigits[#]] > 0 &]
,
False
]
,
False
]
]
out = Select[Range[30000000], CompositeAndContainsPrimeFactor] |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Pascal | Pascal | program FacOfInt;
// gets factors of consecutive integers fast
// limited to 1.2e11
{$IFDEF FPC}
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,
strutils //Numb2USA
{$IFDEF WINDOWS},Windows{$ENDIF}
;
//######################################################################
//prime decomposition
const
//HCN(86) > 1.2E11 = 128,501,493,120 count of divs = 4096 7 3 1 1 1 1 1 1 1
HCN_DivCnt = 4096;
type
tItem = Uint64;
tDivisors = array [0..HCN_DivCnt] of tItem;
tpDivisor = pUint64;
const
//used odd size for test only
SizePrDeFe = 32768;//*72 <= 64kb level I or 2 Mb ~ level 2 cache
type
tdigits = array [0..31] of Uint32;
//the first number with 11 different prime factors =
//2*3*5*7*11*13*17*19*23*29*31 = 2E11
//56 byte
tprimeFac = packed record
pfSumOfDivs,
pfRemain : Uint64;
pfDivCnt : Uint32;
pfMaxIdx : Uint32;
pfpotPrimIdx : array[0..9] of word;
pfpotMax : array[0..11] of byte;
end;
tpPrimeFac = ^tprimeFac;
tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac;
tPrimes = array[0..65535] of Uint32;
var
{$ALIGN 8}
SmallPrimes: tPrimes;
{$ALIGN 32}
PrimeDecompField :tPrimeDecompField;
pdfIDX,pdfOfs: NativeInt;
procedure InitSmallPrimes;
//get primes. #0..65535.Sieving only odd numbers
const
MAXLIMIT = (821641-1) shr 1;
var
pr : array[0..MAXLIMIT] of byte;
p,j,d,flipflop :NativeUInt;
Begin
SmallPrimes[0] := 2;
fillchar(pr[0],SizeOf(pr),#0);
p := 0;
repeat
repeat
p +=1
until pr[p]= 0;
j := (p+1)*p*2;
if j>MAXLIMIT then
BREAK;
d := 2*p+1;
repeat
pr[j] := 1;
j += d;
until j>MAXLIMIT;
until false;
SmallPrimes[1] := 3;
SmallPrimes[2] := 5;
j := 3;
d := 7;
flipflop := (2+1)-1;//7+2*2,11+2*1,13,17,19,23
p := 3;
repeat
if pr[p] = 0 then
begin
SmallPrimes[j] := d;
inc(j);
end;
d += 2*flipflop;
p+=flipflop;
flipflop := 3-flipflop;
until (p > MAXLIMIT) OR (j>High(SmallPrimes));
end;
function OutPots(pD:tpPrimeFac;n:NativeInt):Ansistring;
var
s: String[31];
chk,p,i: NativeInt;
Begin
str(n,s);
result := Format('%15s : ',[Numb2USA(s)]);
with pd^ do
begin
chk := 1;
For n := 0 to pfMaxIdx-1 do
Begin
if n>0 then
result += '*';
p := SmallPrimes[pfpotPrimIdx[n]];
chk *= p;
str(p,s);
result += s;
i := pfpotMax[n];
if i >1 then
Begin
str(pfpotMax[n],s);
result += '^'+s;
repeat
chk *= p;
dec(i);
until i <= 1;
end;
end;
p := pfRemain;
If p >1 then
Begin
str(p,s);
chk *= p;
result += '*'+s;
end;
end;
end;
function CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt;
//n must be multiple of base aka n mod base must be 0
var
q,r: Uint64;
i : NativeInt;
Begin
fillchar(dgt,SizeOf(dgt),#0);
i := 0;
n := n div base;
result := 0;
repeat
r := n;
q := n div base;
r -= q*base;
n := q;
dgt[i] := r;
inc(i);
until (q = 0);
//searching lowest pot in base
result := 0;
while (result<i) AND (dgt[result] = 0) do
inc(result);
inc(result);
end;
function IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt;
var
q :NativeInt;
Begin
result := 0;
q := dgt[result]+1;
if q = base then
repeat
dgt[result] := 0;
inc(result);
q := dgt[result]+1;
until q <> base;
dgt[result] := q;
result +=1;
end;
function SieveOneSieve(var pdf:tPrimeDecompField):boolean;
var
dgt:tDigits;
i,j,k,pr,fac,n,MaxP : Uint64;
begin
n := pdfOfs;
if n+SizePrDeFe >= sqr(SmallPrimes[High(SmallPrimes)]) then
EXIT(FALSE);
//init
for i := 0 to SizePrDeFe-1 do
begin
with pdf[i] do
Begin
pfDivCnt := 1;
pfSumOfDivs := 1;
pfRemain := n+i;
pfMaxIdx := 0;
pfpotPrimIdx[0] := 0;
pfpotMax[0] := 0;
end;
end;
//first factor 2. Make n+i even
i := (pdfIdx+n) AND 1;
IF (n = 0) AND (pdfIdx<2) then
i := 2;
repeat
with pdf[i] do
begin
j := BsfQWord(n+i);
pfMaxIdx := 1;
pfpotPrimIdx[0] := 0;
pfpotMax[0] := j;
pfRemain := (n+i) shr j;
pfSumOfDivs := (Uint64(1) shl (j+1))-1;
pfDivCnt := j+1;
end;
i += 2;
until i >=SizePrDeFe;
//i now index in SmallPrimes
i := 0;
maxP := trunc(sqrt(n+SizePrDeFe))+1;
repeat
//search next prime that is in bounds of sieve
if n = 0 then
begin
repeat
inc(i);
pr := SmallPrimes[i];
k := pr-n MOD pr;
if k < SizePrDeFe then
break;
until pr > MaxP;
end
else
begin
repeat
inc(i);
pr := SmallPrimes[i];
k := pr-n MOD pr;
if (k = pr) AND (n>0) then
k:= 0;
if k < SizePrDeFe then
break;
until pr > MaxP;
end;
//no need to use higher primes
if pr*pr > n+SizePrDeFe then
BREAK;
//j is power of prime
j := CnvtoBASE(dgt,n+k,pr);
repeat
with pdf[k] do
Begin
pfpotPrimIdx[pfMaxIdx] := i;
pfpotMax[pfMaxIdx] := j;
pfDivCnt *= j+1;
fac := pr;
repeat
pfRemain := pfRemain DIV pr;
dec(j);
fac *= pr;
until j<= 0;
pfSumOfDivs *= (fac-1)DIV(pr-1);
inc(pfMaxIdx);
k += pr;
j := IncByBaseInBase(dgt,pr);
end;
until k >= SizePrDeFe;
until false;
//correct sum of & count of divisors
for i := 0 to High(pdf) do
Begin
with pdf[i] do
begin
j := pfRemain;
if j <> 1 then
begin
pfSumOFDivs *= (j+1);
pfDivCnt *=2;
end;
end;
end;
result := true;
end;
function NextSieve:boolean;
begin
dec(pdfIDX,SizePrDeFe);
inc(pdfOfs,SizePrDeFe);
result := SieveOneSieve(PrimeDecompField);
end;
function GetNextPrimeDecomp:tpPrimeFac;
begin
if pdfIDX >= SizePrDeFe then
if Not(NextSieve) then
EXIT(NIL);
result := @PrimeDecompField[pdfIDX];
inc(pdfIDX);
end;
function Init_Sieve(n:NativeUint):boolean;
//Init Sieve pdfIdx,pdfOfs are Global
begin
pdfIdx := n MOD SizePrDeFe;
pdfOfs := n-pdfIdx;
result := SieveOneSieve(PrimeDecompField);
end;
var
s,pr : string[31];
pPrimeDecomp :tpPrimeFac;
T0:Int64;
n,i,cnt : NativeUInt;
checked : boolean;
Begin
InitSmallPrimes;
T0 := GetTickCount64;
cnt := 0;
n := 0;
Init_Sieve(n);
repeat
pPrimeDecomp:= GetNextPrimeDecomp;
with pPrimeDecomp^ do
begin
//composite with smallest factor 11
if (pfDivCnt>=4) AND (pfpotPrimIdx[0]>3) then
begin
str(n,s);
for i := 0 to pfMaxIdx-1 do
begin
str(smallprimes[pfpotPrimIdx[i]],pr);
checked := (pos(pr,s)>0);
if Not(checked) then
Break;
end;
if checked then
begin
//writeln(cnt:4,OutPots(pPrimeDecomp,n));
if pfRemain >1 then
begin
str(pfRemain,pr);
checked := (pos(pr,s)>0);
end;
if checked then
begin
inc(cnt);
writeln(cnt:4,OutPots(pPrimeDecomp,n));
end;
end;
end;
end;
inc(n);
until n > 28118827;//10*1000*1000*1000+1;//
T0 := GetTickCount64-T0;
writeln('runtime ',T0/1000:0:3,' s');
end.
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #FreeBASIC | FreeBASIC | #define MAX 70000
function sqrt2_a( n as uinteger ) as uinteger
return iif(n,2,1)
end function
function sqrt2_b( n as uinteger ) as uinteger
return 1
end function
function napi_a( n as uinteger ) as uinteger
return iif(n,n,2)
end function
function napi_b( n as uinteger ) as uinteger
return iif(n>1,n-1,1)
end function
function pi_a( n as uinteger ) as uinteger
return iif(n,6,3)
end function
function pi_b( n as uinteger ) as uinteger
return (2*n-1)^2
end function
function calc_contfrac( an as function (as uinteger) as uinteger, bn as function (as uinteger) as uinteger, byval iter as uinteger ) as double
dim as double r
dim as integer i
for i = iter to 1 step -1
r = bn(i)/(an(i)+r)
next i
return an(0)+r
end function
print calc_contfrac( @sqrt2_a, @sqrt2_b, MAX )
print calc_contfrac( @napi_a, @napi_b, MAX )
print calc_contfrac( @pi_a, @pi_b, MAX ) |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia |
s = "Rosetta Code"
t = s
println("s = \"", s, "\" and, after \"t = s\", t = \"", t, "\"")
s = "Julia at "*s
println("s = \"", s, "\" and, after this change, t = \"", t, "\"")
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #KonsolScript | KonsolScript | Var:String str1 = "Hello";
Var:String str2 = str1; |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #CoffeeScript | CoffeeScript |
NUM_POINTS = 100
MIN_R = 10
MAX_R = 15
random_circle_points = ->
rand_point = ->
Math.floor (Math.random() * (MAX_R * 2 + 1) - MAX_R)
points = {}
cnt = 0
while cnt < 100
x = rand_point()
y = rand_point()
continue unless MIN_R * MIN_R <= x*x + y*y <= MAX_R * MAX_R
points["#{x},#{y}"] = true
cnt += 1
points
plot = (points) ->
range = [-1 * MAX_R .. MAX_R]
for y in range
s = ''
for x in range
s += if points["#{x},#{y}"] then '*' else ' '
console.log s
plot random_circle_points()
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #FreeBASIC | FreeBASIC |
#include "crt.bi"
Screen 20
Window (-20,-20)-(30,30)
Type Point
As Single x,y
As Long done
End Type
#macro rotate(pivot,p,a,scale)
Type<Point>(scale*(Cos(a*.0174533)*(p.x-pivot.x)-Sin(a*.0174533)*(p.y-pivot.y))+pivot.x, _
scale*(Sin(a*.0174533)*(p.x-pivot.x)+Cos(a*.0174533)*(p.y-pivot.y))+pivot.y)
#endmacro
Dim As Point p(1 To ...)={(16,3),(12,17),(0,6),(-4,-6),(16,6),(16,-7),(16,-3),(17,-4),(5,19), _
(19,-8),(3,16),(12,13),(3,-4),(17,5),(-3,15),(-3,-9),(0,11),(-9,-3),(-4,-2),(12,10)}
Function south(p() As Point,Byref idx As Long) As Point
Dim As Point s=Type(0,100)
For n As Long=Lbound(p) To Ubound(p)
Circle(p(n).x,p(n).y),.2,7,,,,f
If s.y>p(n).y Then s=p(n):idx=n
Next n
Return s
End Function
Function segment_distance(lx1 As Single, _
ly1 As Single, _
lx2 As Single, _
ly2 As Single, _
px As Single,_
py As Single, _
Byref ox As Single=0,_
Byref oy As Single=0) As Single
Dim As Single M1,M2,C1,C2,B
B=(Lx2-Lx1):If B=0 Then B=1e-20
M2=(Ly2-Ly1)/B:If M2=0 Then M2=1e-20
M1=-1/M2
C1=py-M1*px
C2=(Ly1*Lx2-Lx1*Ly2)/B
Var L1=((px-lx1)*(px-lx1)+(py-ly1)*(py-ly1)),L2=((px-lx2)*(px-lx2)+(py-ly2)*(py-ly2))
Var a=((lx1-lx2)*(lx1-lx2) + (ly1-ly2)*(ly1-ly2))
Var a1=a+L1
Var a2=a+L2
Var f1=a1>L2,f2=a2>L1
If f1 Xor f2 Then
Var d1=((px-Lx1)*(px-Lx1)+(py-Ly1)*(py-Ly1))
Var d2=((px-Lx2)*(px-Lx2)+(py-Ly2)*(py-Ly2))
If d1<d2 Then Ox=Lx1:Oy=Ly1 : Return Sqr(d1) Else Ox=Lx2:Oy=Ly2:Return Sqr(d2)
End If
Var M=M1-M2:If M=0 Then M=1e-20
Ox=(C2-C1)/(M1-M2)
Oy=(M1*C2-M2*C1)/M
Return Sqr((px-Ox)*(px-Ox)+(py-Oy)*(py-Oy))
End Function
Dim As Long idx
Var s= south(p(),idx)
p(idx).done=1
Redim As Point ans(1 To 1)
ans(1)=s
Dim As Point e=s
e.x=1000
Dim As Long count=1
Dim As Single z
Circle(s.x,s.y),.4,5
Do
z+=.05
Var pt=rotate(s,e,z,1)
For n As Long=Lbound(p) To Ubound(p)
If segment_distance(s.x,s.y,pt.x,pt.y,p(n).x,p(n).y)<.05 Then
s=p(n)
If p(n).done=0 Then
count+=1
Redim Preserve ans(1 To count)
ans(count)=p(n)
p(n).done=1
End If
End If
Circle(s.x,s.y),.4,5
Next n
Loop Until z>360
For n As Long=Lbound(ans) To Ubound(ans)
printf (!"(%2.0f , %2.0f )\n", ans(n).x, ans(n).y)
Next
Sleep
|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Gambas | Gambas | Public Sub Main()
Dim iInput As Integer[] = [7259, 86400, 6000000] 'Input details
Dim iChecks As Integer[] = [604800, 86400, 3600, 60] 'Weeks, days, hours, mins in seconds
Dim iTime As New Integer[5] 'To store wk, d, hr, min & sec
Dim iOriginal, iSec, iLoop As Integer 'Various integers
Dim sOrd As String[] = [" wk", " d", " hr", " min", " sec"] 'To add to the output string
Dim sOutput As String 'Output string
For Each iSec In iInput 'For each iInput
iOriginal = iSec 'Store orginal value in seconds
iTime[4] = iSec 'Store seconds in iTime[4]
For iLoop = 0 To 3 'Loop through wk, d, hr, min & sec
If iTime[4] >= iChecks[iLoop] Then 'Check if value is = to wk, d, hr, min
iTime[iLoop] = Int(iTime[4] / iChecks[iLoop]) 'Put the correct value for wk, d, hr, min in iTime
iTime[4] = iTime[4] - (iTime[iLoop] * iChecks[iLoop]) 'Remove the amount of seconds for wk, d, hr, min from iTime[4]
Endif
Next
For iLoop = 0 To 4 'Loop through wk, d, hr, min & secs
If iTime[iLoop] > 0 Then sOutput &= ", " & Str(iTime[iLoop]) & sOrd[iLoop] 'Add comma and ordinal as needed
Next
If Left(sOutput, 2) = ", " Then sOutput = Mid(sOutput, 3) 'Remove unnecessary ", "
sOutput = Format(Str(iOriginal), "#######") & " Seconds = " & sOutput 'Add original seconds to the output string
Print sOutput 'Print sOutput string
sOutput = "" 'Clear the sOutput string
iTime = New Integer[5] 'Reset iTime[]
Next
End |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Perl | Perl | use strict;
use warnings;
use ntheory qw<is_prime factor gcd>;
my($values,$cnt);
LOOP: for (my $k = 11; $k < 1E10; $k += 2) {
next if 1 < gcd($k,2*3*5*7) or is_prime $k;
map { next if index($k, $_) < 0 } factor $k;
$values .= sprintf "%10d", $k;
last LOOP if ++$cnt == 20;
}
print $values =~ s/.{1,100}\K/\n/gr; |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Phix | Phix | with javascript_semantics
integer count = 0, n = 11*11,
limit = iff(platform()=JS?10:20)
atom t0 = time(), t1 = time()
while count<limit do
if gcd(n,3*5*7)=1 then
sequence f = prime_factors(n,true,-1)
if length(f)>1 then
string s = sprintf("%d",n)
bool valid = true
for i=1 to length(f) do
if (i=1 or f[i]!=f[i-1])
and not match(sprintf("%d",f[i]),s) then
valid = false
exit
end if
end for
if valid then
count += 1
string t = join(apply(f,sprint),"x"),
e = elapsed(time()-t1)
printf(1,"%2d: %,10d = %-17s (%s)\n",{count,n,t,e})
t1 = time()
end if
end if
end if
n += 2
end while
printf(1,"Total time:%s\n",{elapsed(time()-t0)})
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type cfTerm struct {
a, b int
}
// follows subscript convention of mathworld and WP where there is no b(0).
// cf[0].b is unused in this representation.
type cf []cfTerm
func cfSqrt2(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{2, 1}
}
f[0].a = 1
return f
}
func cfNap(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{n, n - 1}
}
f[0].a = 2
f[1].b = 1
return f
}
func cfPi(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
g := 2*n - 1
f[n] = cfTerm{6, g * g}
}
f[0].a = 3
return f
}
func (f cf) real() (r float64) {
for n := len(f) - 1; n > 0; n-- {
r = float64(f[n].b) / (float64(f[n].a) + r)
}
return r + float64(f[0].a)
}
func main() {
fmt.Println("sqrt2:", cfSqrt2(20).real())
fmt.Println("nap: ", cfNap(20).real())
fmt.Println("pi: ", cfPi(20).real())
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | val s = "Hello"
val alias = s // alias === s
val copy = "" + s // copy !== s |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LabVIEW | LabVIEW | 'hello dup |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Common_Lisp | Common Lisp | (flet ((good-p (x y) (<= 100 (+ (* x x) (* y y)) 255)))
(loop with x with y with cnt = 0
with scr = (loop repeat 31 collect (loop repeat 31 collect " "))
while (< cnt 100)
do (when (good-p (- (setf x (random 31)) 15)
(- (setf y (random 31)) 15))
(setf (elt (elt scr y) x) "@ ")
(incf cnt))
finally (mapc #'(lambda (row) (format t "~{~a~^~}~%" row)) scr))) |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Go | Go | package main
import (
"fmt"
"image"
"sort"
)
// ConvexHull returns the set of points that define the
// convex hull of p in CCW order starting from the left most.
func (p points) ConvexHull() points {
// From https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
// with only minor deviations.
sort.Sort(p)
var h points
// Lower hull
for _, pt := range p {
for len(h) >= 2 && !ccw(h[len(h)-2], h[len(h)-1], pt) {
h = h[:len(h)-1]
}
h = append(h, pt)
}
// Upper hull
for i, t := len(p)-2, len(h)+1; i >= 0; i-- {
pt := p[i]
for len(h) >= t && !ccw(h[len(h)-2], h[len(h)-1], pt) {
h = h[:len(h)-1]
}
h = append(h, pt)
}
return h[:len(h)-1]
}
// ccw returns true if the three points make a counter-clockwise turn
func ccw(a, b, c image.Point) bool {
return ((b.X - a.X) * (c.Y - a.Y)) > ((b.Y - a.Y) * (c.X - a.X))
}
type points []image.Point
func (p points) Len() int { return len(p) }
func (p points) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p points) Less(i, j int) bool {
if p[i].X == p[j].X {
return p[i].Y < p[i].Y
}
return p[i].X < p[j].X
}
func main() {
pts := points{
{16, 3}, {12, 17}, {0, 6}, {-4, -6}, {16, 6},
{16, -7}, {16, -3}, {17, -4}, {5, 19}, {19, -8},
{3, 16}, {12, 13}, {3, -4}, {17, 5}, {-3, 15},
{-3, -9}, {0, 11}, {-9, -3}, {-4, -2}, {12, 10},
}
hull := pts.ConvexHull()
fmt.Println("Convex Hull:", hull)
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Go | Go | package main
import "fmt"
func main(){
fmt.Println(TimeStr(7259))
fmt.Println(TimeStr(86400))
fmt.Println(TimeStr(6000000))
}
func TimeStr(sec int)(res string){
wks, sec := sec / 604800,sec % 604800
ds, sec := sec / 86400, sec % 86400
hrs, sec := sec / 3600, sec % 3600
mins, sec := sec / 60, sec % 60
CommaRequired := false
if wks != 0 {
res += fmt.Sprintf("%d wk",wks)
CommaRequired = true
}
if ds != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d d",ds)
CommaRequired = true
}
if hrs != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d hr",hrs)
CommaRequired = true
}
if mins != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d min",mins)
CommaRequired = true
}
if sec != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d sec",sec)
}
return
}
|
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Raku | Raku | use Prime::Factor;
use Lingua::EN::Numbers;
put (2..∞).hyper(:5000batch).map( {
next if (1 < $_ gcd 210) || .is-prime || any .&prime-factors.map: -> $n { !.contains: $n };
$_
} )[^20].batch(10)».&comma».fmt("%10s").join: "\n"; |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Sidef | Sidef | var e = Enumerator({|f|
var c = (9.primorial)
var a = (1..c -> grep { .is_coprime(c) })
loop {
var n = a.shift
a.push(n + c)
n.is_composite || next
f(n) if n.factor.all {|p| Str(n).contains(p) }
}
})
var count = 10
e.each {|n|
say n
break if (--count <= 0)
} |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Go | Go | package main
import "fmt"
type cfTerm struct {
a, b int
}
// follows subscript convention of mathworld and WP where there is no b(0).
// cf[0].b is unused in this representation.
type cf []cfTerm
func cfSqrt2(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{2, 1}
}
f[0].a = 1
return f
}
func cfNap(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{n, n - 1}
}
f[0].a = 2
f[1].b = 1
return f
}
func cfPi(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
g := 2*n - 1
f[n] = cfTerm{6, g * g}
}
f[0].a = 3
return f
}
func (f cf) real() (r float64) {
for n := len(f) - 1; n > 0; n-- {
r = float64(f[n].b) / (float64(f[n].a) + r)
}
return r + float64(f[0].a)
}
func main() {
fmt.Println("sqrt2:", cfSqrt2(20).real())
fmt.Println("nap: ", cfNap(20).real())
fmt.Println("pi: ", cfPi(20).real())
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lang5 | Lang5 | 'hello dup |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lasso | Lasso | local(x = 'I saw a rhino!')
local(y = #x)
#x //I saw a rhino!
'\r'
#y //I saw a rhino!
'\r\r'
#x = 'I saw one too'
#x //I saw one too
'\r'
#y //I saw a rhino!
'\r\r'
#y = 'it was grey.'
#x //I saw one too
'\r'
#y //it was grey. |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #D | D | import std.stdio, std.random, std.math, std.complex;
void main() {
char[31][31] table = ' ';
foreach (immutable _; 0 .. 100) {
int x, y;
do {
x = uniform(-15, 16);
y = uniform(-15, 16);
} while(abs(12.5 - complex(x, y).abs) > 2.5);
table[x + 15][y + 15] = '*';
}
writefln("%-(%s\n%)", table);
} |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Groovy | Groovy | class ConvexHull {
private static class Point implements Comparable<Point> {
private int x, y
Point(int x, int y) {
this.x = x
this.y = y
}
@Override
int compareTo(Point o) {
return Integer.compare(x, o.x)
}
@Override
String toString() {
return String.format("(%d, %d)", x, y)
}
}
private static List<Point> convexHull(List<Point> p) {
if (p.isEmpty()) return Collections.emptyList()
p.sort(new Comparator<Point>() {
@Override
int compare(Point o1, Point o2) {
return o1 <=> o2
}
})
List<Point> h = new ArrayList<>()
// lower hull
for (Point pt : p) {
while (h.size() >= 2 && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {
h.remove(h.size() - 1)
}
h.add(pt)
}
// upper hull
int t = h.size() + 1
for (int i = p.size() - 1; i >= 0; i--) {
Point pt = p.get(i)
while (h.size() >= t && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {
h.remove(h.size() - 1)
}
h.add(pt)
}
h.remove(h.size() - 1)
return h
}
// ccw returns true if the three points make a counter-clockwise turn
private static boolean ccw(Point a, Point b, Point c) {
return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))
}
static void main(String[] args) {
List<Point> points = Arrays.asList(new Point(16, 3),
new Point(12, 17),
new Point(0, 6),
new Point(-4, -6),
new Point(16, 6),
new Point(16, -7),
new Point(16, -3),
new Point(17, -4),
new Point(5, 19),
new Point(19, -8),
new Point(3, 16),
new Point(12, 13),
new Point(3, -4),
new Point(17, 5),
new Point(-3, 15),
new Point(-3, -9),
new Point(0, 11),
new Point(-9, -3),
new Point(-4, -2),
new Point(12, 10))
List<Point> hull = convexHull(points)
println("Convex Hull: $hull")
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.