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/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#DCL
|
DCL
|
$ happy_1 = 1
$ found = 0
$ i = 1
$ loop1:
$ n = i
$ seen_list = ","
$ loop2:
$ if f$type( happy_'n ) .nes. "" then $ goto happy
$ if f$type( unhappy_'n ) .nes. "" then $ goto unhappy
$ if f$locate( "," + n + ",", seen_list ) .eq. f$length( seen_list )
$ then
$ seen_list = seen_list + f$string( n ) + ","
$ else
$ goto unhappy
$ endif
$ ns = f$string( n )
$ nl = f$length( ns )
$ j = 0
$ sumsq = 0
$ loop3:
$ digit = f$integer( f$extract( j, 1, ns ))
$ sumsq = sumsq + digit * digit
$ j = j + 1
$ if j .lt. nl then $ goto loop3
$ n = sumsq
$ goto loop2
$ unhappy:
$ j = 1
$ loop4:
$ x = f$element( j, ",", seen_list )
$ if x .eqs. "" then $ goto continue
$ unhappy_'x = 1
$ j = j + 1
$ goto loop4
$ happy:
$ found = found + 1
$ found_'found = i
$ if found .eq. 8 then $ goto done
$ j = 1
$ loop5:
$ x = f$element( j, ",", seen_list )
$ if x .eqs. "" then $ goto continue
$ happy_'x = 1
$ j = j + 1
$ goto loop5
$ continue:
$ i = i + 1
$ goto loop1
$ done:
$ show symbol found*
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function rad = radians(degree)
% degrees to radians
rad = degree .* pi / 180;
end;
function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
% HAVERSINE_FORMULA.AWK - converted from AWK
dlat = radians(lat2-lat1);
dlon = radians(lon2-lon1);
lat1 = radians(lat1);
lat2 = radians(lat2);
a = (sin(dlat./2)).^2 + cos(lat1) .* cos(lat2) .* (sin(dlon./2)).^2;
c = 2 .* asin(sqrt(a));
arrayfun(@(x) printf("distance: %.4f km\n",6372.8 * x), c);
end;
[a,c,dlat,dlon] = haversine(36.12,-86.67,33.94,-118.40); % BNA to LAX
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#GAP
|
GAP
|
# Several ways to do it
"Hello world!";
Print("Hello world!\n"); # No EOL appended
Display("Hello world!");
f := OutputTextUser();
WriteLine(f, "Hello world!\n");
CloseStream(f);
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Visual_Basic
|
Visual Basic
|
Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add owner(n), os(n)
Next
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#WDTE
|
WDTE
|
let a => import 'arrays';
let s => import 'stream';
let toScope keys vals =>
s.zip (a.stream keys) (a.stream vals)
->
s.reduce (collect (true)) (@ r scope kv =>
let [k v] => kv;
set scope k v;
)
;
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Objeck
|
Objeck
|
class Harshad {
function : Main(args : String[]) ~ Nil {
count := 0;
for(i := 1; count < 20; i += 1;) {
if(i % SumDigits(i) = 0){
"{$i} "->Print();
count += 1;
};
};
for(i := 1001; true; i += 1;) {
if(i % SumDigits(i) = 0){
"... {$i}"->PrintLine();
break;
};
};
}
function : SumDigits(n : Int) ~ Int {
sum := 0;
do {
sum += n % 10;
n /= 10;
} while(n <> 0);
return sum;
}
}
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#i
|
i
|
graphics {
display("Goodbye, World!")
}
|
http://rosettacode.org/wiki/GUI_component_interaction
|
GUI component interaction
|
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dialogs to query the user for further information
Task
For a minimal "application", write a program that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("random")
The field is initialized to zero.
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
Entering a non-numeric value should be either impossible,
or issue an error message.
Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".
(This task may be regarded as an extension of the task Simple windowed application).
|
#Phix
|
Phix
|
include pGUI.e
Ihandle txt, increment, random, hbx, vbx, dlg
function action_cb(Ihandle /*ih*/, integer ch)
if not find(ch,"0123456789-") then return IUP_IGNORE end if
return IUP_CONTINUE
end function
function increment_cb(Ihandle /*ih*/)
integer v = IupGetInt(txt,"VALUE")+1
IupSetInt(txt,"VALUE",v)
return IUP_CONTINUE
end function
function random_cb(Ihandle /*ih*/)
if IupAlarm("Confirm","Replace wth random value?","Yes","No")=1 then
IupSetInt(txt,"VALUE",rand(1000))
end if
return IUP_CONTINUE
end function
IupOpen()
txt = IupText(Icallback("action_cb"),"EXPAND=YES")
increment = IupButton("increment",Icallback("increment_cb"))
random = IupButton("random",Icallback("random_cb"))
hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20")
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
dlg = IupDialog(vbx)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#8080_Assembly
|
8080 Assembly
|
org 100h
xra a ; set A=0
loop: push psw ; print number as decimal
call decout
call padding ; print padding
pop psw
push psw
call binout ; print number as binary
call padding
pop psw
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov b,a ; gray encode
ana a ; clear carry
rar ; shift right
xra b ; xor the original
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
push psw
call binout ; print gray number as binary
call padding
pop psw
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov b,a ; gray decode
decode: ana a ; clear carry
jz done ; when no more bits are left, stop
rar ; shift right
mov c,a ; keep that value
xra b ; xor into output value
mov b,a ; that is the output value
mov a,c ; restore intermediate
jmp decode ; do next bit
done: mov a,b ; give output value
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
push psw
call binout ; print decoded number as binary
call padding
pop psw
push psw
call decout ; print decoded number as decimal
lxi d,nl
call strout
pop psw
inr a ; next number
ani 1fh ; are we there yet?
jnz loop ; if not, do next number
ret
;; Print A as two-digit number
decout: mvi c,10
call dgtout
mvi c,1
dgtout: mvi e,'0' - 1
dgtloop: inr e
sub c
jnc dgtloop
add c
push psw
mvi c,2
call 5
pop psw
ret
;; Print A as five-bit binary number
binout: ani 1fh
ral
ral
ral
mvi c,5
binloop: ral
push psw
push b
mvi c,2
mvi a,0
aci '0'
mov e,a
call 5
pop b
pop psw
dcr c
jnz binloop
ret
;; Print padding
padding: lxi d,arrow
strout: mvi c,9
jmp 5
arrow: db ' ==> $'
nl: db 13,10,'$'
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Action.21
|
Action!
|
PROC ToBinaryStr(BYTE n CHAR ARRAY s)
BYTE i
s(0)=8 i=8
SetBlock(s+1,8,'0)
WHILE n
DO
s(i)=(n&1)+'0
n==RSH 1
i==-1
OD
RETURN
PROC PrintB2(BYTE n)
IF n<10 THEN Put(32) FI
PrintB(n)
RETURN
PROC PrintBin5(BYTE n)
CHAR ARRAY s(9),sub(6)
ToBinaryStr(n,s)
SCopyS(sub,s,4,s(0))
Print(sub)
RETURN
BYTE FUNC Encode(BYTE n)
RETURN (n XOR (n RSH 1))
BYTE FUNC Decode(BYTE n)
BYTE res
res=n
DO
n==RSH 1
IF n THEN
res==XOR n
ELSE
EXIT
FI
OD
RETURN (res)
PROC Main()
BYTE i,g,b
CHAR ARRAY sep=" -> "
FOR i=0 TO 31
DO
PrintB2(i) Print(sep)
PrintBin5(i) Print(sep)
g=Encode(i)
PrintBin5(g) Print(sep)
b=Decode(g)
PrintBin5(b) Print(sep)
PrintB2(b) PutE()
OD
RETURN
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#ACL2
|
ACL2
|
(defun maximum (xs)
(if (endp (rest xs))
(first xs)
(max (first xs)
(maximum (rest xs)))))
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#11l
|
11l
|
F hailstone(=n)
V seq = [n]
L n > 1
n = I n % 2 != 0 {3 * n + 1} E n I/ 2
seq.append(n)
R seq
V h = hailstone(27)
assert(h.len == 112 & h[0.<4] == [27, 82, 41, 124] & h[(len)-4 ..] == [8, 4, 2, 1])
V m = max((1..99999).map(i -> (hailstone(i).len, i)))
print(‘Maximum length #. was found for hailstone(#.) for numbers <100,000’.format(m[0], m[1]))
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#J
|
J
|
parse=: {{
ref=: 2$L:1(;:each cut y) -.L:1 ;:'-'
labels=: /:~~.;ref
sparse=. (*:#labels) > 20*#ref
graph=: (+.|:) 1 (labels i.L:1 ref)} $.^:sparse 0$~2##labels
}}
greedy=: {{
colors=. (#y)#a:
for_node.y do.
color=. <{.(-.~ [:i.1+#) ~.;node#colors
colors=. color node_index} colors
end.
;colors
}}
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Julia
|
Julia
|
using Random
"""Useful constants for the colors to be selected for nodes of the graph"""
const colors4 = ["blue", "red", "green", "yellow"]
const badcolor = "black"
@assert(!(badcolor in colors4))
"""
struct graph
undirected simple graph
constructed from its name and a string listing of point to point connections
"""
mutable struct Graph
name::String
g::Dict{Int, Vector{Int}}
nodecolor::Dict{Int, String}
function Graph(nam::String, s::String)
gdic = Dict{Int, Vector{Int}}()
for p in eachmatch(r"(\d+)-(\d+)|(\d+)(?!\s*-)" , s)
if p != nothing
if p[3] != nothing
n3 = parse(Int, p[3])
get!(gdic, n3, [])
else
n1, n2 = parse(Int, p[1]), parse(Int, p[2])
p1vec = get!(gdic, n1, [])
!(n2 in p1vec) && push!(p1vec, n2)
p2vec = get!(gdic, n2, [])
!(n1 in p2vec) && push!(p2vec, n1)
end
end
end
new(nam, gdic, Dict{Int, String}())
end
end
"""
tryNcolors!(gr::Graph, N, maxtrials)
Try up to maxtrials to get a coloring with <= N colors
"""
function tryNcolors!(gr::Graph, N, maxtrials)
t, mintrial, minord = N, N + 1, Dict()
for _ in 1:maxtrials
empty!(gr.nodecolor)
ordering = shuffle(collect(keys(gr.g)))
for node in ordering
usedneighborcolors = [gr.nodecolor[c] for c in gr.g[node] if haskey(gr.nodecolor, c)]
gr.nodecolor[node] = badcolor
for c in colors4[1:N]
if !(c in usedneighborcolors)
gr.nodecolor[node] = c
break
end
end
end
t = length(unique(values(gr.nodecolor)))
if t < mintrial
mintrial = t
minord = deepcopy(gr.nodecolor)
end
end
if length(minord) > 0
gr.nodecolor = minord
end
end
"""
prettyprintcolors(gr::graph)
print out the colored nodes in graph
"""
function prettyprintcolors(gr::Graph)
println("\nColors for the graph named ", gr.name, ":")
edgesdone = Vector{Vector{Int}}()
for (node, neighbors) in gr.g
if !isempty(neighbors)
for n in neighbors
edge = node < n ? [node, n] : [n, node]
if !(edge in edgesdone)
println(" ", edge[1], "-", edge[2], " Color: ",
gr.nodecolor[edge[1]], ", ", gr.nodecolor[edge[2]])
push!(edgesdone, edge)
end
end
else
println(" ", node, ": ", gr.nodecolor[node])
end
end
println("\n", length(unique(keys(gr.nodecolor))), " nodes, ",
length(edgesdone), " edges, ",
length(unique(values(gr.nodecolor))), " colors.")
end
for (name, txt) in [("Ex1", "0-1 1-2 2-0 3"),
("Ex2", "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"),
("Ex3", "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"),
("Ex4", "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7")]
exgraph = Graph(name, txt)
tryNcolors!(exgraph, 4, 100)
prettyprintcolors(exgraph)
end
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
ClearAll[ColorGroups]
ColorGroups[g_Graph] := Module[{h, cols, indset, diffcols},
h = g;
cols = {};
While[! EmptyGraphQ[h], maxd = RandomChoice[VertexList[h]];
indset = Flatten[FindIndependentVertexSet[{h, maxd}]];
AppendTo[cols, indset];
h = VertexDelete[h, indset];
];
AppendTo[cols, VertexList[h]];
diffcols = Length[cols];
cols = Catenate[Map[Thread][Rule @@@ Transpose[{cols, Range[Length[cols]]}]]];
Print[Column[Row[{"Edge ", #1, " to ", #2, " has colors ", #1 /. cols, " and ", #2 /. cols }] & @@@ EdgeList[g]]];
Print[Grid[{{"Vertices: ", VertexCount[g]}, {"Edges: ", EdgeCount[g]}, {"Colors used: ", diffcols}}]]
]
ColorGroups[Graph[Range[0, 3], {0 \[UndirectedEdge] 1, 1 \[UndirectedEdge] 2,
2 \[UndirectedEdge] 0}]]
ColorGroups[Graph[Range[8], {1 \[UndirectedEdge] 6, 1 \[UndirectedEdge] 7,
1 \[UndirectedEdge] 8, 2 \[UndirectedEdge] 5,
2 \[UndirectedEdge] 7, 2 \[UndirectedEdge] 8,
3 \[UndirectedEdge] 5, 3 \[UndirectedEdge] 6,
3 \[UndirectedEdge] 8, 4 \[UndirectedEdge] 5,
4 \[UndirectedEdge] 6, 4 \[UndirectedEdge] 7}]]
ColorGroups[Graph[Range[8], {1 \[UndirectedEdge] 4, 1 \[UndirectedEdge] 6,
1 \[UndirectedEdge] 8, 3 \[UndirectedEdge] 2,
3 \[UndirectedEdge] 6, 3 \[UndirectedEdge] 8,
5 \[UndirectedEdge] 2, 5 \[UndirectedEdge] 4,
5 \[UndirectedEdge] 8, 7 \[UndirectedEdge] 2,
7 \[UndirectedEdge] 4, 7 \[UndirectedEdge] 6}]]
ColorGroups[Graph[Range[8], {1 \[UndirectedEdge] 6, 7 \[UndirectedEdge] 1,
8 \[UndirectedEdge] 1, 5 \[UndirectedEdge] 2,
2 \[UndirectedEdge] 7, 2 \[UndirectedEdge] 8,
3 \[UndirectedEdge] 5, 6 \[UndirectedEdge] 3,
3 \[UndirectedEdge] 8, 4 \[UndirectedEdge] 5,
4 \[UndirectedEdge] 6, 4 \[UndirectedEdge] 7}]]
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Julia
|
Julia
|
using Combinatorics
using Plots
using Primes
g(n) = iseven(n) ? count(p -> all(isprime, p), partitions(n, 2)) : error("n must be even")
println("The first 100 G numbers are: ")
foreach(p -> print(lpad(p[2], 4), p[1] % 10 == 0 ? "\n" : ""), map(g, 4:2:202) |> enumerate)
println("\nThe value of G(1000000) is ", g(1_000_000))
x = collect(2:2002)
y = map(g, 2x)
scatter(x, y, markerstrokewidth = 0, color = ["red", "blue", "green"][mod1.(x, 3)])
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Lua
|
Lua
|
function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
table.batch = function(t,n,f) for i=1,#t,n do local s=T{} for j=1,n do s[j]=t[i+j-1] end f(s) end return t end
function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, n^0.5, 6 do
if n%f==0 or n%(f+2)==0 then return false end
end
return true
end
function goldbach(n)
local count = 0
for i = 1, n/2 do
if isprime(i) and isprime(n-i) then
count = count + 1
end
end
return count
end
print("The first 100 G numbers:")
g = T{}:range(100):map(function(n) return goldbach(2+n*2) end)
g:map(function(n) return string.format("%2d ",n) end):batch(10,function(t) print(t:concat()) end)
print("G(1000000) = "..goldbach(1000000))
|
http://rosettacode.org/wiki/Grayscale_image
|
Grayscale image
|
Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#Crystal
|
Crystal
|
class RGBColour
def to_grayscale
luminosity = (0.2126*@red + 0.7152*@green + 0.0722*@blue).to_i
self.class.new(luminosity, luminosity, luminosity)
end
end
class Pixmap
def to_grayscale
gray = self.class.new(@width, @height)
@width.times do |x|
@height.times do |y|
gray[x,y] = self[x,y].to_grayscale
end
end
gray
end
end
|
http://rosettacode.org/wiki/Grayscale_image
|
Grayscale image
|
Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#D
|
D
|
module grayscale_image;
import core.stdc.stdio, std.array, std.algorithm, std.string, std.ascii;
public import bitmap;
struct Gray {
ubyte c;
enum black = typeof(this)(0);
enum white = typeof(this)(255);
alias c this;
}
Image!Color loadPGM(Color)(Image!Color img, in string fileName) {
static int readNum(FILE* f) nothrow @nogc {
int n;
while (!fscanf(f, "%d ", &n)) {
if ((n = fgetc(f)) == '#') {
while ((n = fgetc(f)) != '\n')
if (n == EOF)
return 0;
} else
return 0;
}
return n;
}
if (img is null)
img = new Image!Color();
auto fin = fopen(fileName.toStringz(), "rb");
scope(exit) if (fin) fclose(fin);
if (!fin)
throw new Exception("Can't open input file.");
if (fgetc(fin) != 'P' ||
fgetc(fin) != '5' ||
!isWhite(fgetc(fin)))
throw new Exception("Not a PGM (PPM P5) image.");
immutable int nc = readNum(fin);
immutable int nr = readNum(fin);
immutable int maxVal = readNum(fin);
if (nc <= 0 || nr <= 0 || maxVal <= 0)
throw new Exception("Wrong input image sizes.");
img.allocate(nc, nr);
auto pix = new ubyte[img.image.length];
immutable count = fread(pix.ptr, 1, nc * nr, fin);
if (count != nc * nr)
throw new Exception("Wrong number of items read.");
pix.copy(img.image);
return img;
}
void savePGM(Color)(in Image!Color img, in string fileName)
in {
assert(img !is null);
assert(!fileName.empty);
assert(img.nx > 0 && img.ny > 0 &&
img.image.length == img.nx * img.ny,
"Wrong image.");
} body {
auto fout = fopen(fileName.toStringz(), "wb");
if (fout == null)
throw new Exception("File can't be opened.");
fprintf(fout, "P5\n%d %d\n255\n", img.nx, img.ny);
auto pix = new ubyte[img.image.length];
foreach (i, ref p; pix)
p = cast(typeof(pix[0]))img.image[i];
immutable count = fwrite(pix.ptr, ubyte.sizeof,
img.nx * img.ny, fout);
if (count != img.nx * img.ny)
new Exception("Wrong number of items written.");
fclose(fout);
}
Gray lumCIE(in RGB c) pure nothrow @nogc {
return Gray(cast(ubyte)(0.2126 * c.r +
0.7152 * c.g +
0.0722 * c.b + 0.5));
}
Gray lumAVG(in RGB c) pure nothrow @nogc {
return Gray(cast(ubyte)(0.3333 * c.r +
0.3333 * c.g +
0.3333 * c.b + 0.5));
}
Image!Gray rgb2grayImage(alias Conv=lumCIE)(in Image!RGB im) nothrow {
auto result = new typeof(return)(im.nx, im.ny);
foreach (immutable i, immutable rgb; im.image)
result.image[i] = Conv(rgb);
return result;
}
Image!RGB gray2rgbImage(in Image!Gray im) nothrow {
auto result = new typeof(return)(im.nx, im.ny);
foreach (immutable i, immutable gr; im.image)
result.image[i] = RGB(gr, gr, gr);
return result;
}
version (grayscale_image_main) {
void main() {
auto im1 = new Image!Gray;
im1.loadPGM("lena.pgm");
gray2rgbImage(im1).savePPM6("lena_rgb.ppm");
auto img2 = new Image!RGB;
img2.loadPPM6("quantum_frog.ppm");
img2.rgb2grayImage.savePGM("quantum_frog_grey.pgm");
}
}
|
http://rosettacode.org/wiki/Go_Fish
|
Go Fish
|
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#D
|
D
|
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13)
Dim Shared As String nombre, Snombre, CartaPedida
Dim Shared puntos(2) As Byte = {0,0}
Dim Shared As Integer remca = 4*Len(cartas)
Dim Shared As Integer i, k, j, cn
For i = 1 To 13
deck(i) = 4
Next i
For i = 1 To 9
Reparto_Cartas
deck(k) -= 1
compu(k) += 1
Reparto_Cartas
deck(k) -= 1
play(k) += 1
Next i
Dim As Integer v, po
Sub Reparto_Cartas
remca -= 1
Dim As Integer sc = remca * Rnd + 1
For k = 1 To 13
sc -= deck(k)
If sc <= 0 Then Return
Next k
End Sub
Sub Pescar_Carta_Jug
Reparto_Cartas
Print " " &Mid(cartas,k,1) &"."
deck(k) -= 1
play(k) += 1
End Sub
Sub Pescar_Carta_CPU
Reparto_Cartas
Print "a carta."
deck(k) -= 1
compu(k) += 1
End Sub
Sub Comprobar_Libro_Jug
For i = 1 To 13
If play(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
play(i) = 0
puntos(0) += 1
End If
Next i
End Sub
Sub Comprobar_Libro_CPU
For i = 1 To 13
If compu(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
compu(i) = 0
puntos(1) += 1
End If
Next i
End Sub
Sub Comprobar_Fin_Partida
Dim As Integer np = 0, nc = 0
For i = 1 To 13
np += play(i)
nc += compu(i)
Next i
If remca = 0 Or np = 0 Or nc = 0 Then
Color 15: Print
Print "*** FIN de la partida! ***"
Print
If puntos(0) < puntos(1) Then
Print "La CPU ha ganado."
Elseif puntos(0) > puntos(1) Then
Print nombre &" ha ganado."
Else
Print "Es un empate!"
End If
Sleep: End
End If
End Sub
Sub Intro
Color 15
Print " __ _ _ "
Print " __ _ ___ / _(_)___| |__ "
Print " / ` |/ _ \ | |_| / __| '_ \ "
Print "| (_) | (_) | | _| \__ \ | | | "
Print " \__, |\___/ |_| |_|___/_| |_| "
Print " |___/ "
Print " "
Color 14: Locate 10, 2: Input "Como te llamas: ", nombre
End Sub
'--- Programa Principal ---
Cls
Randomize Timer
Intro
Do
Dim As boolean MuestraMano = false
While MuestraMano = false
Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1)
Color 13: Print Chr(10) &space(10) &remca &" cartas restantes"
Color 14: Print Chr(10) &"Tu mano: ";
For i = 1 To 13
If Not play(i) Then
For j = 1 To play(i)
Print Mid(cartas,i,1); " ";
Next j
End If
Next i
Print
Dim As boolean PideCarta = false
While PideCarta = false
Comprobar_Fin_Partida
Snombre = nombre
Color 7: Print
Input "¨Que carta pides... "; CartaPedida
Print
If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true
If cn = 0 Then
Print "Lo siento, no es una opción valida.": PideCarta = false
Elseif play(cn) = 0 Then Color 12: Print "No tienes esa carta!": Color 7: PideCarta = false
End If
Wend
guess(cn) = 1
If compu(cn) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug
Comprobar_Libro_Jug
MuestraMano = true
Else
v = compu(cn)
compu(cn) = 0
play(cn) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_Jug
MuestraMano = false
End If
Wend
Snombre = "CPU"
For i = 1 To 13
asked(i) = 0
Next i
Dim As boolean Turno_CPU_2 = false
While Turno_CPU_2 = false
Comprobar_Fin_Partida
po = 0
For i = 1 To 13
If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1
Next i
If po = 0 Then
Do
k = (Rnd*12)+1
Loop While compu(k) = 0 Or asked(k)
Else
Do
k = (Rnd*12)+1
Loop While poss(k) = 0
guess(k) = 0
asked(k) = 1
End If
Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s."
asked(k) = 1
If play(k) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU
Comprobar_Libro_CPU
Turno_CPU_2 = true
Else
v = play(k)
play(k) = 0
compu(k) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_CPU
Turno_CPU_2 = false
End If
Wend
Loop
End
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ham;
size_t alloc = 0, n = 1;
ham *q = 0;
void qpush(ham h)
{
int i, j;
if (alloc <= n) {
alloc = alloc ? alloc * 2 : 16;
q = realloc(q, sizeof(ham) * alloc);
}
for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
q[i] = h;
}
ham qpop()
{
int i, j;
ham r, t;
/* outer loop for skipping duplicates */
for (r = q[1]; n > 1 && r == q[1]; q[i] = t) {
/* inner loop is the normal down heap routine */
for (i = 1, t = q[--n]; (j = i * 2) < n;) {
if (j + 1 < n && q[j] > q[j+1]) j++;
if (t <= q[j]) break;
q[i] = q[j], i = j;
}
}
return r;
}
int main()
{
int i;
ham h;
for (qpush(i = 1); i <= 1691; i++) {
/* takes smallest value, and queue its multiples */
h = qpop();
qpush(h * 2);
qpush(h * 3);
qpush(h * 5);
if (i <= 20 || i == 1691)
printf("%6d: %llu\n", i, h);
}
/* free(q); */
return 0;
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Crystal
|
Crystal
|
n = rand(1..10)
puts "Guess the number: 1..10"
until gets.to_s.to_i == n; puts "Wrong! Guess again: " end
puts "Well guessed!"
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#D
|
D
|
void main() {
immutable num = uniform(1, 10).text;
do write("What's next guess (1 - 9)? ");
while (readln.strip != num);
writeln("Yep, you guessed my ", num);
}
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#CoffeeScript
|
CoffeeScript
|
max_sum_seq = (sequence) ->
# This runs in linear time.
[sum_start, sum, max_sum, max_start, max_end] = [0, 0, 0, 0, 0]
for n, i in sequence
sum += n
if sum > max_sum
max_sum = sum
max_start = sum_start
max_end = i + 1
if sum < 0 # start new sequence
sum = 0
sum_start = i + 1
sequence[max_start...max_end]
# tests
console.log max_sum_seq [-1, 0, 15, 3, -9, 12, -4]
console.log max_sum_seq [-1]
console.log max_sum_seq [4, -10, 3]
|
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
|
GUI enabling/disabling of controls
|
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a program
that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("decrement")
The field is initialized to zero.
The user may manually enter a new value into the field,
increment its value with the "increment" button,
or decrement the value with the "decrement" button.
The input field should be enabled only when its value is zero.
The "increment" button only as long as the field's value is less then 10:
When the value 10 is reached, the button should go into a disabled state.
Analogously, the "decrement" button should be enabled only as long as
the value is greater than zero.
Effectively, the user can now either increment up to 10, or down to zero.
Manually entering values outside that range is still legal,
but the buttons should reflect that and enable/disable accordingly.
|
#Tcl
|
Tcl
|
package require Tk
# Model
set field 0
# View
place [ttk::frame .bg] -relwidth 1 -relheight 1; # Hack to make things look nice
pack [ttk::labelframe .val -text "Value"]
pack [ttk::entry .val.ue -textvariable field \
-validate key -invalidcommand bell \
-validatecommand {string is integer %P}]
pack [ttk::button .inc -text "increment" -command up]
pack [ttk::button .dec -text "decrement" -command down]
# Controller
proc up {} {
global field
incr field
}
proc down {} {
global field
incr field -1
}
# Attach this controller to the Model; easier than manual calling
trace add variable field write updateEnables
proc updateEnables {args} {
global field
.inc state [expr {$field < 10 ? "!disabled" : "disabled"}]
.dec state [expr {$field > 0 ? "!disabled" : "disabled"}]
}
updateEnables; # Force initial state of buttons
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
GUESSNUM
; get a random number between 1 and 100
set target = ($random(100) + 1) ; $r(100) gives 0-99
; loop until correct
set tries = 0
for {
write !,"Guess the integer between 1 and 100: "
read "",guess ; gets input following write
; validate input
if (guess?.N) && (guess > 0) && (guess < 101) {
; increment attempts
set tries = tries + 1
; evaluate the guess
set resp = $select(guess < target:"too low.",guess > target:"too high.",1:"correct!")
; display result, conditionally exit loop
write !,"Your guess was "_resp
quit:resp="correct!"
}
else {
write !,"Please enter an integer between 1 and 100."
}
} ; guess loop
write !!,"You guessed the number in "_tries_" attempts."
quit
|
http://rosettacode.org/wiki/Greyscale_bars/Display
|
Greyscale bars/Display
|
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)
For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).
Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
|
#Nim
|
Nim
|
import gintro/[glib, gobject, gtk, gio, cairo]
const
Width = 640
Height = 480
#---------------------------------------------------------------------------------------------------
proc draw(area: DrawingArea; context: Context) =
## Draw the greyscale bars.
const
Black = 0.0
White = 1.0
var y = 0.0
var nrect = 8
let rectHeight = Height / 4
# Draw quarters.
for quarter in 0..3:
let rectWidth = Width / nrect
var x = 0.0
var (grey, incr) = if (quarter and 1) == 0: (Black, 1 / nrect) else: (White, -1 / nrect)
# Draw rectangles.
for _ in 1..nrect:
context.rectangle(x, y, rectWidth, rectHeight)
context.setSource([grey, grey, grey])
context.fill()
x += rectWidth
grey += incr
y += rectHeight
nrect *= 2
#---------------------------------------------------------------------------------------------------
proc onDraw(area: DrawingArea; context: Context; data: pointer): bool =
## Callback to draw/redraw the drawing area contents.
area.draw(context)
result = true
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setSizeRequest(Width, Height)
window.setTitle("Greyscale bars")
# Create the drawing area.
let area = newDrawingArea()
window.add(area)
# Connect the "draw" event to the callback to draw the spiral.
discard area.connect("draw", ondraw, pointer(nil))
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.GreyscaleBars")
discard app.connect("activate", activate)
discard app.run()
|
http://rosettacode.org/wiki/Greyscale_bars/Display
|
Greyscale bars/Display
|
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)
For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).
Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
|
#OCaml
|
OCaml
|
open Graphics
let round x = truncate (floor (x +. 0.5))
let () =
open_graph "";
let width = size_x ()
and height = size_y () in
let bars = [| 8; 16; 32; 64 |] in
let n = Array.length bars in
Array.iteri (fun i bar ->
let part = float width /. float bar in
let y = (height / n) * (n - i - 1) in
for j = 0 to pred bar do
let x = round (float j *. part) in
let v = round (float j *. 255. /. float (bar - 1)) in
let v = if (i mod 2) = 0 then v else 255 - v in
set_color (rgb v v v);
fill_rect x y (round part) (height / n)
done
) bars;
ignore(read_key())
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#Lua
|
Lua
|
function wait(waittime)--wait function is used so that app will not quit immediately
local timer = os.time()
repeat until os.time() == timer + waittime
end
upperBound = 100
lowerBound = 0
print("Think of an integer between 1 to 100.")
print("I will try to guess it.")
while true do
upper1 = upperBound+1
upper2 = upperBound-1
if upperBound == lowerBound or upper1 == lowerBound or upper2 == lowerBound or lowerBound > upperBound then--make sure player is not cheating
io.write("You're cheating! I'm not playing anymore. Goodbye.")
wait(3)
break
else
Guess = math.floor((upperBound + lowerBound)/2)--guessing mechanism
print("My guess is: "..Guess..". Is it too high, too low, or correct? (h/l/c)")
input = io.read()
if input == "h" then --higher
upperBound = Guess
elseif input == "l" then --lower
lowerBound = Guess
elseif input == "c" then --correct
io.write("So I win? Thanks for playing with me.")
wait(3)
break
else
print("Invalid input. Please try again. ")
end
end
end
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
guessnumber[min0_, max0_] :=
DynamicModule[{min = min0, max = max0, guess, correct = False},
guess[] := Round@Mean@{min, max};
Dynamic@If[correct, Row@{"Your number is ", guess[], "."},
Column@{Row@{"I guess ", guess[], "."},
Row@{Button["too high", max = guess[]],
Button["too low", min = guess[]],
Button["correct", correct = True]}}]];
guessnumber[1, 100]
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Delphi
|
Delphi
|
program Happy_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Int;
type
TIntegerDynArray = TArray<Integer>;
TIntHelper = record helper for Integer
function IsHappy: Boolean;
procedure Next;
end;
{ TIntHelper }
function TIntHelper.IsHappy: Boolean;
var
cache: TIntegerDynArray;
sum, n: integer;
begin
n := self;
repeat
sum := 0;
while n > 0 do
begin
sum := sum + (n mod 10) * (n mod 10);
n := n div 10;
end;
if sum = 1 then
exit(True);
if cache.Has(sum) then
exit(False);
n := sum;
cache.Add(sum);
until false;
end;
procedure TIntHelper.Next;
begin
inc(self);
end;
var
count, n: integer;
begin
n := 1;
count := 0;
while count < 8 do
begin
if n.IsHappy then
begin
count.Next;
write(n, ' ');
end;
n.Next;
end;
writeln;
readln;
end.
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Maxima
|
Maxima
|
dms(d, m, s) := (d + m/60 + s/3600)*%pi/180$
great_circle_distance(lat1, long1, lat2, long2) :=
12742*asin(sqrt(sin((lat2 - lat1)/2)^2 + cos(lat1)*cos(lat2)*sin((long2 - long1)/2)^2))$
/* Coordinates are found here:
http://www.airport-data.com/airport/BNA/
http://www.airport-data.com/airport/LAX/ */
great_circle_distance(dms( 36, 7, 28.10), -dms( 86, 40, 41.50),
dms( 33, 56, 32.98), -dms(118, 24, 29.05)), numer;
/* 2886.326609413624 */
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#.D0.9C.D0.9A-61.2F52
|
МК-61/52
|
П3 -> П2 -> П1 -> П0
пи 1 8 0 / П4
ИП1 МГ ИП3 МГ - ИП4 * П1 ИП0 МГ ИП4 * П0 ИП2 МГ ИП4 * П2
ИП0 sin ИП2 sin - П8
ИП1 cos ИП0 cos * ИП2 cos - П6
ИП1 sin ИП0 cos * П7
ИП6 x^2 ИП7 x^2 ИП8 x^2 + + КвКор 2 / arcsin 2 * ИП5 * С/П
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#GB_BASIC
|
GB BASIC
|
10 print "Hello world!"
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Vlang
|
Vlang
|
fn main() {
keys := ["a", "b", "c"]
vals := [1, 2, 3]
mut hash := map[string]int{}
for i, key in keys {
hash[key] = vals[i]
}
println(hash)
}
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Wortel
|
Wortel
|
@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Oforth
|
Oforth
|
: sumDigits(n) 0 while(n) [ n 10 /mod ->n + ] ;
: isHarshad dup sumDigits mod 0 == ;
1100 seq filter(#isHarshad) dup left(20) println dup filter(#[ 1000 > ]) first println
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Integer_BASIC
|
Integer BASIC
|
10 REM FONT DERIVED FROM 04B-09 BY YUJI OSHIMOTO
20 GR
30 COLOR = 12
40 REM G
50 HLIN 0,5 AT 0 : HLIN 0,5 AT 1
60 VLIN 2,9 AT 0 : VLIN 2,9 AT 1
70 HLIN 2,5 AT 9 : HLIN 2,5 AT 8
80 VLIN 4,7 AT 5 : VLIN 4,7 AT 4
90 VLIN 4,5 AT 3
100 REM O
110 HLIN 7,12 AT 2 : HLIN 7,12 AT 3
120 HLIN 7,12 AT 8 : HLIN 7,12 AT 9
130 VLIN 4,7 AT 7 : VLIN 4,7 AT 8
140 VLIN 4,7 AT 11 : VLIN 4,7 AT 12
150 REM O
160 HLIN 14,19 AT 2 : HLIN 14,19 AT 3
170 HLIN 14,19 AT 8 : HLIN 14,19 AT 9
180 VLIN 4,7 AT 14 : VLIN 4,7 AT 15
190 VLIN 4,7 AT 18 : VLIN 4,7 AT 19
200 REM D
210 HLIN 21,24 AT 2 : HLIN 21,24 AT 3
220 HLIN 21,26 AT 8 : HLIN 21,26 AT 9
230 VLIN 4,7 AT 21 : VLIN 4,7 AT 22
240 VLIN 0,7 AT 25 : VLIN 0,7 AT 26
250 REM -
260 HLIN 28,33 AT 4 : HLIN 28,33 AT 5
270 REM B
280 VLIN 11,20 AT 0 : VLIN 11,20 AT 1
290 HLIN 2,5 AT 20 : HLIN 2,5 AT 19
300 VLIN 15,18 AT 5 : VLIN 15,18 AT 4
310 HLIN 2,5 AT 14 : HLIN 2,5 AT 13
320 REM Y
330 VLIN 13,20 AT 7 : VLIN 13,20 AT 8
340 VLIN 19,20 AT 9 : VLIN 19,20 AT 10
350 VLIN 13,24 AT 11 : VLIN 13,24 AT 12
360 VLIN 23,24 AT 10 : VLIN 23,24 AT 9
370 REM E
380 VLIN 13,20 AT 14 : VLIN 13,20 AT 15
390 HLIN 16,19 AT 13 : HLIN 16,19 AT 14
400 HLIN 18,19 AT 15 : HLIN 18,19 AT 16
410 HLIN 16,17 AT 17 : HLIN 16,17 AT 18
420 HLIN 16,19 AT 19 : HLIN 16,19 AT 20
430 REM ,
440 VLIN 17,22 AT 21 : VLIN 17,22 AT 22
450 REM W
460 VLIN 24,33 AT 0 : VLIN 24,33 AT 1 : VLIN 24,33 AT 3
470 VLIN 24,33 AT 4 : VLIN 24,33 AT 6 : VLIN 24,33 AT 7
480 HLIN 0,7 AT 33 : HLIN 0,7 AT 32
490 REM O
500 HLIN 9,14 AT 26 : HLIN 9,14 AT 27
510 HLIN 9,14 AT 32 : HLIN 9,14 AT 33
520 VLIN 28,31 AT 9 : VLIN 28,31 AT 10
530 VLIN 28,31 AT 13 : VLIN 28,31 AT 14
540 REM R
550 HLIN 16,21 AT 26 : HLIN 16,21 AT 27
560 VLIN 28,33 AT 16 : VLIN 28,33 AT 17
570 REM L
580 VLIN 24,33 AT 23 : VLIN 24,33 AT 24
590 REM D
600 HLIN 26,29 AT 26 : HLIN 26,29 AT 27
610 HLIN 26,29 AT 32 : HLIN 26,29 AT 33
620 VLIN 28,33 AT 26 : VLIN 28,33 AT 27
630 VLIN 24,33 AT 30 : VLIN 24,33 AT 31
640 REM !
650 VLIN 24,29 AT 33 : VLIN 24,29 AT 34
660 VLIN 32,33 AT 33 : VLIN 32,33 AT 34
670 END
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Ioke
|
Ioke
|
import(
:javax:swing, :JOptionPane, :JFrame, :JTextArea, :JButton
)
import java:awt:FlowLayout
JOptionPane showMessageDialog(nil, "Goodbye, World!")
button = JButton new("Goodbye, World!")
text = JTextArea new("Goodbye, World!")
window = JFrame new("Goodbye, World!") do(
layout = FlowLayout new
add(button)
add(text)
pack
setDefaultCloseOperation(JFrame field:EXIT_ON_CLOSE)
visible = true
)
|
http://rosettacode.org/wiki/GUI_component_interaction
|
GUI component interaction
|
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dialogs to query the user for further information
Task
For a minimal "application", write a program that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("random")
The field is initialized to zero.
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
Entering a non-numeric value should be either impossible,
or issue an error message.
Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".
(This task may be regarded as an extension of the task Simple windowed application).
|
#PicoLisp
|
PicoLisp
|
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
(de start ()
(and (app) (zero *Number))
(action
(html 0 "Increment" "@lib.css" NIL
(form NIL
(gui '(+Var +NumField) '*Number 20 "Value")
(gui '(+JS +Button) "increment"
'(inc '*Number) )
(gui '(+Button) "random"
'(ask "Reset to a random value?"
(setq *Number (rand)) ) ) ) ) ) )
(server 8080 "!start")
(wait)
|
http://rosettacode.org/wiki/GUI_component_interaction
|
GUI component interaction
|
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dialogs to query the user for further information
Task
For a minimal "application", write a program that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("random")
The field is initialized to zero.
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
Entering a non-numeric value should be either impossible,
or issue an error message.
Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".
(This task may be regarded as an extension of the task Simple windowed application).
|
#PowerShell
|
PowerShell
|
[xml]$XML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Rosetta Code" WindowStartupLocation = "CenterScreen" Height="100" Width="210" ResizeMode="NoResize">
<Grid Background="#FFC1C3CB">
<Label Name="Label_Value" Content="Value" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="70"/>
<TextBox Name="TextBox_Value" HorizontalAlignment="Left" Height="23" Margin="90,10,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="100"/>
<Button Name="Button_Random" Content="Random" HorizontalAlignment="Left" Margin="10,41,0,0" VerticalAlignment="Top" Width="70" Height="23"/>
<Button Name="Button_Increment" Content="Increment" HorizontalAlignment="Left" Margin="90,41,0,0" VerticalAlignment="Top" Width="100" Height="23"/>
</Grid>
</Window>
"@
$XMLReader = New-Object System.Xml.XmlNodeReader $XML
$XMLForm = [Windows.Markup.XamlReader]::Load($XMLReader)
$buttonIncrement = $XMLForm.FindName('Button_Increment')
$buttonRandom = $XMLForm.FindName('Button_Random')
$textBoxValue = $XMLForm.FindName('TextBox_Value')
$buttonRandom.add_click({
$textBoxValue.Text = Get-Random -Minimum 0 -Maximum 10000
})
$buttonIncrement.add_click({++[Int]$textBoxValue.Text})
$XMLForm.ShowDialog() | Out-Null
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Ada
|
Ada
|
with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
procedure Gray is
Bits : constant := 5; -- Change only this line for 6 or 7-bit encodings
subtype Values is Unsigned_8 range 0 .. 2 ** Bits - 1;
package Values_Io is new Ada.Text_IO.Modular_IO (Values);
function Encode (Binary : Values) return Values is
begin
return Binary xor Shift_Right (Binary, 1);
end Encode;
pragma Inline (Encode);
function Decode (Gray : Values) return Values is
Binary, Bit : Values;
Mask : Values := 2 ** (Bits - 1);
begin
Bit := Gray and Mask;
Binary := Bit;
for I in 2 .. Bits loop
Bit := Shift_Right (Bit, 1);
Mask := Shift_Right (Mask, 1);
Bit := (Gray and Mask) xor Bit;
Binary := Binary + Bit;
end loop;
return Binary;
end Decode;
pragma Inline (Decode);
HT : constant Character := Character'Val (9);
J : Values;
begin
Put_Line ("Num" & HT & "Binary" & HT & HT & "Gray" & HT & HT & "decoded");
for I in Values'Range loop
J := Encode (I);
Values_Io.Put (I, 4);
Put (": " & HT);
Values_Io.Put (I, Bits + 2, 2);
Put (" =>" & HT);
Values_Io.Put (J, Bits + 2, 2);
Put (" => " & HT);
Values_Io.Put (Decode (J), 4);
New_Line;
end loop;
end Gray;
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Action.21
|
Action!
|
BYTE FUNC Max(BYTE ARRAY tab BYTE size)
BYTE i,res
res=tab(0)
FOR i=1 TO size-1
DO
IF res<tab(i) THEN
res=tab(i)
FI
OD
RETURN (res)
PROC Main()
BYTE i,m,size=[20]
BYTE ARRAY tab(size)
FOR i=0 TO size-1
DO
tab(i)=Rand(0)
OD
Print("Array:")
FOR i=0 TO size-1
DO
PrintF(" %I",tab(i))
OD
PutE()
m=Max(tab,size)
PrintF("Greatest: %I%E",m)
RETURN
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#360_Assembly
|
360 Assembly
|
* Hailstone sequence 16/08/2015
HAILSTON CSECT
USING HAILSTON,R12
LR R12,R15
ST R14,SAVER14
BEGIN L R11,=F'100000' nmax
LA R8,27 n=27
LR R1,R8
MVI FTAB,X'01' ftab=true
BAL R14,COLLATZ
LR R10,R1 p
XDECO R8,XDEC n
MVC BUF1+10(6),XDEC+6
XDECO R10,XDEC p
MVC BUF1+18(5),XDEC+7
LA R5,6
LA R3,0 i
LA R4,BUF1+25
LOOPED L R2,TAB(R3) tab(i)
XDECO R2,XDEC
MVC 0(7,R4),XDEC+5
LA R3,4(R3) i=i+1
LA R4,7(R4)
C R5,=F'4'
BNE BCT
LA R4,7(R4)
BCT BCT R5,LOOPED
XPRNT BUF1,80 print hailstone(n)=p,tab(*)
MVC LONGEST,=F'0' longest=0
MVI FTAB,X'00' ftab=true
LA R8,1 i
LOOPI CR R8,R11 do i=1 to nmax
BH ELOOPI
LR R1,R8 n
BAL R14,COLLATZ
LR R10,R1 p
L R4,LONGEST
CR R4,R10 if longest<p
BNL NOTSUP
ST R8,IVAL ival=i
ST R10,LONGEST longest=p
NOTSUP LA R8,1(R8) i=i+1
B LOOPI
ELOOPI EQU * end i
XDECO R11,XDEC maxn
MVC BUF2+9(6),XDEC+6
L R1,IVAL ival
XDECO R1,XDEC
MVC BUF2+28(6),XDEC+6
L R1,LONGEST longest
XDECO R1,XDEC
MVC BUF2+36(5),XDEC+7
XPRNT BUF2,80 print maxn,hailstone(ival)=longest
B RETURN
* * * r1=collatz(r1)
COLLATZ LR R7,R1 m=n (R7)
LA R6,1 p=1 (R6)
LOOPP C R7,=F'1' do p=1 by 1 while(m>1)
BNH ELOOPP
CLI FTAB,X'01' if ftab
BNE NONOK
C R6,=F'1' if p>=1
BL NONOK
C R6,=F'3' & p<=3
BH NONOK
LR R1,R6 then
BCTR R1,0
SLA R1,2
ST R7,TAB(R1) tab(p)=m
NONOK LR R4,R7 m
N R4,=F'1' m&1
LTR R4,R4 if m//2=0 (if not(m&1))
BNZ ODD
EVEN SRA R7,1 m=m/2
B EIFM
ODD LA R3,3
MR R2,R7 *m
LA R7,1(R3) m=m*3+1
EIFM CLI FTAB,X'01' if ftab
BNE NEXTP
MVC TAB+12,TAB+16 tab(4)=tab(5)
MVC TAB+16,TAB+20 tab(5)=tab(6)
ST R7,TAB+20 tab(6)=m
NEXTP LA R6,1(R6) p=p+1
B LOOPP
ELOOPP LR R1,R6 end p; return(p)
BR R14 end collatz
*
RETURN L R14,SAVER14 restore caller address
XR R15,R15 set return code
BR R14 return to caller
SAVER14 DS F
IVAL DS F
LONGEST DS F
N DS F
TAB DS 6F
FTAB DS X
BUF1 DC CL80'hailstone(nnnnnn)=nnnnn : nnnnnn nnnnnn nnnnnn ...*
... nnnnnn nnnnnn nnnnnn'
BUF2 DC CL80'longest <nnnnnn : hailstone(nnnnnn)=nnnnn'
XDEC DS CL12
YREGS
END HAILSTON
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Nim
|
Nim
|
import algorithm, sequtils, strscans, strutils, tables
const NoColor = 0
type
Color = range[0..63]
Node = ref object
num: Natural # Node number.
color: Color # Node color.
degree: Natural # Node degree.
dsat: Natural # Node Dsaturation.
neighbors: seq[Node] # List of neighbors.
Graph = seq[Node] # List of nodes ordered by number.
#---------------------------------------------------------------------------------------------------
proc initGraph(graphRepr: string): Graph =
## Initialize the graph from its string representation.
var mapping: Table[Natural, Node] # Temporary mapping.
for elem in graphRepr.splitWhitespace():
var num1, num2: int
if elem.scanf("$i-$i", num1, num2):
let node1 = mapping.mgetOrPut(num1, Node(num: num1))
let node2 = mapping.mgetOrPut(num2, Node(num: num2))
node1.neighbors.add node2
node2.neighbors.add node1
elif elem.scanf("$i", num1):
discard mapping.mgetOrPut(num1, Node(num: num1))
else:
raise newException(ValueError, "wrong description: " & elem)
for node in mapping.values:
node.degree = node.neighbors.len
result = sortedByIt(toSeq(mapping.values), it.num)
#---------------------------------------------------------------------------------------------------
proc numbers(nodes: seq[Node]): string =
## Return the numbers of a list of nodes.
for node in nodes:
result.addSep(" ")
result.add($node.num)
#---------------------------------------------------------------------------------------------------
proc `$`(graph: Graph): string =
## Return the description of the graph.
var maxColor = NoColor
for node in graph:
stdout.write "Node ", node.num, ": color = ", node.color
if node.color > maxColor: maxColor = node.color
if node.neighbors.len > 0:
echo " neighbors = ", sortedByIt(node.neighbors, it.num).numbers
else:
echo ""
echo "Number of colors: ", maxColor
#---------------------------------------------------------------------------------------------------
proc `<`(node1, node2: Node): bool =
## Comparison of nodes, by dsaturation first, then by degree.
if node1.dsat == node2.dsat: node1.degree < node2.degree
else: node1.dsat < node2.dsat
#---------------------------------------------------------------------------------------------------
proc getMaxDsatNode(nodes: var seq[Node]): Node =
## Return the node with the greatest dsaturation.
let idx = nodes.maxIndex()
result = nodes[idx]
nodes.delete(idx)
#---------------------------------------------------------------------------------------------------
proc minColor(node: Node): COLOR =
## Return the minimum available color for a node.
var colorUsed: set[Color]
for neighbor in node.neighbors:
colorUsed.incl neighbor.color
for color in 1..Color.high:
if color notin colorUsed: return color
#---------------------------------------------------------------------------------------------------
proc distinctColorsCount(node: Node): Natural =
## Return the number of distinct colors of the neighbors of a node.
var colorUsed: set[Color]
for neighbor in node.neighbors:
colorUsed.incl neighbor.color
result = colorUsed.card
#---------------------------------------------------------------------------------------------------
proc updateDsats(node: Node) =
## Update the dsaturations of the neighbors of a node.
for neighbor in node.neighbors:
if neighbor.color == NoColor:
neighbor.dsat = neighbor.distinctColorsCount()
#---------------------------------------------------------------------------------------------------
proc colorize(graphRepr: string) =
## Colorize a graph.
let graph = initGraph(graphRepr)
var nodes = sortedByIt(graph, -it.degree) # Copy or graph sorted by decreasing degrees.
while nodes.len > 0:
let node = nodes.getMaxDsatNode()
node.color = node.minColor()
node.updateDsats()
echo "Graph: ", graphRepr
echo graph
#---------------------------------------------------------------------------------------------------
when isMainModule:
colorize("0-1 1-2 2-0 3")
colorize("1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7")
colorize("1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6")
colorize("1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7")
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Perl
|
Perl
|
use strict;
use warnings;
no warnings 'uninitialized';
use feature 'say';
use constant True => 1;
use List::Util qw(head uniq);
sub GraphNodeColor {
my(%OneMany, %NodeColor, %NodePool, @ColorPool);
my(@data) = @_;
for (@data) {
my($a,$b) = @$_;
push @{$OneMany{$a}}, $b;
push @{$OneMany{$b}}, $a;
}
@ColorPool = 0 .. -1 + scalar %OneMany;
$NodePool{$_} = True for keys %OneMany;
if ($OneMany{''}) { # skip islanders for now
delete $NodePool{$_} for @{$OneMany{''}};
delete $NodePool{''};
}
while (%NodePool) {
my $color = shift @ColorPool;
my %TempPool = %NodePool;
while (my $n = head 1, sort keys %TempPool) {
$NodeColor{$n} = $color;
delete $TempPool{$n};
delete $TempPool{$_} for @{$OneMany{$n}} ; # skip neighbors as well
delete $NodePool{$n};
}
if ($OneMany{''}) { # islanders use an existing color
$NodeColor{$_} = head 1, sort values %NodeColor for @{$OneMany{''}};
}
}
%NodeColor
}
my @DATA = (
[ [1,2],[2,3],[3,1],[4,undef],[5,undef],[6,undef] ],
[ [1,6],[1,7],[1,8],[2,5],[2,7],[2,8],[3,5],[3,6],[3,8],[4,5],[4,6],[4,7] ],
[ [1,4],[1,6],[1,8],[3,2],[3,6],[3,8],[5,2],[5,4],[5,8],[7,2],[7,4],[7,6] ],
[ [1,6],[7,1],[8,1],[5,2],[2,7],[2,8],[3,5],[6,3],[3,8],[4,5],[4,6],[4,7] ]
);
for my $d (@DATA) {
my %result = GraphNodeColor @$d;
my($graph,$colors);
$graph .= '(' . join(' ', @$_) . '), ' for @$d;
$colors .= ' ' . $result{$$_[0]} . '-' . ($result{$$_[1]} // '') . ' ' for @$d;
say 'Graph : ' . $graph =~ s/,\s*$//r;
say 'Colors : ' . $colors;
say 'Nodes : ' . keys %result;
say 'Edges : ' . @$d;
say 'Unique : ' . uniq values %result;
say '';
}
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[GoldbachFuncion]
GoldbachFuncion[e_Integer] := Module[{ps},
ps = Prime[Range[PrimePi[e/2]]];
Total[Boole[PrimeQ[e - ps]]]
]
Grid[Partition[GoldbachFuncion /@ Range[4, 220, 2], 10]]
GoldbachFuncion[10^6]
DiscretePlot[GoldbachFuncion[e], {e, 4, 2000}, Filling -> None]
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use List::Util 'max';
use GD::Graph::bars;
use ntheory 'is_prime';
sub table { my $t = shift() * (my $c = 1 + max map {length} @_); ( sprintf( ('%'.$c.'s')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub G {
my($n) = @_;
scalar grep { is_prime($_) and is_prime($n - $_) } 2 .. $n/2;
}
my @y;
push @y, G(2*$_ + 4) for my @x = 0..1999;
say $_ for table 10, @y;
printf "G $_: %d", G($_) for 1e6;
my @data = ( \@x, \@y);
my $graph = GD::Graph::bars->new(1200, 400);
$graph->set(
title => q/Goldbach's Comet/,
y_max_value => 170,
x_tick_number => 10,
r_margin => 10,
dclrs => [ 'blue' ],
) or die $graph->error;
my $gd = $graph->plot(\@data) or die $graph->error;
open my $fh, '>', 'goldbachs-comet.png';
binmode $fh;
print $fh $gd->png();
close $fh;
|
http://rosettacode.org/wiki/Grayscale_image
|
Grayscale image
|
Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#Delphi
|
Delphi
|
-module(ros_bitmap).
-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]).
-record(bitmap, {
mode = rgb,
pixels = nil,
shape = {0, 0}
}).
tuple_to_bytes({rgb, R, G, B}) ->
<<R:8, G:8, B:8>>;
tuple_to_bytes({gray, L}) ->
<<L:8>>.
bytes_to_tuple(rgb, Bytes) ->
<<R:8, G:8, B:8>> = Bytes,
{rgb, R, G, B};
bytes_to_tuple(gray, Bytes) ->
<<L:8>> = Bytes,
{gray, L}.
new(Width, Height) ->
new(Width, Height, {rgb, 0, 0, 0}).
new(Width, Height, rgb) ->
new(Width, Height, {rgb, 0, 0, 0});
new(Width, Height, gray) ->
new(Width, Height, {gray, 0, 0, 0});
new(Width, Height, ColorTuple) when is_tuple(ColorTuple) ->
[Mode|Components] = tuple_to_list(ColorTuple),
Bytes = list_to_binary(Components),
#bitmap{
pixels=array:new(Width * Height, {default, Bytes}),
shape={Width, Height},
mode=Mode}.
fill(#bitmap{shape={Width, Height}, mode=Mode}, ColorTuple)
when element(1, ColorTuple) =:= Mode ->
new(Width, Height, ColorTuple).
set_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode}=Bitmap,
{at, X, Y}, ColorTuple) when element(1, ColorTuple) =:= Mode ->
Index = X + Y * Width,
Bitmap#bitmap{pixels=array:set(Index, tuple_to_bytes(ColorTuple), Pixels)}.
get_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode},
{at, X, Y}) ->
Index = X + Y * Width,
Bytes = array:get(Index, Pixels),
bytes_to_tuple(Mode, Bytes).
luminance(<<R:8, G:8, B:8>>) ->
<<(trunc(R * 0.2126 + G * 0.7152 + B * 0.0722))>>.
%% convert from rgb to grayscale
convert(#bitmap{pixels=Pixels, mode=rgb}=Bitmap, gray) ->
Bitmap#bitmap{
pixels=array:map(fun(_I, Pixel) ->
luminance(Pixel) end, Pixels),
mode=gray};
%% convert from grayscale to rgb
convert(#bitmap{pixels=Pixels, mode=gray}=Bitmap, rgb)->
Bitmap#bitmap{
pixels=array:map(fun(_I, <<L:8>>) -> <<L:8, L:8, L:8>> end, Pixels),
mode=rgb};
%% no conversion if the mode is the same with the bitmap.
convert(#bitmap{mode=Mode}=Bitmap, Mode) ->
Bitmap.
|
http://rosettacode.org/wiki/Go_Fish
|
Go Fish
|
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#Erlang
|
Erlang
|
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13)
Dim Shared As String nombre, Snombre, CartaPedida
Dim Shared puntos(2) As Byte = {0,0}
Dim Shared As Integer remca = 4*Len(cartas)
Dim Shared As Integer i, k, j, cn
For i = 1 To 13
deck(i) = 4
Next i
For i = 1 To 9
Reparto_Cartas
deck(k) -= 1
compu(k) += 1
Reparto_Cartas
deck(k) -= 1
play(k) += 1
Next i
Dim As Integer v, po
Sub Reparto_Cartas
remca -= 1
Dim As Integer sc = remca * Rnd + 1
For k = 1 To 13
sc -= deck(k)
If sc <= 0 Then Return
Next k
End Sub
Sub Pescar_Carta_Jug
Reparto_Cartas
Print " " &Mid(cartas,k,1) &"."
deck(k) -= 1
play(k) += 1
End Sub
Sub Pescar_Carta_CPU
Reparto_Cartas
Print "a carta."
deck(k) -= 1
compu(k) += 1
End Sub
Sub Comprobar_Libro_Jug
For i = 1 To 13
If play(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
play(i) = 0
puntos(0) += 1
End If
Next i
End Sub
Sub Comprobar_Libro_CPU
For i = 1 To 13
If compu(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
compu(i) = 0
puntos(1) += 1
End If
Next i
End Sub
Sub Comprobar_Fin_Partida
Dim As Integer np = 0, nc = 0
For i = 1 To 13
np += play(i)
nc += compu(i)
Next i
If remca = 0 Or np = 0 Or nc = 0 Then
Color 15: Print
Print "*** FIN de la partida! ***"
Print
If puntos(0) < puntos(1) Then
Print "La CPU ha ganado."
Elseif puntos(0) > puntos(1) Then
Print nombre &" ha ganado."
Else
Print "Es un empate!"
End If
Sleep: End
End If
End Sub
Sub Intro
Color 15
Print " __ _ _ "
Print " __ _ ___ / _(_)___| |__ "
Print " / ` |/ _ \ | |_| / __| '_ \ "
Print "| (_) | (_) | | _| \__ \ | | | "
Print " \__, |\___/ |_| |_|___/_| |_| "
Print " |___/ "
Print " "
Color 14: Locate 10, 2: Input "Como te llamas: ", nombre
End Sub
'--- Programa Principal ---
Cls
Randomize Timer
Intro
Do
Dim As boolean MuestraMano = false
While MuestraMano = false
Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1)
Color 13: Print Chr(10) &space(10) &remca &" cartas restantes"
Color 14: Print Chr(10) &"Tu mano: ";
For i = 1 To 13
If Not play(i) Then
For j = 1 To play(i)
Print Mid(cartas,i,1); " ";
Next j
End If
Next i
Print
Dim As boolean PideCarta = false
While PideCarta = false
Comprobar_Fin_Partida
Snombre = nombre
Color 7: Print
Input "¨Que carta pides... "; CartaPedida
Print
If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true
If cn = 0 Then
Print "Lo siento, no es una opción valida.": PideCarta = false
Elseif play(cn) = 0 Then Color 12: Print "No tienes esa carta!": Color 7: PideCarta = false
End If
Wend
guess(cn) = 1
If compu(cn) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug
Comprobar_Libro_Jug
MuestraMano = true
Else
v = compu(cn)
compu(cn) = 0
play(cn) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_Jug
MuestraMano = false
End If
Wend
Snombre = "CPU"
For i = 1 To 13
asked(i) = 0
Next i
Dim As boolean Turno_CPU_2 = false
While Turno_CPU_2 = false
Comprobar_Fin_Partida
po = 0
For i = 1 To 13
If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1
Next i
If po = 0 Then
Do
k = (Rnd*12)+1
Loop While compu(k) = 0 Or asked(k)
Else
Do
k = (Rnd*12)+1
Loop While poss(k) = 0
guess(k) = 0
asked(k) = 1
End If
Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s."
asked(k) = 1
If play(k) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU
Comprobar_Libro_CPU
Turno_CPU_2 = true
Else
v = play(k)
play(k) = 0
compu(k) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_CPU
Turno_CPU_2 = false
End If
Wend
Loop
End
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#C.23
|
C#
|
using System;
using System.Numerics;
using System.Linq;
namespace Hamming {
class MainClass {
public static BigInteger Hamming(int n) {
BigInteger two = 2, three = 3, five = 5;
var h = new BigInteger[n];
h[0] = 1;
BigInteger x2 = 2, x3 = 3, x5 = 5;
int i = 0, j = 0, k = 0;
for (int index = 1; index < n; index++) {
h[index] = BigInteger.Min(x2, BigInteger.Min(x3, x5));
if (h[index] == x2) x2 = two * h[++i];
if (h[index] == x3) x3 = three * h[++j];
if (h[index] == x5) x5 = five * h[++k];
}
return h[n - 1];
}
public static void Main(string[] args) {
Console.WriteLine(string.Join(" ", Enumerable.Range(1, 20).ToList().Select(x => Hamming(x))));
Console.WriteLine(Hamming(1691));
Console.WriteLine(Hamming(1000000));
}
}
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Dart
|
Dart
|
import 'dart:math';
import 'dart:io';
main() {
final n = (1 + new Random().nextInt(10)).toString();
print("Guess which number I've chosen in the range 1 to 10");
do { stdout.write(" Your guess : "); } while (n != stdin.readLineSync());
print("\nWell guessed!");
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#DCL
|
DCL
|
$ time = f$time()
$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
$ loop:
$ inquire guess "enter a guess (integer 1-10) "
$ if guess .nes. number then $ goto loop
$ write sys$output "Well guessed!"
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Common_Lisp
|
Common Lisp
|
(defun max-subseq (list)
(let ((best-sum 0) (current-sum 0) (end 0))
;; determine the best sum, and the end of the max subsequence
(do ((list list (rest list))
(i 0 (1+ i)))
((endp list))
(setf current-sum (max 0 (+ current-sum (first list))))
(when (> current-sum best-sum)
(setf end i
best-sum current-sum)))
;; take the subsequence of list ending at end, and remove elements
;; from the beginning until the subsequence sums to best-sum.
(let* ((sublist (subseq list 0 (1+ end)))
(sum (reduce #'+ sublist)))
(do ((start 0 (1+ start))
(sublist sublist (rest sublist))
(sum sum (- sum (first sublist))))
((or (endp sublist) (eql sum best-sum))
(values best-sum sublist start (1+ end)))))))
|
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
|
GUI enabling/disabling of controls
|
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a program
that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("decrement")
The field is initialized to zero.
The user may manually enter a new value into the field,
increment its value with the "increment" button,
or decrement the value with the "decrement" button.
The input field should be enabled only when its value is zero.
The "increment" button only as long as the field's value is less then 10:
When the value 10 is reached, the button should go into a disabled state.
Analogously, the "decrement" button should be enabled only as long as
the value is greater than zero.
Effectively, the user can now either increment up to 10, or down to zero.
Manually entering values outside that range is still legal,
but the buttons should reflect that and enable/disable accordingly.
|
#Vala
|
Vala
|
bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
if(!ret || str == ""){
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
"Invalid value");
dialog.run();
dialog.destroy();
}
if(str == ""){
ret = false;
}
return ret;
}
int main (string[] args) {
Gtk.init (ref args);
var window = new Gtk.Window();
window.title = "Rosetta Code";
window.window_position = Gtk.WindowPosition.CENTER;
window.destroy.connect(Gtk.main_quit);
window.set_default_size(0,0);
var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1);
box.set_border_width(1);
var label = new Gtk.Label("Value:");
var entry = new Gtk.Entry();
var ib = new Gtk.Button.with_label("inc");
var db = new Gtk.Button.with_label("dec");
ib.set_sensitive(true); //enable the inc button
db.set_sensitive(false); //disable the dec button
entry.set_text("0"); //initialize to zero
entry.activate.connect(() => {
var str = entry.get_text();
if(!validate_input(window, str)){
entry.set_text("0"); //initialize to zero on wrong input
}else{
int num = int.parse(str);
if(num != 0){
entry.set_sensitive(false); //disable the field
}
if(num > 0 && num < 10){
ib.set_sensitive(true); //enable the inc button
db.set_sensitive(true); //enable the dec button
}
if(num > 9){
ib.set_sensitive(false); //disable the inc button
db.set_sensitive(true); //enable the dec button
}
}
});
ib.clicked.connect(() => {
// read and validate the entered value
if(!validate_input(window, entry.get_text())){
entry.set_text("0"); //initialize to zero on wrong input
}else{
int num = int.parse(entry.get_text()) + 1;
entry.set_text(num.to_string());
if(num > 9){
ib.set_sensitive(false); //disable the inc button
}
if(num != 0){
db.set_sensitive(true); //enable the dec button
entry.set_sensitive(false); //disable the field
}
if(num == 0){
entry.set_sensitive(true); //enable the field
}
if(num < 0){
db.set_sensitive(false); //disable the dec button
}
}
});
db.clicked.connect(() => {
// read and validate the entered value
int num = int.parse(entry.get_text()) - 1;
entry.set_text(num.to_string());
if(num == 0){
db.set_sensitive(false); //disable the dec button
entry.set_sensitive(true); //enable the field
}
if(num < 10){
ib.set_sensitive(true); //enable the inc button
}
});
box.pack_start(label, false, false, 2);
box.pack_start(entry, false, false, 2);
box.pack_start(ib, false, false, 2);
box.pack_start(db, false, false, 2);
window.add(box);
window.show_all();
Gtk.main();
return 0;
}
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Ceylon
|
Ceylon
|
import ceylon.random {
DefaultRandom
}
shared void run() {
value random = DefaultRandom();
value range = 1..10;
while(true) {
value chosen = random.nextElement(range);
print("I have chosen a number between ``range.first`` and ``range.last``.
What is your guess?");
while(true) {
if(exists line = process.readLine()) {
value guess = Integer.parse(line.trimmed);
if(is ParseException guess) {
print(guess.message);
continue;
}
switch(guess <=> chosen)
case (larger) {
print("Too high!");
}
case (smaller) {
print("Too low!");
}
case (equal) {
print("You got it!");
break;
}
} else {
print("Please enter a number!");
}
}
}
}
|
http://rosettacode.org/wiki/Greyscale_bars/Display
|
Greyscale bars/Display
|
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)
For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).
Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
|
#Perl
|
Perl
|
sub partition {
my($all, $div) = @_;
my @marks = 0;
push @marks, $_/$div * $all for 1..$div;
my @copy = @marks;
$marks[$_] -= $copy[$_-1] for 1..$#marks;
@marks[1..$#marks];
}
sub bars {
my($h,$w,$p,$rev) = @_;
my (@nums,@vals,$line,$d);
$d = 2**$p;
push @nums, int $_/($d-1) * (2**16-1) for $rev ? reverse 0..$d-1 : 0..$d-1;
push @vals, ($nums[$_]) x (partition($w, $d))[$_] for 0..$#nums;
$line = join(' ', @vals) . "\n";
$line x $h;
}
my($w,$h) = (1280,768);
open my $pgm, '>', 'Greyscale-bars-perl5.pgm' or die "Can't create Greyscale-bars-perl5.pgm: $!";
print $pgm <<"EOH";
P2
# Greyscale-bars-perl5.pgm
$w $h
65535
EOH
my ($h1,$h2,$h3,$h4) = partition($h,4);
print $pgm
bars($h1,$w,3,0),
bars($h2,$w,4,1),
bars($h3,$w,5,0),
bars($h4,$w,6,1);
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#MATLAB
|
MATLAB
|
function GuessNumberFeedbackPlayer
lowVal = input('Lower limit: ');
highVal = input('Upper limit: ');
fprintf('Think of your number. Press Enter when ready.\n')
pause
nGuesses = 1;
done = false;
while ~done
guess = floor(0.5*(lowVal+highVal));
score = input(sprintf( ...
'Is %d too high (H), too low (L), or equal (E)? ', guess), 's');
if any(strcmpi(score, {'h' 'hi' 'high' 'too high' '+'}))
highVal = guess-1;
nGuesses = nGuesses+1;
elseif any(strcmpi(score, {'l' 'lo' 'low' 'too low' '-'}))
lowVal = guess+1;
nGuesses = nGuesses+1;
elseif any(strcmpi(score, {'e' 'eq' 'equal' 'right' 'correct' '='}))
fprintf('Yay! I win in %d guesses.\n', nGuesses)
done = true;
else
fprintf('Unclear response. Try again.\n')
end
if highVal < lowVal
fprintf('Incorrect scoring. No further guesses.\n')
done = true;
end
end
end
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Draco
|
Draco
|
proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
while n~=0 do
d := n % 10;
n := n / 10;
r := r + d * d
od;
r
corp
proc nonrec happy(byte n) bool:
[256] bool seen;
byte i;
for i from 0 upto 255 do seen[i] := false od;
while not seen[n] do
seen[n] := true;
n := dsumsq(n)
od;
seen[1]
corp
proc nonrec main() void:
byte n, seen;
n := 1;
seen := 0;
while seen < 8 do
if happy(n) then
writeln(n:3);
seen := seen + 1
fi;
n := n + 1
od
corp
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#MySQL
|
MySQL
|
DELIMITER $$
CREATE FUNCTION haversine (
lat1 FLOAT, lon1 FLOAT,
lat2 FLOAT, lon2 FLOAT
) RETURNS FLOAT
NO SQL DETERMINISTIC
BEGIN
DECLARE r FLOAT unsigned DEFAULT 6372.8;
DECLARE dLat FLOAT unsigned;
DECLARE dLon FLOAT unsigned;
DECLARE a FLOAT unsigned;
DECLARE c FLOAT unsigned;
SET dLat = ABS(RADIANS(lat2 - lat1));
SET dLon = ABS(RADIANS(lon2 - lon1));
SET lat1 = RADIANS(lat1);
SET lat2 = RADIANS(lat2);
SET a = POW(SIN(dLat / 2), 2) + COS(lat1) * COS(lat2) * POW(SIN(dLon / 2), 2);
SET c = 2 * ASIN(SQRT(a));
RETURN (r * c);
END$$
DELIMITER ;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#gecho
|
gecho
|
'Hello, <> 'World! print
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Wren
|
Wren
|
var keys = [1, 2, 3, 4, 5]
var values = ["first", "second", "third", "fourth","fifth"]
var hash = {}
(0..4).each { |i| hash[keys[i]] = values[i] }
System.print(hash)
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#zkl
|
zkl
|
keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println();
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#ooRexx
|
ooRexx
|
/* REXX ---------------------------------------------------------------
* 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1
*--------------------------------------------------------------------*/
Parse Arg x y . /* get optional arguments: X Y */
If x='' Then x=20 /* Not specified? Use default */
If y='' Then y=1000 /* " " " " */
n=0 /* Niven count */
nl='' /* Niven list. */
Do j=1 Until n=x /* let's go Niven number hunting.*/
If j//sumdigs(j)=0 Then Do /* j is a Niven number */
n=n+1 /* bump Niven count */
nl=nl j /* add to list. */
End
End
Say 'first' n 'Niven numbers:'nl
Do j=y+1 /* start with first candidate */
If j//sumdigs(j)=0 Then /* j is a Niven number */
Leave
End
Say 'first Niven number >' y 'is:' j
Exit
sumdigs: Procedure /* compute sum of n's digits */
Parse Arg n
sum=left(n,1)
Do k=2 To length(n)
sum=sum+substr(n,k,1)
End
Return sum
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#IWBASIC
|
IWBASIC
|
DEF Win:WINDOW
DEF Close:CHAR
DEF ScreenSizeX,ScreenSizeY:UINT
GETSCREENSIZE(ScreenSizeX,ScreenSizeY)
OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,NULL,NULL,"Goodbye program",&MainHandler
PRINT Win,"Goodbye, World!"
'Prints in upper left corner of the window (position 0,0).
WAITUNTIL Close=1
CLOSEWINDOW Win
END
SUB MainHandler
IF @MESSAGE=@IDCLOSEWINDOW THEN Close=1
RETURN
ENDSUB
|
http://rosettacode.org/wiki/GUI_component_interaction
|
GUI component interaction
|
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dialogs to query the user for further information
Task
For a minimal "application", write a program that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("random")
The field is initialized to zero.
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
Entering a non-numeric value should be either impossible,
or issue an error message.
Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".
(This task may be regarded as an extension of the task Simple windowed application).
|
#Prolog
|
Prolog
|
dialog('GUI_Interaction',
[ object :=
GUI_Interaction,
parts :=
[ GUI_Interaction :=
dialog('Rosetta Code'),
Input_field :=
text_item(input_field),
Increment :=
button(increment),
Random :=
button(random)
],
modifications :=
[ Input_field := [ label := 'Value :',
length := 28
]
],
layout :=
[ area(Input_field,
area(54, 24, 251, 24)),
area(Increment,
area(54, 90, 80, 24)),
area(Random,
area(230, 90, 80, 24))
],
behaviour :=
[
Increment := [
message := message(@prolog,
increment,
Input_field )
],
Random := [
message := message(@prolog,
my_random,
Input_field)
],
Input_field := [
message := message(@prolog,
input,
GUI_Interaction,
Increment,
@receiver,
@arg1)
]
]
]).
gui_component :-
make_dialog(S, 'GUI_Interaction'),
send(S, open).
increment(Input) :-
get(Input, selection, V),
atom_number(V, Val),
Val1 is Val + 1,
send(Input, selection, Val1).
my_random(Input) :-
new(D, dialog('GUI Interaction')),
send(D, append(label(lbl,'Confirm your choice !'))),
send(D, append(button(ok, message(D, return, ok)))),
send(D, append(button(cancel, message(D, return, ko)))),
send(D, default_button(ok)),
get(D, confirm, Rval),
free(D),
( Rval = ok
-> X is random(10000),
send(Input, selection, X)
).
input(Gui, Btn, Input, Selection) :-
catch( (term_to_atom(T, Selection), number(T), send(Gui, focus, Btn)),
_,
( send(@display, inform, 'Please type a number !'),
send(Input,clear))).
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Aime
|
Aime
|
integer
gray_encode(integer n)
{
n ^ (n >> 1);
}
integer
gray_decode(integer n)
{
integer p;
p = n;
while (n >>= 1) {
p ^= n;
}
p;
}
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#ActionScript
|
ActionScript
|
function max(... args):Number
{
var curMax:Number = -Infinity;
for(var i:uint = 0; i < args.length; i++)
curMax = Math.max(curMax, args[i]);
return curMax;
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#ABAP
|
ABAP
|
CLASS lcl_hailstone DEFINITION.
PUBLIC SECTION.
TYPES: tty_sequence TYPE STANDARD TABLE OF i
WITH NON-UNIQUE EMPTY KEY,
BEGIN OF ty_seq_len,
start TYPE i,
len TYPE i,
END OF ty_seq_len,
tty_seq_len TYPE HASHED TABLE OF ty_seq_len
WITH UNIQUE KEY start.
CLASS-METHODS:
get_next
IMPORTING
n TYPE i
RETURNING
VALUE(r_next_hailstone_num) TYPE i,
get_sequence
IMPORTING
start TYPE i
RETURNING
VALUE(r_sequence) TYPE tty_sequence,
get_longest_sequence_upto
IMPORTING
limit TYPE i
RETURNING
VALUE(r_longest_sequence) TYPE ty_seq_len.
PRIVATE SECTION.
TYPES: BEGIN OF ty_seq,
start TYPE i,
seq TYPE tty_sequence,
END OF ty_seq.
CLASS-DATA: sequence_buffer TYPE HASHED TABLE OF ty_seq
WITH UNIQUE KEY start.
ENDCLASS.
CLASS lcl_hailstone IMPLEMENTATION.
METHOD get_next.
r_next_hailstone_num = COND #( WHEN n MOD 2 = 0 THEN n / 2
ELSE ( 3 * n ) + 1 ).
ENDMETHOD.
METHOD get_sequence.
INSERT start INTO TABLE r_sequence.
IF start = 1.
RETURN.
ENDIF.
READ TABLE sequence_buffer ASSIGNING FIELD-SYMBOL(<buff>)
WITH TABLE KEY start = start.
IF sy-subrc = 0.
INSERT LINES OF <buff>-seq INTO TABLE r_sequence.
ELSE.
DATA(seq) = get_sequence( get_next( start ) ).
INSERT LINES OF seq INTO TABLE r_sequence.
INSERT VALUE ty_seq( start = start
seq = seq ) INTO TABLE sequence_buffer.
ENDIF.
ENDMETHOD.
METHOD get_longest_sequence_upto.
DATA: max_seq TYPE ty_seq_len,
act_seq TYPE ty_seq_len.
DO limit TIMES.
act_seq-len = lines( get_sequence( sy-index ) ).
IF act_seq-len > max_seq-len.
max_seq-len = act_seq-len.
max_seq-start = sy-index.
ENDIF.
ENDDO.
r_longest_sequence = max_seq.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
cl_demo_output=>begin_section( |Hailstone sequence of 27 is: | ).
cl_demo_output=>write( REDUCE string( INIT result = ``
FOR item IN lcl_hailstone=>get_sequence( 27 )
NEXT result = |{ result } { item }| ) ).
cl_demo_output=>write( |With length: { lines( lcl_hailstone=>get_sequence( 27 ) ) }| ).
cl_demo_output=>begin_section( |Longest hailstone sequence upto 100k| ).
cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
cl_demo_output=>display( ).
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Phix
|
Phix
|
-- demo\rosetta\Graph_colouring.exw
with javascript_semantics
constant tests = split("""
0-1 1-2 2-0 3
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
""","\n",true)
function colour(sequence nodes, links, colours, soln, integer best, next, used=0)
-- fill/try each colours[next], recursing as rqd and saving any improvements.
-- nodes/links are read-only here, colours is the main workspace, soln/best are
-- the results, next is 1..length(nodes), and used is length(unique(colours)).
-- On really big graphs I might consider making nodes..best static, esp colours,
-- in which case you will probably also want a "colours[next] = 0" reset below.
integer c = 1
colours = deep_copy(colours)
while c<best do
bool avail = true
for i=1 to length(links[next]) do
if colours[links[next][i]]==c then
avail = false
exit
end if
end for
if avail then
colours[next] = c
integer newused = used + (find(c,colours)==next)
if next<length(nodes) then
{best,soln} = colour(nodes,links,colours,soln,best,next+1,newused)
elsif newused<best then
{best,soln} = {newused,deep_copy(colours)}
end if
end if
c += 1
end while
return {best,soln}
end function
function add_node(sequence nodes, links, string n)
integer rdx = find(n,nodes)
if rdx=0 then
nodes = append(nodes,n)
links = append(links,{})
rdx = length(nodes)
end if
return {nodes, links, rdx}
end function
for t=1 to length(tests) do
string tt = tests[t]
sequence lt = split(tt," "),
nodes = {},
links = {}
integer linkcount = 0, left, right
for l=1 to length(lt) do
sequence ll = split(lt[l],"-")
{nodes, links, left} = add_node(deep_copy(nodes),deep_copy(links),ll[1])
if length(ll)=2 then
{nodes, links, right} = add_node(deep_copy(nodes),deep_copy(links),ll[2])
links[left] = deep_copy(links[left])&right
links[right] = deep_copy(links[right])&left
linkcount += 1
end if
end for
integer ln = length(nodes)
printf(1,"test%d: %d nodes, %d edges, ",{t,ln,linkcount})
sequence colours = repeat(0,ln),
soln = tagset(ln) -- fallback solution
integer next = 1, best = ln
printf(1,"%d colours:%v\n",colour(nodes,links,colours,soln,best,next))
end for
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Phix
|
Phix
|
--
-- demo\rosetta\Goldbachs_comet.exw
-- ================================
--
-- Note: this plots n/2 vs G(n) for n=6 to 4000 by 2, matching wp and
-- Algol 68, Python, and Raku. However, while not wrong, Arturo
-- and Wren apparently plot n vs G(n) for n=6 to 2000 by 2, so
-- should you spot any (very) minor differences, that'd be why.
--
with javascript_semantics
requires("1.0.2")
constant limit = 4000
sequence primes = get_primes_le(limit)[2..$],
goldbach = reinstate(repeat(0,limit),{4},{1})
for i=1 to length(primes) do
for j=i to length(primes) do
integer s = primes[i] + primes[j]
if s>limit then exit end if
goldbach[s] += 1
end for
end for
sequence fhg = extract(goldbach,tagstart(4,100,2))
string fhgs = join_by(fhg,1,10," ","\n","%2d")
integer gm = sum(apply(sq_sub(1e6,get_primes_le(499999)[2..$]),is_prime))
printf(1,"The first 100 G values:\n%s\n\nG(1,000,000) = %,d\n",{fhgs,gm})
include pGUI.e
include IupGraph.e
function get_data(Ihandle /*graph*/)
return {{tagset(limit/2,3,3),extract(goldbach,tagset(limit,6,6)),CD_RED},
{tagset(limit/2,4,3),extract(goldbach,tagset(limit,8,6)),CD_BLUE},
{tagset(limit/2,5,3),extract(goldbach,tagset(limit,10,6)),CD_DARK_GREEN}}
end function
IupOpen()
Ihandle graph = IupGraph(get_data,"RASTERSIZE=640x440,MARKSTYLE=PLUS")
IupSetAttributes(graph,"XTICK=%d,XMIN=0,XMAX=%d",{limit/20,limit/2})
IupSetAttributes(graph,"YTICK=20,YMIN=0,YMAX=%d",{max(goldbach)+20})
Ihandle dlg = IupDialog(graph,`TITLE="Goldbach's comet",MINSIZE=400x300`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Grayscale_image
|
Grayscale image
|
Many image processing algorithms are defined for grayscale (or else monochromatic) images.
Task
Extend the data storage type defined on this page to support grayscale images.
Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.
To get luminance of a color use the formula recommended by CIE:
L = 0.2126 × R + 0.7152 × G + 0.0722 × B
When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
|
#Erlang
|
Erlang
|
-module(ros_bitmap).
-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]).
-record(bitmap, {
mode = rgb,
pixels = nil,
shape = {0, 0}
}).
tuple_to_bytes({rgb, R, G, B}) ->
<<R:8, G:8, B:8>>;
tuple_to_bytes({gray, L}) ->
<<L:8>>.
bytes_to_tuple(rgb, Bytes) ->
<<R:8, G:8, B:8>> = Bytes,
{rgb, R, G, B};
bytes_to_tuple(gray, Bytes) ->
<<L:8>> = Bytes,
{gray, L}.
new(Width, Height) ->
new(Width, Height, {rgb, 0, 0, 0}).
new(Width, Height, rgb) ->
new(Width, Height, {rgb, 0, 0, 0});
new(Width, Height, gray) ->
new(Width, Height, {gray, 0, 0, 0});
new(Width, Height, ColorTuple) when is_tuple(ColorTuple) ->
[Mode|Components] = tuple_to_list(ColorTuple),
Bytes = list_to_binary(Components),
#bitmap{
pixels=array:new(Width * Height, {default, Bytes}),
shape={Width, Height},
mode=Mode}.
fill(#bitmap{shape={Width, Height}, mode=Mode}, ColorTuple)
when element(1, ColorTuple) =:= Mode ->
new(Width, Height, ColorTuple).
set_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode}=Bitmap,
{at, X, Y}, ColorTuple) when element(1, ColorTuple) =:= Mode ->
Index = X + Y * Width,
Bitmap#bitmap{pixels=array:set(Index, tuple_to_bytes(ColorTuple), Pixels)}.
get_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode},
{at, X, Y}) ->
Index = X + Y * Width,
Bytes = array:get(Index, Pixels),
bytes_to_tuple(Mode, Bytes).
luminance(<<R:8, G:8, B:8>>) ->
<<(trunc(R * 0.2126 + G * 0.7152 + B * 0.0722))>>.
%% convert from rgb to grayscale
convert(#bitmap{pixels=Pixels, mode=rgb}=Bitmap, gray) ->
Bitmap#bitmap{
pixels=array:map(fun(_I, Pixel) ->
luminance(Pixel) end, Pixels),
mode=gray};
%% convert from grayscale to rgb
convert(#bitmap{pixels=Pixels, mode=gray}=Bitmap, rgb)->
Bitmap#bitmap{
pixels=array:map(fun(_I, <<L:8>>) -> <<L:8, L:8, L:8>> end, Pixels),
mode=rgb};
%% no conversion if the mode is the same with the bitmap.
convert(#bitmap{mode=Mode}=Bitmap, Mode) ->
Bitmap.
|
http://rosettacode.org/wiki/Go_Fish
|
Go Fish
|
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:
Each player is dealt nine cards to start with.
On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
The game ends when every book is complete. The player with the most books wins.
The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.
You may want to use code from Playing Cards.
Related tasks:
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
|
#FreeBASIC
|
FreeBASIC
|
' Go Fish ~ ¡Pesca!
Const cartas = "A234567890JQK"
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13)
Dim Shared As String nombre, Snombre, CartaPedida
Dim Shared puntos(2) As Byte = {0,0}
Dim Shared As Integer remca = 4*Len(cartas)
Dim Shared As Integer i, k, j, cn
For i = 1 To 13
deck(i) = 4
Next i
For i = 1 To 9
Reparto_Cartas
deck(k) -= 1
compu(k) += 1
Reparto_Cartas
deck(k) -= 1
play(k) += 1
Next i
Dim As Integer v, po
Sub Reparto_Cartas
remca -= 1
Dim As Integer sc = remca * Rnd + 1
For k = 1 To 13
sc -= deck(k)
If sc <= 0 Then Return
Next k
End Sub
Sub Pescar_Carta_Jug
Reparto_Cartas
Print " " &Mid(cartas,k,1) &"."
deck(k) -= 1
play(k) += 1
End Sub
Sub Pescar_Carta_CPU
Reparto_Cartas
Print "a carta."
deck(k) -= 1
compu(k) += 1
End Sub
Sub Comprobar_Libro_Jug
For i = 1 To 13
If play(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
play(i) = 0
puntos(0) += 1
End If
Next i
End Sub
Sub Comprobar_Libro_CPU
For i = 1 To 13
If compu(i) <> 4 Then
Else
Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7
compu(i) = 0
puntos(1) += 1
End If
Next i
End Sub
Sub Comprobar_Fin_Partida
Dim As Integer np = 0, nc = 0
For i = 1 To 13
np += play(i)
nc += compu(i)
Next i
If remca = 0 Or np = 0 Or nc = 0 Then
Color 15: Print
Print "*** FIN de la partida! ***"
Print
If puntos(0) < puntos(1) Then
Print "La CPU ha ganado."
Elseif puntos(0) > puntos(1) Then
Print nombre &" ha ganado."
Else
Print "Es un empate!"
End If
Sleep: End
End If
End Sub
Sub Intro
Color 15
Print " __ _ _ "
Print " __ _ ___ / _(_)___| |__ "
Print " / ` |/ _ \ | |_| / __| '_ \ "
Print "| (_) | (_) | | _| \__ \ | | | "
Print " \__, |\___/ |_| |_|___/_| |_| "
Print " |___/ "
Print " "
Color 14: Locate 10, 2: Input "Como te llamas: ", nombre
End Sub
'--- Programa Principal ---
Cls
Randomize Timer
Intro
Do
Dim As boolean MuestraMano = false
While MuestraMano = false
Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1)
Color 13: Print Chr(10) &space(10) &remca &" cartas restantes"
Color 14: Print Chr(10) &"Tu mano: ";
For i = 1 To 13
If Not play(i) Then
For j = 1 To play(i)
Print Mid(cartas,i,1); " ";
Next j
End If
Next i
Print
Dim As boolean PideCarta = false
While PideCarta = false
Comprobar_Fin_Partida
Snombre = nombre
Color 7: Print
Input "¨Que carta pides... "; CartaPedida
Print
If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true
If cn = 0 Then
Print "Lo siento, no es una opción valida.": PideCarta = false
Elseif play(cn) = 0 Then Color 12: Print "No tienes esa carta!": Color 7: PideCarta = false
End If
Wend
guess(cn) = 1
If compu(cn) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug
Comprobar_Libro_Jug
MuestraMano = true
Else
v = compu(cn)
compu(cn) = 0
play(cn) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_Jug
MuestraMano = false
End If
Wend
Snombre = "CPU"
For i = 1 To 13
asked(i) = 0
Next i
Dim As boolean Turno_CPU_2 = false
While Turno_CPU_2 = false
Comprobar_Fin_Partida
po = 0
For i = 1 To 13
If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1
Next i
If po = 0 Then
Do
k = (Rnd*12)+1
Loop While compu(k) = 0 Or asked(k)
Else
Do
k = (Rnd*12)+1
Loop While poss(k) = 0
guess(k) = 0
asked(k) = 1
End If
Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s."
asked(k) = 1
If play(k) = 0 Then
Print Snombre &", ";
Color 15: Print "ve a pescar!"
Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU
Comprobar_Libro_CPU
Turno_CPU_2 = true
Else
v = play(k)
play(k) = 0
compu(k) += v
Print Snombre &" consigue " &v &" carta(s) mas."
Comprobar_Libro_CPU
Turno_CPU_2 = false
End If
Wend
Loop
End
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <vector>
// Hamming like sequences Generator
//
// Nigel Galloway. August 13th., 2012
//
class Ham {
private:
std::vector<unsigned int> _H, _hp, _hv, _x;
public:
bool operator!=(const Ham& other) const {return true;}
Ham begin() const {return *this;}
Ham end() const {return *this;}
unsigned int operator*() const {return _x.back();}
Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){}
const Ham& operator++() {
for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]);
_x.push_back(_hv[0]);
for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i];
return *this;
}
};
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Delphi
|
Delphi
|
program GuessTheNumber;
{$APPTYPE CONSOLE}
uses SysUtils;
var
theDigit : String ;
theAnswer : String ;
begin
Randomize ;
theDigit := IntToStr(Random(9)+1) ;
while ( theAnswer <> theDigit ) do Begin
Writeln('Please enter a digit between 1 and 10' ) ;
Readln(theAnswer);
End ;
Writeln('Congratulations' ) ;
end.
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
local :number random-range 1 11
while true:
if = number to-num !prompt "Guess my number: ":
!print "Congratulations, you've guessed it!"
return
else:
!print "Nope, try again."
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Component_Pascal
|
Component Pascal
|
MODULE OvctGreatestSubsequentialSum;
IMPORT StdLog, Strings, Args;
PROCEDURE Gss(iseq: ARRAY OF INTEGER;OUT start, end, maxsum: INTEGER);
VAR
i,j,sum: INTEGER;
BEGIN
i := 0; maxsum := 0; start := 0; end := -1;
WHILE i < LEN(iseq) - 1 DO
sum := 0; j := i;
WHILE j < LEN(iseq) -1 DO
INC(sum ,iseq[j]);
IF sum > maxsum THEN
maxsum := sum;
start := i;
end := j
END;
INC(j);
END;
INC(i)
END
END Gss;
PROCEDURE Do*;
VAR
p: Args.Params;
iseq: POINTER TO ARRAY OF INTEGER;
i, res, start, end, sum: INTEGER;
BEGIN
Args.Get(p); (* Get Params *)
NEW(iseq,p.argc);
(* Transform params to INTEGERs *)
FOR i := 0 TO p.argc - 1 DO
Strings.StringToInt(p.args[i],iseq[i],res)
END;
Gss(iseq,start,end,sum);
StdLog.String("[");
FOR i := start TO end DO
StdLog.Int(iseq[i]);
IF i < end THEN StdLog.String(",") END
END;
StdLog.String("]=");StdLog.Int(sum);StdLog.Ln;
END Do;
END OvctGreatestSubsequentialSum.
|
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
|
GUI enabling/disabling of controls
|
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.
Task
Similar to the task GUI component interaction, write a program
that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("decrement")
The field is initialized to zero.
The user may manually enter a new value into the field,
increment its value with the "increment" button,
or decrement the value with the "decrement" button.
The input field should be enabled only when its value is zero.
The "increment" button only as long as the field's value is less then 10:
When the value 10 is reached, the button should go into a disabled state.
Analogously, the "decrement" button should be enabled only as long as
the value is greater than zero.
Effectively, the user can now either increment up to 10, or down to zero.
Manually entering values outside that range is still legal,
but the buttons should reflect that and enable/disable accordingly.
|
#Visual_Basic
|
Visual Basic
|
VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton cmdDec
Caption = "Decrement"
Enabled = 0 'False
Height = 495
Left = 120
TabIndex = 2
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdInc
Caption = "Increment"
Height = 495
Left = 120
TabIndex = 1
Top = 1080
Width = 1215
End
Begin VB.TextBox txtValue
Height = 495
Left = 120
TabIndex = 0
Text = "0"
Top = 240
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'-----user-written code begins here; everything above this line is hidden in the GUI-----
Private Sub cmdDec_Click()
If Val(txtValue.Text) > 0 Then txtValue.Text = Val(txtValue.Text) - 1
End Sub
Private Sub cmdInc_Click()
If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub
Private Sub txtValue_Change()
Select Case Val(txtValue.Text)
Case Is < 0
txtValue.Enabled = False
cmdInc.Enabled = True
cmdDec.Enabled = False
Case Is > 9
txtValue.Enabled = False
cmdInc.Enabled = False
cmdDec.Enabled = True
Case 0
txtValue.Enabled = True
cmdInc.Enabled = True
cmdDec.Enabled = False
Case Else
txtValue.Enabled = False
cmdInc.Enabled = True
cmdDec.Enabled = True
End Select
End Sub
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Clojure
|
Clojure
|
(defn guess-run []
(let [start 1
end 100
target (+ start (rand-int (inc (- end start))))]
(printf "Guess a number between %d and %d" start end)
(loop [i 1]
(printf "Your guess %d:\n" i)
(let [ans (read)]
(if (cond
(not (number? ans)) (println "Invalid format")
(or (< ans start) (> ans end)) (println "Out of range")
(< ans target) (println "too low")
(> ans target) (println "too high")
:else true)
(println "Correct")
(recur (inc i)))))))
|
http://rosettacode.org/wiki/Greyscale_bars/Display
|
Greyscale bars/Display
|
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.
For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)
For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).
Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
|
#Phix
|
Phix
|
--
-- demo\rosetta\Greyscale_bars.exw
-- ===============================
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
integer quit = 1
bool refire = false
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
cdCanvasActivate(cddbuffer)
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
integer h = floor(height/4)
height -= 1
for row=1 to 4 do
integer x = 0, p2 = power(2,row+2), c = floor(255/(p2-1))
for n=0 to p2-1 do
integer colour = c*n*#010101
if and_bits(row,1)=0 then colour = xor_bits(colour,#FFFFFF) end if
cdCanvasSetForeground(cddbuffer, colour)
integer nx = ceil(width*(n+1)/p2)
cdCanvasBox(cddbuffer, x, nx-1, (4-row)*h, height)
x = nx
end for
height = (4-row)*h-1
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
return IUP_DEFAULT
end function
function unmap_cb(Ihandle /*ih*/)
cdKillCanvas(cddbuffer)
cdKillCanvas(cdcanvas)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=600x400")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"UNMAP_CB", Icallback("unmap_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas, `TITLE="Greyscale bars"`)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#MAXScript
|
MAXScript
|
inclusiveRange = [1,100]
lowRange = inclusiveRange.x
maxRange = inclusiveRange.y
guesses = 1
inf = "Think of a number between % and % and I will try to guess it.\n" +\
"Type -1 if the guess is less than your number,\n"+\
"0 if the guess is correct, " +\
"or 1 if it's too high.\nPress esc to exit.\n"
clearListener()
format inf (int lowRange) (int maxRange)
while not keyboard.escpressed do
(
local chosen = ((lowRange + maxRange) / 2) as integer
if lowRange == maxRange do format "\nHaving fun?"
format "\nI choose %.\n" chosen
local theAnswer = getKBValue prompt:"Answer? "
case theAnswer of
(
(-1): (lowRange = chosen; guesses += 1)
(0): (format "\nYay. I guessed your number after % %.\n" \
guesses (if guesses == 1 then "try" else "tries")
exit with OK)
(1): (maxRange = chosen; guesses += 1)
default: (format "\nI don't understand your input.")
)
)
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
|
Guess the number/With feedback (player)
|
Task
Write a player for the game that follows the following rules:
The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.
Related tasks
Guess the number/With Feedback
Bulls and cows/Player
|
#Modula-2
|
Modula-2
|
MODULE raden;
IMPORT InOut;
VAR done, ok : BOOLEAN;
guess, upp, low : CARDINAL;
res : CHAR;
BEGIN
InOut.WriteString ("Choose a number between 0 and 1000.");
InOut.WriteLn;
InOut.WriteLn;
upp := 1000;
low := 0;
REPEAT
ok := FALSE;
guess := ( ( upp - low ) DIV 2 ) + low;
InOut.WriteString ("My guess is"); InOut.WriteCard (guess, 4); InOut.Write (11C);
InOut.WriteString ("How did I score? 'L' = too low, 'H' = too high, 'Q' = OK : ");
InOut.WriteBf;
REPEAT
InOut.Read (res);
res := CAP (res)
UNTIL (res = 'Q') OR (res = 'L') OR (res = 'H');
CASE res OF
'L' : low := guess |
'H' : upp := guess
ELSE
ok := TRUE
END;
UNTIL ok;
InOut.WriteString ("So the number is"); InOut.WriteCard (guess, 4);
InOut.WriteLn;
InOut.WriteString ("Thanks for letting me play with you.");
InOut.WriteLn
END raden.
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#DWScript
|
DWScript
|
function IsHappy(n : Integer) : Boolean;
var
cache : array of Integer;
sum : Integer;
begin
while True do begin
sum := 0;
while n>0 do begin
sum += Sqr(n mod 10);
n := n div 10;
end;
if sum = 1 then
Exit(True);
if sum in cache then
Exit(False);
n := sum;
cache.Add(sum);
end;
end;
var n := 8;
var i : Integer;
while n>0 do begin
Inc(i);
if IsHappy(i) then begin
PrintLn(i);
Dec(n);
end;
end;
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Nim
|
Nim
|
import math
proc radians(x): float = x * Pi / 180
proc haversine(lat1, lon1, lat2, lon2): float =
const r = 6372.8 # Earth radius in kilometers
let
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat/2)*sin(dLat/2) + cos(lat1)*cos(lat2)*sin(dLon/2)*sin(dLon/2)
c = 2*arcsin(sqrt(a))
result = r * c
echo haversine(36.12, -86.67, 33.94, -118.40)
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Oberon-2
|
Oberon-2
|
MODULE Haversines;
IMPORT
LRealMath,
Out;
PROCEDURE Distance(lat1,lon1,lat2,lon2: LONGREAL): LONGREAL;
CONST
r = 6372.8D0; (* Earth radius as LONGREAL *)
to_radians = LRealMath.pi / 180.0D0;
VAR
d,ph1,th1,th2: LONGREAL;
dz,dx,dy: LONGREAL;
BEGIN
d := lon1 - lon2;
ph1 := d * to_radians;
th1 := lat1 * to_radians;
th2 := lat2 * to_radians;
dz := LRealMath.sin(th1) - LRealMath.sin(th2);
dx := LRealMath.cos(ph1) * LRealMath.cos(th1) - LRealMath.cos(th2);
dy := LRealMath.sin(ph1) * LRealMath.cos(th1);
RETURN LRealMath.arcsin(LRealMath.sqrt(LRealMath.power(dx,2.0) + LRealMath.power(dy,2.0) + LRealMath.power(dz,2.0)) / 2.0) * 2.0 * r;
END Distance;
BEGIN
Out.LongRealFix(Distance(36.12,-86.67,33.94,-118.4),6,10);Out.Ln
END Haversines.
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Gema
|
Gema
|
*= ! ignore off content of input
\B=Hello world!\! ! Start output with this text.
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#PARI.2FGP
|
PARI/GP
|
isHarshad(n)=n%sumdigits(n)==0
n=0;k=20;while(k,if(isHarshad(n++),k--;print1(n", ")));
n=1000;while(!isHarshad(n++),);print("\n"n)
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#J
|
J
|
wdinfo 'Goodbye, World!'
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Java
|
Java
|
import javax.swing.*;
import java.awt.*;
public class OutputSwing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog (null, "Goodbye, World!"); // in alert box
JFrame frame = new JFrame("Goodbye, World!"); // on title bar
JTextArea text = new JTextArea("Goodbye, World!"); // in editable area
JButton button = new JButton("Goodbye, World!"); // on button
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(text);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
|
http://rosettacode.org/wiki/GUI_component_interaction
|
GUI component interaction
|
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.
Typically, the following is needed:
put values into input fields under program control
read and check input from the user
pop up dialogs to query the user for further information
Task
For a minimal "application", write a program that presents a form with three components to the user:
a numeric input field ("Value")
a button ("increment")
a button ("random")
The field is initialized to zero.
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
Entering a non-numeric value should be either impossible,
or issue an error message.
Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".
(This task may be regarded as an extension of the task Simple windowed application).
|
#PureBasic
|
PureBasic
|
Enumeration
#StringGadget
#Increment
#Random
EndEnumeration
If OpenWindow(0,#PB_Ignore,#PB_Ignore,180,50,"PB-GUI",#PB_Window_SystemMenu)
StringGadget(#StringGadget,5,5,170,20,"",#PB_String_Numeric)
ButtonGadget(#Increment,5,25,80,20, "Increment")
ButtonGadget(#Random, 90,25,80,20, "Random")
Repeat
Event=WaitWindowEvent()
If Event=#PB_Event_Gadget
Select EventGadget()
Case #Increment
CurrentVal=Val(GetGadgetText(#StringGadget))
SetGadgetText(#StringGadget,Str(CurrentVal+1))
Case #Random
Flag=#PB_MessageRequester_YesNo
Answer=MessageRequester("Randomize","Are you sure?",Flag)
If Answer=#PB_MessageRequester_Yes
SetGadgetText(#StringGadget,Str(Random(#MAXLONG)))
EndIf
EndSelect
EndIf
Until Event=#PB_Event_CloseWindow
CloseWindow(0)
EndIf
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
OP GRAY = (BITS b) BITS : b XOR (b SHR 1); CO Convert to Gray code CO
OP YARG = (BITS g) BITS : CO Convert from Gray code CO
BEGIN
BITS b := g, mask := g SHR 1;
WHILE mask /= 2r0 DO b := b XOR mask; mask := mask SHR 1 OD;
b
END;
FOR i FROM 0 TO 31 DO
printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i))
OD
END
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Amazing_Hopper
|
Amazing Hopper
|
#proto GrayEncode(_X_)
#synon _GrayEncode *getGrayEncode
#proto GrayDecode(_X_)
#synon _GrayDecode *getGrayDecode
#include <hbasic.h>
Begin
Gray=0
SizeBin(4) // size 5 bits: 0->4
Take (" # BINARY GRAY DECODE\n")
Take ("------------------------------\n"), and Print It
For Up( i := 0, 31, 1)
Print( LPad$(" ",2,Str$(i))," => ", Bin$(i)," => ")
get Gray Encode(i) and Copy to (Gray), get Binary; then Take(" => ")
now get Gray Decode( Gray ), get Binary, and Print It with a Newl
Next
End
Subrutines
Gray Encode(n)
Return (XorBit( RShift(1,n), n ))
Gray Decode(n)
p = n
While ( n )
n >>= 1
p != n
Wend
Return (p)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Ada
|
Ada
|
with Ada.Text_Io;
procedure Max_Test isco
-- substitute any array type with a scalar element
type Flt_Array is array (Natural range <>) of Float;
-- Create an exception for the case of an empty array
Empty_Array : Exception;
function Max(Item : Flt_Array) return Float is
Max_Element : Float := Float'First;
begin
if Item'Length = 0 then
raise Empty_Array;
end if;
for I in Item'range loop
if Item(I) > Max_Element then
Max_Element := Item(I);
end if;
end loop;
return Max_Element;
end Max;
Buf : Flt_Array := (-275.0, -111.19, 0.0, -1234568.0, 3.14159, -3.14159);
begin
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
end Max_Test;
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#11l
|
11l
|
F gcd(=u, =v)
L v != 0
(u, v) = (v, u % v)
R abs(u)
print(gcd(0, 0))
print(gcd(0, 10))
print(gcd(0, -10))
print(gcd(9, 6))
print(gcd(6, 9))
print(gcd(-6, 9))
print(gcd(8, 45))
print(gcd(40902, 24140))
|
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
|
Globally replace text in several files
|
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
|
#11l
|
11l
|
L(fname) fs:list_dir(‘.’)
I fname.ends_with(‘.txt’)
V fcontents = File(fname).read()
File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#ACL2
|
ACL2
|
(defun hailstone (len)
(loop for x = len
then (if (evenp x)
(/ x 2)
(+ 1 (* 3 x)))
collect x until (= x 1)))
;; Must be tail recursive
(defun max-hailstone-start (limit mx curr)
(declare (xargs :mode :program))
(if (zp limit)
(mv mx curr)
(let ((new-mx (len (hailstone limit))))
(if (> new-mx mx)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) mx curr)))))
|
http://rosettacode.org/wiki/Graph_colouring
|
Graph colouring
|
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.
In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes need a separate
description.
For example,
0-1 1-2 2-0 3
Describes the following graph. Note that node 3 has no neighbours
Example graph
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.
In the above example:
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
Graph colouring task
Colour the vertices of a given graph so that no edge is between verticies of
the same colour.
Integers may be used to denote different colours.
Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement).
Show for each edge, the colours assigned on each vertex.
Show the total number of nodes, edges, and colours used for each graph.
Use the following graphs
Ex1
0-1 1-2 2-0 3
+---+
| 3 |
+---+
+-------------------+
| |
+---+ +---+ +---+
| 0 | --- | 1 | --- | 2 |
+---+ +---+ +---+
Ex2
The wp articles left-side graph
1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7
+----------------------------------+
| |
| +---+ |
| +-----------------| 3 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 6 | --- | 4 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 7 | --- | 2 | --- | 5 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex3
The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.
1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6
+----------------------------------+
| |
| +---+ |
| +-----------------| 5 | ------+----+
| | +---+ | |
| | | | |
| | | | |
| | | | |
| +---+ +---+ +---+ +---+ |
| | 8 | --- | 1 | --- | 4 | --- | 7 | |
| +---+ +---+ +---+ +---+ |
| | | | |
| | | | |
| | | | |
| | +---+ +---+ +---+ |
+----+------ | 6 | --- | 3 | --- | 2 | -+
| +---+ +---+ +---+
| |
+-------------------+
Ex4
This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.
1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7
+-------------------------------------------------+
| |
| |
+-------------------+---------+ |
| | | |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
| | | | | |
+---------+-----------------------------+---------+ | |
| | | |
| | | |
+-----------------------------+-------------------+ |
| |
| |
+-----------------------------+
References
Greedy coloring Wikipedia.
Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
|
#Python
|
Python
|
import re
from collections import defaultdict
from itertools import count
connection_re = r"""
(?: (?P<N1>\d+) - (?P<N2>\d+) | (?P<N>\d+) (?!\s*-))
"""
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
g = self.graph = defaultdict(list) # maps vertex to direct connections
matches = re.finditer(connection_re, connections,
re.MULTILINE | re.VERBOSE)
for match in matches:
n1, n2, n = match.groups()
if n:
g[n] += []
else:
g[n1].append(n2) # Each the neighbour of the other
g[n2].append(n1)
def greedy_colour(self, order=None):
"Greedy colourisation algo."
if order is None:
order = self.graph # Choose something
colour = self.colour = {}
neighbours = self.graph
for node in order:
used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]
if nbr in colour)
colour[node] = first_avail_int(used_neighbour_colours)
self.pp_colours()
return colour
def pp_colours(self):
print(f"\n{self.name}")
c = self.colour
e = canonical_edges = set()
for n1, neighbours in sorted(self.graph.items()):
if neighbours:
for n2 in neighbours:
edge = tuple(sorted([n1, n2]))
if edge not in canonical_edges:
print(f" {n1}-{n2}: Colour: {c[n1]}, {c[n2]}")
canonical_edges.add(edge)
else:
print(f" {n1}: Colour: {c[n1]}")
lc = len(set(c.values()))
print(f" #Nodes: {len(c)}\n #Edges: {len(e)}\n #Colours: {lc}")
def first_avail_int(data):
"return lowest int 0... not in data"
d = set(data)
for i in count():
if i not in d:
return i
if __name__ == '__main__':
for name, connections in [
('Ex1', "0-1 1-2 2-0 3"),
('Ex2', "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"),
('Ex3', "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"),
('Ex4', "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"),
]:
g = Graph(name, connections)
g.greedy_colour()
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Picat
|
Picat
|
main =>
println("First 100 G numbers:"),
foreach({G,I} in zip(take([G: T in 1..300, G=g(T),G>0],100),1..100))
printf("%2d %s",G,cond(I mod 10 == 0,"\n",""))
end,
nl,
printf("G(1_000_000): %d\n", g(1_000_000)).
g(N) = cond((N > 2, N mod 2 == 0),
{1 : I in 1..N // 2,
prime(I),prime(N-I)}.len,
0).
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Python
|
Python
|
from matplotlib.pyplot import scatter, show
from sympy import isprime
def g(n):
assert n > 2 and n % 2 == 0, 'n in goldbach function g(n) must be even'
count = 0
for i in range(1, n//2 + 1):
if isprime(i) and isprime(n - i):
count += 1
return count
print('The first 100 G numbers are:')
col = 1
for n in range(4, 204, 2):
print(str(g(n)).ljust(4), end = '\n' if (col % 10 == 0) else '')
col += 1
print('\nThe value of G(1000000) is', g(1_000_000))
x = range(4, 4002, 2)
y = [g(i) for i in x]
colors = [["red", "blue", "green"][(i // 2) % 3] for i in x]
scatter([i // 2 for i in x], y, marker='.', color = colors)
show()
|
http://rosettacode.org/wiki/Goldbach%27s_comet
|
Goldbach's comet
|
This page uses content from Wikipedia. The original article was at Goldbach's comet. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function.
The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes.
Examples
G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)
Task
Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
Find and display the value of G(1000000)
Stretch
Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet
See also
Wikipedia: Goldbach's conjecture
OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
|
#Raku
|
Raku
|
sub G (Int $n) { +(2..$n/2).grep: { .is-prime && ($n - $_).is-prime } }
# Task
put "The first 100 G values:\n", (^100).map({ G 2 × $_ + 4 }).batch(10)».fmt("%2d").join: "\n";
put "\nG 1_000_000 = ", G 1_000_000;
# Stretch
use SVG;
use SVG::Plot;
my @x = map 2 × * + 4, ^2000;
my @y = @x.map: &G;
'Goldbachs-Comet-Raku.svg'.IO.spurt: SVG.serialize: SVG::Plot.new(
width => 1000,
height => 500,
background => 'white',
title => "Goldbach's Comet",
x => @x,
values => [@y,],
).plot: :points;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.