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/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.
|
#Euler_Math_Toolbox
|
Euler Math Toolbox
|
>A=loadrgb("mona.jpg");
>insrgb(A);
>function grayscale (A) ...
${r,g,b}=getrgb(A);
$c=0.2126*r+0.7152*g+0.0722*b;
$return rgb(c,c,c);
$endfunction
>insrgb(grayscale(A));
>insrgb(A|grayscale(A));
|
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.
|
#Euphoria
|
Euphoria
|
function to_gray(sequence image)
sequence color
for i = 1 to length(image) do
for j = 1 to length(image[i]) do
color = and_bits(image[i][j], {#FF0000,#FF00,#FF}) /
{#010000,#0100,#01} -- unpack color triple
image[i][j] = floor(0.2126*color[1] + 0.7152*color[2] + 0.0722*color[3])
end for
end for
return image
end function
function to_color(sequence image)
for i = 1 to length(image) do
for j = 1 to length(image[i]) do
image[i][j] = image[i][j]*#010101
end for
end for
return image
end function
|
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
|
#Go
|
Go
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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).
|
#Chapel
|
Chapel
|
use BigInteger; use Time;
// Chapel doesn't have closure functions that can capture variables from
// outside scope, so we use a class to emulate them for this special case;
// the member fields mult, mrglst, and mltlst, emulate "captured" variables
// that would normally be captured by the `next` continuation closure...
class HammingsList {
const head: bigint;
const mult: uint(8);
var mrglst: shared HammingsList?;
var mltlst: shared HammingsList?;
var tail: shared HammingsList? = nil;
proc init(hd: bigint, mlt: uint(8), mrgl: shared HammingsList?,
mltl: shared HammingsList?) {
head = hd; mult = mlt; mrglst = mrgl; mltlst = mltl; }
proc next(): shared HammingsList {
if tail != nil then return tail: shared HammingsList;
const nhd: bigint = mltlst!.head * mult;
if mrglst == nil then {
tail = new shared HammingsList(nhd, mult,
nil: shared HammingsList?,
nil: shared HammingsList?);
mltlst = mltlst!.next();
tail!.mltlst <=> mltlst;
}
else {
if mrglst!.head < nhd then {
tail = new shared HammingsList(mrglst!.head, mult,
nil: shared HammingsList?,
nil: shared HammingsList?);
mrglst = mrglst!.next(); mrglst <=> tail!.mrglst;
mltlst <=> tail!.mltlst;
}
else {
tail = new shared HammingsList(nhd, mult,
nil: shared HammingsList?,
nil: shared HammingsList?);
mltlst = mltlst!.next(); mltlst <=> tail!.mltlst;
mrglst <=> tail!.mrglst;
}
}
return tail: shared HammingsList;
}
}
proc u(n: uint(8), s: shared HammingsList?): shared HammingsList {
var r = new shared HammingsList(1: bigint, n, s,
nil: shared HammingsList?);
r.mltlst = r; // lazy recursion!
return r.next();
}
iter hammings(): bigint {
var nxt: shared HammingsList? = nil: shared HammingsList?;
const mlts: [ 0 .. 2 ] int = [ 5, 3, 2 ];
for m in mlts do nxt = u(m: uint(8), nxt);
yield 1 : bigint;
while true { yield nxt!.head; nxt = nxt!.next(); }
}
write("The first 20 Hamming numbers are: ");
var cnt: int = 0;
for h in hammings() { write(" ", h); cnt += 1; if cnt >= 20 then break; }
write(".\nThe 1691st Hamming number is ");
cnt = 0;
for h in hammings() { cnt += 1; if cnt < 1691 then continue; write(h); break; }
writeln(".\nThe millionth Hamming number is ");
var timer: Timer; timer.start(); cnt = 0;
for h in hammings() { cnt += 1; if cnt < 1000000 then continue; write(h); break; }
timer.stop(); writeln(".\nThis last took ",
timer.elapsed(TimeUnits.milliseconds), " milliseconds.");
|
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
|
#EasyLang
|
EasyLang
|
n = random 10 + 1
write "Guess a number between 1 and 10: "
repeat
g = number input
write g
until g = n
print " is wrong"
write "try again: "
.
print " is correct. 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
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
local
number_to_guess: INTEGER
do
number_to_guess := (create {RANDOMIZER}).random_integer_in_range (1 |..| 10)
from
print ("Please guess the number!%N")
io.read_integer
until
io.last_integer = number_to_guess
loop
print ("Please, guess again!%N")
io.read_integer
end
print ("Well guessed!%N")
end
end
|
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.
|
#Crystal
|
Crystal
|
def subarray_sum(arr)
max, slice = 0, [] of Int32
arr.each_index do |i|
(i...arr.size).each do |j|
sum = arr[i..j].sum
max, slice = sum, arr[i..j] if sum > max
end
end
[max, slice]
end
|
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.
|
#D
|
D
|
import std.stdio;
inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc {
int maxSum, thisSum, i, start, end = -1;
foreach (immutable j, immutable x; sequence) {
thisSum += x;
if (thisSum < 0) {
i = j + 1;
thisSum = 0;
} else if (thisSum > maxSum) {
maxSum = thisSum;
start = i;
end = j;
}
}
if (start <= end && start >= 0 && end >= 0)
return sequence[start .. end + 1];
else
return [];
}
void main() {
const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1];
writeln("Maximal subsequence: ", a1.maxSubseq);
const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1];
writeln("Maximal subsequence: ", a2.maxSubseq);
}
|
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.
|
#Wren
|
Wren
|
import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "./polygon" for Polygon
class Button {
construct new(x, y, w, h, legend, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_legend = legend
_c = c
_oc = oc
_lc = lc
_enabled = true
}
enabled { _enabled }
enabled=(e) { _enabled = e }
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_legend)
var lx = ((_w - l.x)/2).truncate
lx = (lx > 0) ? _x + lx : _x + 1
var ly = ((_h - l.y)/2).truncate
ly = (ly > 0) ? _y + ly : _y + 1
var col = _enabled ? _lc : Color.darkgray
Canvas.print(_legend, lx, ly, col)
}
justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) }
}
class TextBox {
construct new(x, y, w, h, label, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_label = label
_c = c
_oc = oc
_lc = lc
_text = ""
_enabled = true
}
text { _text }
text=(t) { _text = t }
enabled { _enabled }
enabled=(e) { _enabled = e }
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_label).x
var lx = _x - l - 7
if (lx < 1) {
lx = 1
_label = _label[0..._x]
}
var col = _enabled ? _lc : Color.darkgray
Canvas.print(_label, lx, _y, col)
Canvas.getPrintArea(_label).x
Canvas.print(_text, _x + 3, _y + 1, Color.black)
}
}
class GUIControlEnablement {
construct new() {
Window.title = "GUI control enablement"
_btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white)
_btnDecrement = Button.new(180, 40, 80, 80, "Decrement", Color.green, Color.blue, Color.white)
_txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white)
_txtValue.text = "0"
Keyboard.handleText = true
}
init() {
_btnDecrement.enabled = false
drawControls()
}
update() {
if (_btnIncrement.enabled && _btnIncrement.justClicked) {
var number = Num.fromString(_txtValue.text) + 1
_btnIncrement.enabled = (number < 10)
_btnDecrement.enabled = true
_txtValue.enabled = (number == 0)
_txtValue.text = number.toString
} else if (_btnDecrement.enabled && _btnDecrement.justClicked) {
var number = Num.fromString(_txtValue.text) - 1
_btnDecrement.enabled = (number > 0)
_btnIncrement.enabled = true
_txtValue.enabled = (number == 0)
_txtValue.text = number.toString
} else if (_txtValue.enabled && "0123456789".any { |d| Keyboard[d].justPressed }) {
_txtValue.text = Keyboard.text
_txtValue.enabled = (_txtValue.text == "0")
_btnIncrement.enabled = true
_btnDecrement.enabled = (_txtValue.text != "0")
}
}
draw(alpha) {
drawControls()
}
drawControls() {
Canvas.cls()
_btnIncrement.draw()
_btnDecrement.draw()
_txtValue.draw()
}
}
var Game = GUIControlEnablement.new()
|
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)
|
#CLU
|
CLU
|
read_number = proc (prompt: string) returns (int)
po: stream := stream$primary_output()
pi: stream := stream$primary_input()
while true do
stream$puts(po, prompt)
return(int$parse(stream$getl(pi)))
except when bad_format:
stream$putl(po, "Invalid number.")
end
end
end read_number
read_limits = proc () returns (int,int)
po: stream := stream$primary_output()
while true do
min: int := read_number("Lower limit? ")
max: int := read_number("Upper limit? ")
if min >= 0 cand min < max then return(min,max) end
stream$putl(po, "Invalid limits, try again.")
end
end read_limits
read_guess = proc (min, max: int) returns (int)
po: stream := stream$primary_output()
while true do
guess: int := read_number("Guess? ")
if min <= guess cand max >= guess then return(guess) end
stream$putl(po, "Guess must be between "
|| int$unparse(min) || " and " || int$unparse(max) || ".")
end
end read_guess
play_game = proc (min, max, secret: int)
po: stream := stream$primary_output()
guesses: int := 0
while true do
guesses := guesses + 1
guess: int := read_guess(min, max)
if guess = secret then break
elseif guess < secret then stream$putl(po, "Too low!")
elseif guess > secret then stream$putl(po, "Too high!")
end
end
stream$putl(po, "Correct! You got it in " || int$unparse(guesses) || " tries.")
end play_game
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
stream$putl(po, "Guess the number\n----- --- ------\n")
min, max: int := read_limits()
secret: int := min + random$next(max - min + 1)
play_game(min, max, secret)
end start_up
|
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.
|
#PicoLisp
|
PicoLisp
|
(let Pgm # Create PGM of 384 x 288 pixels
(make
(for N 4
(let L
(make
(for I (* N 8)
(let C (*/ (dec I) 255 (dec (* N 8)))
(unless (bit? 1 N)
(setq C (- 255 C)) )
(do (/ 48 N) (link C)) ) ) )
(do 72 (link L)) ) ) )
(out '(display) # Pipe to ImageMagick
(prinl "P5") # NetPBM format
(prinl (length (car Pgm)) " " (length Pgm))
(prinl 255)
(for Y Pgm (apply wr Y)) ) )
|
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.
|
#Plain_English
|
Plain English
|
To run:
Start up.
Clear the screen.
Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4.
Make a gradient with the box and 8 and "left-to-right".
Draw the gradient.
Draw the next gradient given the gradient.
Draw the next gradient given the gradient.
Draw the next gradient given the gradient.
Refresh the screen.
Wait for the escape key.
Shut down.
A gradient is a record with
A box,
A partitions number,
And a direction string. \"left-to-right" or "right-to-left"
To make a gradient with a box and a number and a string:
Put the box into the gradient's box.
Put the number into the gradient's partitions.
Put the string into the gradient's direction.
To draw a gradient:
Put the white color into a color.
Put 1000 [the maximum lightness] divided by the gradient's partitions into an amount.
If the gradient's direction is "left-to-right", put the black color into the color.
Put the gradient's box into a box.
Put the gradient's box's width divided by the gradient's partitions into a width number.
Put the width plus the box's left into the box's right.
Loop.
If a counter is past the gradient's partitions, exit.
Draw and fill the box with the color.
Move the box right the width.
If the gradient's direction is "left-to-right", lighten the color by the amount; repeat.
Darken the color by the amount.
Repeat.
To draw the next gradient given a gradient:
Move the gradient's box down the gradient's box's height.
Double the gradient's partitions.
If the gradient's direction is "left-to-right", set a flag.
If the flag is set, put "right-to-left" into the gradient's direction.
If the flag is not set, put "left-to-right" into the gradient's direction.
Draw the gradient.
|
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.
|
#PureBasic
|
PureBasic
|
EnableExplicit
Macro Check(Function)
If Not Function : End : EndIf
EndMacro
Check(InitKeyboard()) ; Cannot initialize keyboard
Check(InitSprite()) ; Cannot initialize sprite/screen library
Check(ExamineDesktops()) ; Cannot retrieve informations about desktops
Define.i iHeight, iWidth, iDepth
iHeight = DesktopHeight(0)
iWidth = DesktopWidth(0)
iDepth = DesktopDepth(0)
If OpenScreen(iWidth, iHeight, iDepth, "Press ENTER to exit")
Define.i bMode.b, iLines, fLine.f, iRow, iSpans, fSpan.f,
fColor.f, iTop, iWide, iHigh, iCol, iShade
If StartDrawing(ScreenOutput())
bMode = #True ; Pow = #True; Add = #False
iLines = 4 ; Number of Lines
If iLines < 1 : iLines = 1 : EndIf ; Pow/Add-Min
If bMode
If iLines > 6 : iLines = 6 : EndIf ; Pow-Max
Else
If iLines > 32 : iLines = 32 : EndIf ; Add-Max
EndIf
fLine = iHeight / iLines
iLines - 1
For iRow = 0 To iLines
If bMode
iSpans = Pow(2, iRow + 3) - 1 ; Pow: 8, 16, 32, 64, 128, 256
Else
iSpans = (iRow + 1) * 8 - 1 ; Add: 8, 16, 24, 32, 40, 48, ...
EndIf
fSpan = iWidth / (iSpans + 1)
fColor = 255 / iSpans
iTop = Round(iRow * fLine, #PB_Round_Up)
iWide = Round(fSpan, #PB_Round_Up)
iHigh = Round(fLine, #PB_Round_Up)
For iCol = 0 To iSpans
iShade = Round(fColor * iCol, #PB_Round_Nearest)
If iRow % 2 <> 0 : iShade = 255 - iShade : EndIf ; Alternation
Box(Round(iCol * fSpan, #PB_Round_Up), iTop, iWide, iHigh,
RGB(iShade, iShade, iShade))
Next
Next
StopDrawing()
FlipBuffers()
Repeat
Delay(30)
ExamineKeyboard()
Until KeyboardPushed(#PB_Key_Escape) Or
KeyboardPushed(#PB_Key_Return)
EndIf
CloseScreen()
EndIf
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
|
#Nim
|
Nim
|
import strutils
let oRange = 1..10
var iRange = oRange
echo """Think of a number between $# and $# and wait for me to guess it.
On every guess of mine you should state whether the guess was
too high, too low, or equal to your number by typing h, l, or =""".format(iRange.a, iRange.b)
var i = 0
while true:
inc i
let guess = (iRange.a + iRange.b) div 2
stdout.write "Guess $# is: $#. The score for which is (h,l,=): ".format(i, guess)
let txt = stdin.readLine()
case txt
of "h": iRange.b = guess - 1
of "l": iRange.a = guess + 1
of "=":
echo " Ye-Haw!!"
break
else: echo " I don't understand your input of '%s'?".format(txt)
if iRange.a > iRange.b or iRange.a < oRange.a or iRange.b > oRange.b:
echo "Please check your scoring as I cannot find the value"
break
echo "Thanks for keeping score."
|
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
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 PRINT "THINK OF A NUMBER BETWEEN 1 AND";" 9, AND I'LL TRY TO GUESS IT."
20 ISVALID=0
30 GUESS=5
40 PRINT "I GUESS"GUESS"."
50 INPUT "IS THAT HIGHER THAN, LOWER THAN OR EQUAL TO YOUR NUMBER? ",ANSWER$
60 IF ANSWER$="LOWER THAN" THEN ISVALID=1:IF GUESS<9 THEN GUESS=GUESS+1
70 IF ANSWER$="HIGHER THAN" THEN ISVALID=1:IF GUESS>1 THEN GUESS=GUESS-1
80 IF ANSWER$="EQUAL TO" THEN PRINT "OH YES! I GUESSED CORRECTLY!":END
90 IF ISVALID=0 THEN PRINT "SORRY";", BUT THAT ANSWER IS INVALID."
100 GOTO 40
|
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
|
#Dyalect
|
Dyalect
|
func happy(n) {
var m = []
while n > 1 {
m.Add(n)
var x = n
n = 0
while x > 0 {
var d = x % 10
n += d * d
x /= 10
}
if m.IndexOf(n) != -1 {
return false
}
}
return true
}
var (n, found) = (1, 0)
while found < 8 {
if happy(n) {
print("\(n) ", terminator: "")
found += 1
}
n += 1
}
print()
|
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.
|
#Objeck
|
Objeck
|
bundle Default {
class Haversine {
function : Dist(th1 : Float, ph1 : Float, th2 : Float, ph2 : Float) ~ Float {
ph1 -= ph2;
ph1 := ph1->ToRadians();
th1 := th1->ToRadians();
th2 := th2->ToRadians();
dz := th1->Sin()- th2->Sin();
dx := ph1->Cos() * th1->Cos() - th2->Cos();
dy := ph1->Sin() * th1->Cos();
return ((dx * dx + dy * dy + dz * dz)->SquareRoot() / 2.0)->ArcSin() * 2 * 6371.0;
}
function : Main(args : String[]) ~ Nil {
IO.Console->Print("distance: ")->PrintLine(Dist(36.12, -86.67, 33.94, -118.4));
}
}
}
|
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
|
#Genie
|
Genie
|
init
print "Hello world!"
|
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
|
#Pascal
|
Pascal
|
program Niven;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
const
base = 10;
type
tNum = longword; {Uint64}
{$IFDEF FPC}
const
cntbasedigits = trunc(ln(High(tNum)) / ln(base)) + 1;
{$ELSE}
var
cntbasedigits: Integer = 0;
{$ENDIF}
type
tSumDigit = record
sdNumber: tNum;
{$IFDEF FPC}
sdDigits: array[0..cntbasedigits - 1] of byte;
{$ELSE}
sdDigits: TArray<Byte>;
{$ENDIF}
sdSumDig: byte;
sdIsNiven: boolean;
end;
function InitSumDigit(n: tNum): tSumDigit;
var
sd: tSumDigit;
qt: tNum;
i: integer;
begin
with sd do
begin
sdNumber := n;
{$IFDEF FPC}
fillchar(sdDigits, SizeOf(sdDigits), #0);
{$ELSE}
SetLength(sdDigits,cntbasedigits);
fillchar(sdDigits[0], SizeOf(sdDigits), #0);
{$ENDIF}
sdSumDig := 0;
sdIsNiven := false;
i := 0;
// calculate Digits und sum them up
while n > 0 do
begin
qt := n div base;
{n mod base}
sdDigits[i] := n - qt * base;
inc(sdSumDig, sdDigits[i]);
n := qt;
inc(i);
end;
if sdSumDig > 0 then
sdIsNiven := (sdNumber mod sdSumDig = 0);
end;
InitSumDigit := sd;
end;
procedure IncSumDigit(var sd: tSumDigit);
var
i, d: integer;
begin
i := 0;
with sd do
begin
inc(sdNumber);
repeat
d := sdDigits[i];
inc(d);
inc(sdSumDig);
//base-1 times the repeat is left here
if d < base then
begin
sdDigits[i] := d;
BREAK;
end
else
begin
sdDigits[i] := 0;
dec(sdSumDig, base);
inc(i);
end;
until i > high(sdDigits);
sdIsNiven := (sdNumber mod sdSumDig) = 0;
end;
end;
var
MySumDig: tSumDigit;
lnn: tNum;
cnt: integer;
begin
{$IFNDEF FPC}
cntbasedigits := trunc(ln(High(tNum)) / ln(base)) + 1;
{$ENDIF}
MySumDig := InitSumDigit(0);
cnt := 0;
repeat
IncSumDigit(MySumDig);
if MySumDig.sdIsNiven then
begin
write(MySumDig.sdNumber, '.');
inc(cnt);
end;
until cnt >= 20;
write('....');
MySumDig := InitSumDigit(1000);
repeat
IncSumDigit(MySumDig);
until MySumDig.sdIsNiven;
writeln(MySumDig.sdNumber, '.');
// searching for big gaps between two niven-numbers
// MySumDig:=InitSumDigit(18879989100-276);
MySumDig := InitSumDigit(1);
cnt := 0;
lnn := MySumDig.sdNumber;
repeat
IncSumDigit(MySumDig);
if MySumDig.sdIsNiven then
begin
if cnt < (MySumDig.sdNumber - lnn) then
begin
cnt := (MySumDig.sdNumber - lnn);
writeln(lnn, ' --> ', MySumDig.sdNumber, ' d=', cnt);
end;
lnn := MySumDig.sdNumber;
end;
until MySumDig.sdNumber = High(tNum);
{
689988915 --> 689989050 d=135
879987906 --> 879988050 d=144
989888823 --> 989888973 d=150
2998895823 --> 2998895976 d=153
~ 24 Cpu-cycles per test i3- 4330 1..2^32-1}
{$IFNDEF LINUX}readln;{$ENDIF}
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
|
#JavaScript
|
JavaScript
|
alert("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).
|
#Python
|
Python
|
import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
|
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.
|
#APL
|
APL
|
N←5
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)
|
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.
|
#Arturo
|
Arturo
|
toGray: function [n]-> xor n shr n 1
fromGray: function [n][
p: n
while [n > 0][
n: shr n 1
p: xor p n
]
return p
]
loop 0..31 'num [
encoded: toGray num
decoded: fromGray encoded
print [
pad to :string num 2 ":"
pad as.binary num 5 "=>"
pad as.binary encoded 5 "=>"
pad as.binary decoded 5 ":"
pad to :string decoded 2
]
]
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#6502_Assembly
|
6502 Assembly
|
JSR $FFED
;returns screen width in X and screen height in Y
dex ;subtract 1. This is more useful for comparisons.
dey ;subtract 1. This is more useful for comparisons.
stx $20 ;store in zero page ram
sty $21 ;store in zero page ram
|
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.
|
#Aime
|
Aime
|
integer
lmax(list l)
{
integer max, x;
max = l[0];
for (, x in l) {
if (max < x) {
max = x;
}
}
max;
}
|
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.
|
#360_Assembly
|
360 Assembly
|
* Greatest common divisor 04/05/2016
GCD CSECT
USING GCD,R15 use calling register
L R6,A u=a
L R7,B v=b
LOOPW LTR R7,R7 while v<>0
BZ ELOOPW leave while
LR R8,R6 t=u
LR R6,R7 u=v
LR R4,R8 t
SRDA R4,32 shift to next reg
DR R4,R7 t/v
LR R7,R4 v=mod(t,v)
B LOOPW end while
ELOOPW LPR R9,R6 c=abs(u)
L R1,A a
XDECO R1,XDEC edit a
MVC PG+4(5),XDEC+7 move a to buffer
L R1,B b
XDECO R1,XDEC edit b
MVC PG+10(5),XDEC+7 move b to buffer
XDECO R9,XDEC edit c
MVC PG+17(5),XDEC+7 move c to buffer
XPRNT PG,80 print buffer
XR R15,R15 return code =0
BR R14 return to caller
A DC F'1071' a
B DC F'1029' b
PG DC CL80'gcd(00000,00000)=00000' buffer
XDEC DS CL12 temp for edit
YREGS
END GCD
|
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.
|
#Ada
|
Ada
|
with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;
procedure Global_Replace is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
function "+"(S: String) return U_String renames
Ada.Strings.Unbounded.To_Unbounded_String;
function "-"(U: U_String) return String renames
Ada.Strings.Unbounded.To_String;
procedure String_Replace(S: in out U_String; Pattern, Replacement: String) is
-- example: if S is "Mary had a XX lamb", then String_Replace(S, "X", "little");
-- will turn S into "Mary had a littlelittle lamb"
-- and String_Replace(S, "Y", "small"); will not change S
Index : Natural;
begin
loop
Index := Ada.Strings.Unbounded.Index(Source => S, Pattern => Pattern);
exit when Index = 0;
Ada.Strings.Unbounded.Replace_Slice
(Source => S, Low => Index, High => Index+Pattern'Length-1,
By => Replacement);
end loop;
end String_Replace;
procedure File_Replace(Filename: String; Pattern, Replacement: String) is
-- applies String_Rplace to each line in the file with the given Filename
-- propagates any exceptions, when, e.g., the file does not exist
I_File, O_File: Ada.Text_IO.File_Type;
Line: U_String;
Tmp_Name: String := Filename & ".tmp";
-- name of temporary file; if that file already exists, it will be overwritten
begin
Ada.Text_IO.Open(I_File, Ada.Text_IO.In_File, Filename);
Ada.Text_IO.Create(O_File, Ada.Text_IO.Out_File, Tmp_Name);
while not Ada.Text_IO.End_Of_File(I_File) loop
Line := +Ada.Text_IO.Get_Line(I_File);
String_Replace(Line, Pattern, Replacement);
Ada.Text_IO.Put_Line(O_File, -Line);
end loop;
Ada.Text_IO.Close(I_File);
Ada.Text_IO.Close(O_File);
Ada.Directories.Delete_File(Filename);
Ada.Directories.Rename(Old_Name => Tmp_Name, New_Name => Filename);
end File_Replace;
Pattern: String := Ada.Command_Line.Argument(1);
Replacement: String := Ada.Command_Line.Argument(2);
begin
Ada.Text_IO.Put_Line("Replacing """ & Pattern
& """ by """ & Replacement & """ in"
& Integer'Image(Ada.Command_Line.Argument_Count - 2)
& " files.");
for I in 3 .. Ada.Command_Line.Argument_Count loop
File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement);
end loop;
end Global_Replace;
|
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).
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure hailstone is
type int_arr is array(Positive range <>) of Integer;
type int_arr_pt is access all int_arr;
function hailstones(num:Integer; pt:int_arr_pt) return Integer is
stones : Integer := 1;
n : Integer := num;
begin
if pt /= null then pt(1) := num; end if;
while (n/=1) loop
stones := stones + 1;
if n mod 2 = 0 then n := n/2;
else n := (3*n)+1;
end if;
if pt /= null then pt(stones) := n; end if;
end loop;
return stones;
end hailstones;
nmax,stonemax,stones : Integer := 0;
list : int_arr_pt;
begin
stones := hailstones(27,null);
list := new int_arr(1..stones);
stones := hailstones(27,list);
put(" 27: "&Integer'Image(stones)); new_line;
for n in 1..4 loop put(Integer'Image(list(n))); end loop;
put(" .... ");
for n in stones-3..stones loop put(Integer'Image(list(n))); end loop;
new_line;
for n in 1..100000 loop
stones := hailstones(n,null);
if stones>stonemax then
nmax := n; stonemax := stones;
end if;
end loop;
put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
end hailstone;
|
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.
|
#Raku
|
Raku
|
sub GraphNodeColor(@RAW) {
my %OneMany = my %NodeColor;
for @RAW { %OneMany{$_[0]}.push: $_[1] ; %OneMany{$_[1]}.push: $_[0] }
my @ColorPool = "0", "1" … ^+%OneMany.elems; # as string
my %NodePool = %OneMany.BagHash; # this DWIM is nice
if %OneMany<NaN>:exists { %NodePool{$_}:delete for %OneMany<NaN>, NaN } # pending
while %NodePool.Bool {
my $color = @ColorPool.shift;
my %TempPool = %NodePool;
while (my \n = %TempPool.keys.sort.first) {
%NodeColor{n} = $color;
%TempPool{n}:delete;
%TempPool{$_}:delete for @(%OneMany{n}) ; # skip neighbors as well
%NodePool{n}:delete;
}
}
if %OneMany<NaN>:exists { # islanders use an existing color
%NodeColor{$_} = %NodeColor.values.sort.first for @(%OneMany<NaN>)
}
return %NodeColor
}
my \DATA = [
[<0 1>,<1 2>,<2 0>,<3 NaN>,<4 NaN>,<5 NaN>],
[<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 DATA {
say "DATA : ", $_;
say "Result : ";
my %out = GraphNodeColor $_;
say "$_[0]-$_[1]:\t Color %out{$_[0]} ",$_[1].isNaN??''!!%out{$_[1]} for @$_;
say "Nodes : ", %out.keys.elems;
say "Edges : ", $_.elems;
say "Colors : ", %out.values.Set.elems;
}
|
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
|
#Wren
|
Wren
|
import "./math" for Int
import "./trait" for Stepped
import "./fmt" for Fmt
import "io" for File
var limit = 2000
var primes = Int.primeSieve(limit-1).skip(1).toList
var goldbach = {4: 1}
for (i in Stepped.new(6..limit, 2)) goldbach[i] = 0
for (i in 0...primes.count) {
for (j in i...primes.count) {
var s = primes[i] + primes[j]
if (s > limit) break
goldbach[s] = goldbach[s] + 1
}
}
System.print("The first 100 G values:")
var count = 0
for (i in Stepped.new(4..202, 2)) {
count = count + 1
Fmt.write("$2d ", goldbach[i])
if (count % 10 == 0) System.print()
}
primes = Int.primeSieve(499999).skip(1)
var gm = 0
for (p in primes) {
if (Int.isPrime(1e6 - p)) gm = gm + 1
}
System.print("\nG(1000000) = %(gm)")
// create .csv file for values up to 2000 for display by an external plotter
// the third field being the color (red = 0, blue = 1, green = 2)
File.create("goldbachs_comet.csv") { |file|
for(i in Stepped.new(4..limit, 2)) {
file.writeBytes("%(i), %(goldbach[i]), %(i/2 % 3)\n")
}
}
|
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.
|
#Factor
|
Factor
|
USING: arrays kernel math math.matrices math.vectors ;
: rgb>gray ( matrix -- new-matrix )
[ { 0.2126 0.7152 0.0722 } vdot >integer ] matrix-map ;
: gray>rgb ( matrix -- new-matrix )
[ dup dup 3array ] matrix-map ;
|
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.
|
#FBSL
|
FBSL
|
DIM colored = ".\LenaClr.bmp", grayscale = ".\LenaGry.bmp"
DIM head, tail, r, g, b, l, ptr, blobsize = 54 ' sizeof BMP file headers
FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' load buffer
head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' set loop bounds
FOR ptr = head TO tail STEP 3 ' transform color triplets
b = PEEK(ptr + 0, 1) ' read Windows colors stored in BGR order
g = PEEK(ptr + 1, 1)
r = PEEK(ptr + 2, 1)
l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' derive luminance
SETMEM(FILEGET, RGB(l, l, l), ptr - head + blobsize, 3) ' write grayscale
NEXT
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save buffer
|
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
|
#Haskell
|
Haskell
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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).
|
#Clojure
|
Clojure
|
(defn smerge [xs ys]
(lazy-seq
(let [x (first xs),
y (first ys),
[z xs* ys*]
(cond
(< x y) [x (rest xs) ys]
(> x y) [y xs (rest ys)]
:else [x (rest xs) (rest ys)])]
(cons z (smerge xs* ys*)))))
(def hamming
(lazy-seq
(->> (map #(*' 5 %) hamming)
(smerge (map #(*' 3 %) hamming))
(smerge (map #(*' 2 %) hamming))
(cons 1))))
|
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
|
#Elena
|
Elena
|
import extensions;
public program()
{
int randomNumber := randomGenerator.eval(1,10);
console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?");
bool numberCorrect := false;
until(numberCorrect)
{
console.print("Guess: ");
int userGuess := console.readLine().toInt();
if (randomNumber == userGuess)
{
numberCorrect := true;
console.printLine("Congrats!! You guessed right!")
}
else
{
console.printLine("That's not it. Guess again.")
}
}
}
|
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
|
#Elixir
|
Elixir
|
defmodule GuessingGame do
def play do
play(Enum.random(1..10))
end
defp play(number) do
guess = Integer.parse(IO.gets "Guess a number (1-10): ")
case guess do
{^number, _} ->
IO.puts "Well guessed!"
{n, _} when n in 1..10 ->
IO.puts "That's not it."
play(number)
_ ->
IO.puts "Guess not in valid range."
play(number)
end
end
end
GuessingGame.play
|
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.
|
#Delphi
|
Delphi
|
pragma.enable("accumulator")
def maxSubseq(seq) {
def size := seq.size()
# Collect all intervals of indexes whose values are positive
def intervals := {
var intervals := []
var first := 0
while (first < size) {
var next := first
def seeing := seq[first] > 0
while (next < size && (seq[next] > 0) == seeing) {
next += 1
}
if (seeing) { # record every positive interval
intervals with= first..!next
}
first := next
}
intervals
}
# For recording the best result found
var maxValue := 0
var maxInterval := 0..!0
# Try all subsequences beginning and ending with such intervals.
for firstIntervalIx => firstInterval in intervals {
for lastInterval in intervals(firstIntervalIx) {
def interval :=
(firstInterval.getOptStart())..!(lastInterval.getOptBound())
def value :=
accum 0 for i in interval { _ + seq[i] }
if (value > maxValue) {
maxValue := value
maxInterval := interval
}
}
}
return ["value" => maxValue,
"indexes" => maxInterval]
}
|
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)
|
#COBOL
|
COBOL
|
IDENTIFICATION DIVISION.
PROGRAM-ID. Guess-With-Feedback.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 Seed PIC 9(8).
01 Random-Num PIC 99.
01 Guess PIC 99.
PROCEDURE DIVISION.
ACCEPT Seed FROM TIME
COMPUTE Random-Num =
FUNCTION REM(FUNCTION RANDOM(Seed) * 1000, 10) + 1
DISPLAY "Guess a number between 1 and 10:"
PERFORM FOREVER
ACCEPT Guess
IF Guess > Random-Num
DISPLAY "Your guess was too high."
ELSE IF Guess < Random-Num
DISPLAY "Your guess was too low."
ELSE
DISPLAY "Well guessed!"
EXIT PERFORM
END-PERFORM
GOBACK
.
|
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.
|
#Python
|
Python
|
#!/usr/bin/env python
#four gray scaled stripes 8:16:32:64 in Python 2.7.1
from livewires import *
horiz=640; vert=480; pruh=vert/4; dpp=255.0
begin_graphics(width=horiz,height=vert,title="Gray stripes",background=Colour.black)
def ty_pruhy(each):
hiy=each[0]*pruh; loy=hiy-pruh
krok=horiz/each[1]; piecol=255.0/(each[1]-1)
for x in xrange(0,each[1]):
barva=Colour(piecol*x/dpp,piecol*x/dpp,piecol*x/dpp ); set_colour(barva)
if each[2]:
box(x*krok,hiy,x*krok+krok,loy,filled=1)
else:
box(horiz-x*krok,hiy,horiz-((x+1)*krok),loy,filled=1)
# main
source=[[4,8,True],[3,16,False],[2,32,True],[1,64,False]]
for each in source:
ty_pruhy(each)
while keys_pressed() != [' ']: # press spacebar to close window
pass
|
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.
|
#R
|
R
|
mat <- matrix(c(rep(1:8, each = 8) / 8,
rep(16:1, each = 4) / 16,
rep(1:32, each = 2) / 32,
rep(64:1, each = 1) / 64),
nrow = 4, byrow = TRUE)
par(mar = rep(0, 4))
image(t(mat[4:1, ]), col = gray(1:64/64), axes = FALSE)
|
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
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
@interface GuessNumberFakeArray : NSArray {
int lower, upper;
}
- (instancetype)initWithLower:(int)l andUpper:(int)u;
@end
@implementation GuessNumberFakeArray
- (instancetype)initWithLower:(int)l andUpper:(int)u {
if ((self = [super init])) {
lower = l;
upper = u;
}
return self;
}
- (NSUInteger)count { return upper-lower; }
- (id)objectAtIndex:(NSUInteger)i {
printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", lower + (int)i);
char input[2] = " ";
scanf("%1s", input);
switch (tolower(input[0])) {
case 'l':
return @-1;
case 'h':
return @1;
case 'c':
return @0;
}
return nil;
}
@end
#define LOWER 0
#define UPPER 100
int main(int argc, const char *argv[]) {
@autoreleasepool {
printf("Instructions:\n"
"Think of integer number from %d (inclusive) to %d (exclusive) and\n"
"I will guess it. After each guess, you respond with L, H, or C depending\n"
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
NSUInteger result = [[[GuessNumberFakeArray alloc] initWithLower:LOWER andUpper:UPPER]
indexOfObject:[NSNumber numberWithInt: 0]
inSortedRange:NSMakeRange(0, UPPER - LOWER)
options:0
usingComparator:^(id x, id y){ return [x compare: y]; }];
if (result == NSNotFound)
printf("That is impossible.\n");
else
printf("Your number is %d.", LOWER + (int)result);
}
return 0;
}
|
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
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
next-num:
0
while over:
over
* dup % swap 10
+
swap floor / swap 10 swap
drop swap
is-happy happies n:
if has happies n:
return happies! n
local :seq set{ n }
n
while /= 1 dup:
next-num
if has seq dup:
drop
set-to happies n false
return false
if has happies dup:
set-to happies n dup happies!
return
set-to seq over true
drop
set-to happies n true
true
local :h {}
1 0
while > 8 over:
if is-happy h dup:
!print( "A happy number: " over )
swap ++ swap
++
drop
drop
|
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.
|
#Objective-C
|
Objective-C
|
+ (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1
lat2:(double)lat2 lon2:(double)lon2 {
//degrees to radians
double lat1rad = lat1 * M_PI/180;
double lon1rad = lon1 * M_PI/180;
double lat2rad = lat2 * M_PI/180;
double lon2rad = lon2 * M_PI/180;
//deltas
double dLat = lat2rad - lat1rad;
double dLon = lon2rad - lon1rad;
double a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad);
double c = 2 * asin(sqrt(a));
double R = 6372.8;
return R * c;
}
|
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
|
#Gentee
|
Gentee
|
func hello <main>
{
print("Hello world!")
}
|
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
|
#Perl
|
Perl
|
#!/usr/bin/perl
use strict ;
use warnings ;
use List::Util qw ( sum ) ;
sub createHarshads {
my @harshads ;
my $number = 1 ;
do {
if ( $number % sum ( split ( // , $number ) ) == 0 ) {
push @harshads , $number ;
}
$number++ ;
} until ( $harshads[ -1 ] > 1000 ) ;
return @harshads ;
}
my @harshadnumbers = createHarshads ;
for my $i ( 0..19 ) {
print "$harshadnumbers[ $i ]\n" ;
}
print "The first Harshad number greater than 1000 is $harshadnumbers[ -1 ]!\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
|
#jq
|
jq
|
# Convert a JSON object to a string suitable for use as a CSS style value
# e.g: "font-size: 40px; text-align: center;" (without the quotation marks)
def to_s:
reduce to_entries[] as $pair (""; . + "\($pair.key): \($pair.value); ");
# Defaults: 100%, 100%
def svg(width; height):
"<svg width='\(width // "100%")' height='\(height // "100%")'
xmlns='http://www.w3.org/2000/svg'>";
# Defaults:
# id: "linearGradient"
# color1: rgb(0,0,0)
# color2: rgb(255,255,255)
def linearGradient(id; color1; color2):
"<defs>
<linearGradient id='\(id//"linearGradient")' x1='0%' y1='0%' x2='100%' y2='0%'>
<stop offset='0%' style='stop-color:\(color1//"rgb(0,0,0)");stop-opacity:1' />
<stop offset='100%' style='stop-color:\(color2//"rgb(255,255,255)");stop-opacity:1' />
</linearGradient>
</defs>";
# input: the text string
# "style" should be a JSON object (see for example the default ($dstyle));
# the style actually used is (default + style), i.e. whatever is specified in "style" wins.
# Defaults:
# x: 0
# y: 0
def text(x; y; style):
. as $in
| {"font-size": "40px", "text-align": "center", "text-anchor": "left", "fill": "black"} as $dstyle
| (($dstyle + style) | to_s) as $style
| "<text x='\(x//0)' y='\(y//0)' style='\($style)'>
\(.)",
"</text>";
|
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
|
#JSE
|
JSE
|
Text 25,10,"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).
|
#R
|
R
|
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
w <- gwindow("Interaction")
g <- ggroup(cont=w, horizontal=FALSE)
e <- gedit(0, cont=g, coerce.with=as.numeric)
bg <- ggroup(cont=g)
inc_btn <- gbutton("increment", cont=bg)
rdm_btn <- gbutton("random", cont=bg)
addHandlerChanged(e, handler=function(h,...) {
val <- svalue(e)
if(is.na(val))
galert("You need to enter a number", parent=w)
})
addHandlerChanged(inc_btn, handler=function(h,...) {
val <- svalue(e)
if(is.na(val))
galert("Can't increment if not a number", parent=w)
else
svalue(e) <- val + 1
})
addHandlerChanged(rdm_btn, handler=function(h,...) {
if(gconfirm("Really replace value?"))
svalue(e) <- sample(1:1000, 1)
})
|
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).
|
#Racket
|
Racket
|
#lang racket/gui
(define frame (new frame% [label "Interaction Demo"]))
(define inp
(new text-field% [label "Value"] [parent frame] [init-value "0"]
[callback
(λ(f ev)
(define v (send f get-value))
(unless (string->number v)
(send f set-value (regexp-replace* #rx"[^0-9]+" v ""))))]))
(define buttons (new horizontal-pane% [parent frame]))
(define inc-b
(new button% [parent buttons] [label "Increment"]
[callback (λ (b e) (let* ([v (string->number (send inp get-value))]
[v (number->string (add1 v))])
(send inp set-value v)))]))
(define rand-b
(new button% [parent buttons] [label "Random"]
[callback (λ (b e) (when (message-box "Confirm" "Are you sure?"
frame '(yes-no))
(send inp set-value (~a (random 10000)))))]))
(send frame show #t)
|
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.
|
#AutoHotkey
|
AutoHotkey
|
gray_encode(n){
return n ^ (n >> 1)
}
gray_decode(n){
p := n
while (n >>= 1)
p ^= n
return p
}
BinString(n){
Loop 5
If ( n & ( 1 << (A_Index-1) ) )
o := "1" . o
else o := "0" . o
return o
}
Loop 32
n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n))
. " => " BinString(gray_decode(e)) " => " BinString(n) "`n"
MsgBox % clipboard := out
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#68000_Assembly
|
68000 Assembly
|
doRNG:
;run this during vblank for best results.
JSR SYS_READ_CALENDAR
;gets the calendar.
;MAME uses your computer's time for this.
MOVE.L BIOS_HOUR,D0 ;D0 = HHMMSS00
LSR.L #8,D0 ;shift out the zeroes.
MOVE.L frame_timer,D1 ;this value is incremented by 1 every vBlank (i.e. just before this procedure is run)
NOT.L D1 ;flip all the bits of D1
MULS D1,D0
MULU D1,D0
MOVE.L JOYPAD1,D1 ;get the most recent button presses.
CloneByte D1 ;copy this byte to all 4 bytes of D1
EOR.L D1,D0
MOVE.L RNGout_32,D2 ;look at last time's results.
AND.B #1,D2 ;check if it's odd or even
BNE SwapRNGifEven
SWAP D0 ;if even, swap the low and high words of D0
SwapRNGifEven:
MOVE.L D0,RNGout_32
rts
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect; use GNAT.Expect;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.String_Split; use GNAT.String_Split;
procedure System_Command is
Command : String := "ls -l";
Args : Argument_List_Access;
Status : aliased Integer;
Separators : constant String := LF & CR;
Reply_List : Slice_Set;
begin
Args := Argument_String_To_List (Command);
-- execute the system command and get the output in a single string
declare
Response : String :=
Get_Command_Output
(Command => Args (Args'First).all,
Arguments => Args (Args'First + 1 .. Args'Last),
Input => "",
Status => Status'Access);
begin
Free (Args);
-- split the output in a slice for easier manipulation
if Status = 0 then
Create (S => Reply_List,
From => Response,
Separators => Separators,
Mode => Multiple);
end if;
end;
-- do something with the system output. Just print it out
for I in 1 .. Slice_Count (Reply_List) loop
Put_Line (Slice (Reply_List, I));
end loop;
end System_Command;
|
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.
|
#ALGOL_68
|
ALGOL 68
|
# substitute any array type with a scalar element #
MODE FLT = REAL;
# create an exception for the case of an empty array #
PROC raise empty array = VOID:(
GO TO except empty array
);
PROC max = ([]FLT item)FLT:
BEGIN
IF LWB item > UPB item THEN
raise empty array; SKIP
ELSE
FLT max element := item[LWB item];
FOR i FROM LWB item + 1 TO UPB item DO
IF item[i] > max element THEN
max element := item[i]
FI
OD;
max element
FI
END # max #;
test:(
[]FLT buf = (-275.0, -111.19, 0.0, -1234568.0, pi, -pi);
print((max(buf),new line)) EXIT
except empty array:
SKIP
)
|
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.
|
#8th
|
8th
|
: gcd \ a b -- gcd
dup 0 n:= if drop ;; then
tuck \ b a b
n:mod \ b a-mod-b
recurse ;
: demo \ a b --
2dup "GCD of " . . " and " . . " = " . gcd . ;
100 5 demo cr
5 100 demo cr
7 23 demo cr
bye
|
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.
|
#AutoHotkey
|
AutoHotkey
|
SetWorkingDir %A_ScriptDir% ; Change the working directory to the script's location
listFiles := "a.txt|b.txt|c.txt" ; Define a list of files in the current working directory
loop, Parse, listFiles, |
{
; The above parses the list based on the | character
fileread, contents, %A_LoopField% ; Read the file
fileDelete, %A_LoopField% ; Delete the file
stringReplace, contents, contents, Goodbye London!, Hello New York!, All ; replace all occurrences
fileAppend, %contents%, %A_LoopField% ; Re-create the file with new contents
}
|
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.
|
#AWK
|
AWK
|
# syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s)
BEGIN {
old_text = "Goodbye London!"
new_text = "Hello New York!"
}
BEGINFILE {
nfiles_in++
text_found = 0
delete arr
}
{ if (gsub(old_text,new_text,$0) > 0) {
text_found++
}
arr[FNR] = $0
}
ENDFILE {
if (text_found > 0) {
nfiles_out++
close(FILENAME)
for (i=1; i<=FNR; i++) {
printf("%s\n",arr[i]) >FILENAME
}
}
}
END {
printf("files: %d read, %d updated\n",nfiles_in,nfiles_out)
exit(0)
}
|
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).
|
#Aime
|
Aime
|
void
print_hailstone(integer h)
{
list l;
while (h ^ 1) {
lb_p_integer(l, h);
h = h & 1 ? 3 * h + 1 : h / 2;
}
o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n",
l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, ~l + 1);
}
void
max_hailstone(integer x)
{
integer e, i, m;
index r;
m = 0;
i = 1;
while (i < x) {
integer h, k, l;
h = i;
l = 1;
while (h ^ 1) {
if (i_j_integer(k, r, h)) {
l += k;
break;
} else {
l += 1;
h = h & 1 ? 3 * h + 1 : h / 2;
}
}
r[i] = l - 1;
if (m < l) {
m = l;
e = i;
}
i += 1;
}
o_form("hailstone sequence length for ~ is ~\n", e, m);
}
integer
main(void)
{
print_hailstone(27);
max_hailstone(100000);
return 0;
}
|
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.
|
#Wren
|
Wren
|
import "/dynamic" for Struct
import "/sort" for Sort
import "/fmt" for Fmt
// (n)umber of node and its (v)alence i.e. number of neighbors
var NodeVal = Struct.create("NodeVal", ["n", "v"])
class Graph {
construct new(nn, st) {
_nn = nn // number of nodes
_st = st // node numbering starts from
_nbr = List.filled(nn, null) // neighbor list for each node
for (i in 0...nn) _nbr[i] = []
}
nn { _nn }
st { _st }
// Note that this creates a single 'virtual' edge for an isolated node.
addEdge(n1, n2) {
// adjust to starting node number
n1 = n1 - _st
n2 = n2 - _st
_nbr[n1].add(n2)
if (n1 != n2) _nbr[n2].add(n1)
}
// Uses 'greedy' algorithm.
greedyColoring {
// create a list with a color for each node
var cols = List.filled(_nn, -1) // -1 denotes no color assigned
cols[0] = 0 // first node assigned color 0
// create a bool list to keep track of which colors are available
var available = List.filled(_nn, false)
// assign colors to all nodes after the first
for (i in 1..._nn) {
// iterate through neighbors and mark their colors as available
for (j in _nbr[i]) {
if (cols[j] != -1) available[cols[j]] = true
}
// find the first available color
var c = available.indexOf(false)
cols[i] = c // assign it to the current node
// reset the neighbors' colors to unavailable
// before the next iteration
for (j in _nbr[i]) {
if (cols[j] != -1) available[cols[j]] = false
}
}
return cols
}
// Uses Welsh-Powell algorithm.
wpColoring {
// create NodeVal for each node
var nvs = List.filled(_nn, null)
for (i in 0..._nn) {
var v = _nbr[i].count
if (v == 1 && _nbr[i][0] == i) { // isolated node
v = 0
}
nvs[i] = NodeVal.new(i, v)
}
// sort the NodeVals in descending order by valence
var cmp = Fn.new { |nv1, nv2| (nv2.v - nv1.v).sign }
Sort.insertion(nvs, cmp) // stable sort
// create colors list with entries for each node
var cols = List.filled(_nn, -1) // set all nodes to no color (-1) initially
var currCol = 0 // start with color 0
for (f in 0..._nn-1) {
var h = nvs[f].n
if (cols[h] != -1) { // already assigned a color
continue
}
cols[h] = currCol
// assign same color to all subsequent uncolored nodes which are
// not connected to a previous colored one
var i = f + 1
while (i < _nn) {
var outer = false
var j = nvs[i].n
if (cols[j] != -1) { // already colored
i = i + 1
continue
}
var k = f
while (k < i) {
var l = nvs[k].n
if (cols[l] == -1) { // not yet colored
k = k + 1
continue
}
if (_nbr[j].contains(l)) {
outer = true
break // node j is connected to an earlier colored node
}
k = k + 1
}
if (!outer) cols[j] = currCol
i = i + 1
}
currCol = currCol + 1
}
return cols
}
}
var fns = [Fn.new { |g| g.greedyColoring }, Fn.new { |g| g.wpColoring }]
var titles = ["'Greedy'", "Welsh-Powell"]
var nns = [4, 8, 8, 8]
var starts = [0, 1, 1, 1]
var edges1 = [[0, 1], [1, 2], [2, 0], [3, 3]]
var edges2 = [[1, 6], [1, 7], [1, 8], [2, 5], [2, 7], [2, 8],
[3, 5], [3, 6], [3, 8], [4, 5], [4, 6], [4, 7]]
var edges3 = [[1, 4], [1, 6], [1, 8], [3, 2], [3, 6], [3, 8],
[5, 2], [5, 4], [5, 8], [7, 2], [7, 4], [7, 6]]
var edges4 = [[1, 6], [7, 1], [8, 1], [5, 2], [2, 7], [2, 8],
[3, 5], [6, 3], [3, 8], [4, 5], [4, 6], [4, 7]]
var j = 0
for (fn in fns) {
System.print("Using the %(titles[j]) algorithm:\n")
var i = 0
for (edges in [edges1, edges2, edges3, edges4]) {
System.print(" Example %(i+1)")
var g = Graph.new(nns[i], starts[i])
for (e in edges) g.addEdge(e[0], e[1])
var cols = fn.call(g)
var ecount = 0 // counts edges
for (e in edges) {
if (e[0] != e[1]) {
Fmt.print(" Edge $d-$d -> Color $d, $d", e[0], e[1],
cols[e[0]-g.st], cols[e[1]-g.st])
ecount = ecount + 1
} else {
Fmt.print(" Node $d -> Color $d\n", e[0], cols[e[0]-g.st])
}
}
var maxCol = 0 // maximum color number used
for (col in cols) {
if (col > maxCol) maxCol = col
}
System.print(" Number of nodes : %(nns[i])")
System.print(" Number of edges : %(ecount)")
System.print(" Number of colors : %(maxCol+1)")
System.print()
i = i + 1
}
j = j + 1
}
|
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
|
#XPL0
|
XPL0
|
func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
int PT(1_000_000);
func G(E); \Ways E can be expressed as sum of two primes
int E, C, I, J, T;
[C:= 0; I:= 0;
loop [J:= I;
if PT(J) + PT(I) > E then return C;
loop [T:= PT(J) + PT(I);
if T = E then C:= C+1;
if T > E then quit;
J:= J+1;
];
I:= I+1;
];
];
int I, N;
[I:= 0; \make prime table
for N:= 2 to 1_000_000 do
if IsPrime(N) then
[PT(I):= N; I:= I+1];
I:= 4; \show first 100 G numbers
Format(4, 0);
for N:= 1 to 100 do
[RlOut(0, float(G(I)));
if rem(N/10) = 0 then CrLf(0);
I:= I+2;
];
CrLf(0);
Text(0, "G(1,000,000) = "); IntOut(0, G(1_000_000));
CrLf(0);
]
|
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.
|
#Forth
|
Forth
|
\ grayscale bitmap (without word-alignment for scan lines)
\ bdim, bwidth, bdata all work with graymaps
: graymap ( w h -- gmp )
2dup * bdata allocate throw
dup >r 2! r> ;
: gxy ( x y gmp -- addr )
dup bwidth rot * rot + swap bdata + ;
: g@ ( x y gmp -- c ) gxy c@ ;
: g! ( c x y bmp -- ) gxy c! ;
: gfill ( c gmp -- )
dup bdata swap bdim * rot fill ;
: gshow ( gmp -- )
dup bdim
0 do cr
dup 0 do
over i j rot g@ if [char] * emit else space then
loop
loop
2drop ;
\ RGB <-> Grayscale
: lum>rgb ( 0..255 -- pixel )
dup 8 lshift or
dup 8 lshift or ;
: pixel>rgb ( pixel -- r g b )
256 /mod 256 /mod ;
: rgb>lum ( pixel -- 0..255 )
pixel>rgb
722 * swap
7152 * + swap
2126 * + 10000 / ;
: bitmap>graymap ( bmp -- gmp )
dup bdim graymap
dup bdim nip 0 do
dup bwidth 0 do
over i j rot b@ rgb>lum
over i j rot g!
loop
loop nip ;
: graymap>bitmap ( gmp -- bmp )
dup bdim bitmap
dup bdim nip 0 do
dup bwidth 0 do
over i j rot g@ lum>rgb
over i j rot b!
loop
loop nip ;
|
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.
|
#Fortran
|
Fortran
|
type scimage
integer, dimension(:,:), pointer :: channel
integer :: width, height
end type scimage
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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).
|
#CoffeeScript
|
CoffeeScript
|
# Generate hamming numbers in order. Hamming numbers have the
# property that they don't evenly divide any prime numbers outside
# a given set, such as [2, 3, 5].
generate_hamming_sequence = (primes, max_n) ->
# We use a lazy algorithm, only ever keeping N candidates
# in play, one for each of our seed primes. Let's say
# primes is [2,3,5]. Our virtual streams are these:
#
# hammings: 1,2,3,4,5,6,8,10,12,15,16,18,20,...
# hammings*2: 2,4,6,9.10,12,16,20,24,30,32,36,40...
# hammings*3: 3,6,9,12,15,18,24,30,36,45,...
# hammings*5: 5,10,15,20,25,30,40,50,...
#
# After encountering 40 for the last time, our candidates
# will be
# 50 = 2 * 25
# 45 = 3 * 15
# 50 = 5 * 10
# Then, after 45
# 50 = 2 * 25
# 48 = 3 * 16 <= new
# 50 = 5 * 10
hamming_numbers = [1]
candidates = ([p, p, 1] for p in primes)
last_number = 1
while hamming_numbers.length < max_n
# Get the next candidate Hamming Number tuple.
i = min_idx(candidates)
candidate = candidates[i]
[n, p, seq_idx] = candidate
# Add to sequence unless it's a duplicate.
if n > last_number
hamming_numbers.push n
last_number = n
# Replace the candidate with its successor (based on
# p = 2, 3, or 5).
#
# This is the heart of the algorithm. Let's say, over the
# primes [2,3,5], we encounter the hamming number 32 based on it being
# 2 * 16, where 16 is the 12th number in the sequence.
# We'll be passed in [32, 2, 12] as candidate, and
# hamming_numbers will be [1,2,3,4,5,6,8,9,10,12,16,18,...]
# by now. The next candidate we need to enqueue is
# [36, 2, 13], where the numbers mean this:
#
# 36 - next multiple of 2 of a Hamming number
# 2 - prime number
# 13 - 1-based index of 18 in the sequence
#
# When we encounter [36, 2, 13], we will then enqueue
# [40, 2, 14], based on 20 being the 14th hamming number.
q = hamming_numbers[seq_idx]
candidates[i] = [p*q, p, seq_idx+1]
hamming_numbers
min_idx = (arr) ->
# Don't waste your time reading this--it just returns
# the index of the smallest tuple in an array, respecting that
# the tuples may contain integers. (CS compiles to JS, which is
# kind of stupid about sorting. There are libraries to work around
# the limitation, but I wanted this code to be standalone.)
less_than = (tup1, tup2) ->
i = 0
while i < tup2.length
return true if tup1[i] <= tup2[i]
return false if tup1[i] > tup2[i]
i += 1
min_i = 0
for i in [1...arr.length]
if less_than arr[i], arr[min_i]
min_i = i
return min_i
primes = [2, 3, 5]
numbers = generate_hamming_sequence(primes, 10000)
console.log numbers[1690]
console.log numbers[9999]
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
(let ((number (1+ (random 10))))
(while (not (= (read-number "Guess the number ") number))
(message "Wrong, try again."))
(message "Well guessed! %d" number))
|
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
|
#Erlang
|
Erlang
|
% Implemented by Arjun Sunel
-module(guess_the_number).
-export([main/0]).
main() ->
io:format("Guess my number between 1 and 10 until you get it right:\n"),
N = random:uniform(10),
guess(N).
guess(N) ->
{ok, [K]} = io:fread("Guess number : ","~d"),
if
K=:=N ->
io:format("Well guessed!!\n");
true ->
guess(N)
end.
|
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.
|
#E
|
E
|
pragma.enable("accumulator")
def maxSubseq(seq) {
def size := seq.size()
# Collect all intervals of indexes whose values are positive
def intervals := {
var intervals := []
var first := 0
while (first < size) {
var next := first
def seeing := seq[first] > 0
while (next < size && (seq[next] > 0) == seeing) {
next += 1
}
if (seeing) { # record every positive interval
intervals with= first..!next
}
first := next
}
intervals
}
# For recording the best result found
var maxValue := 0
var maxInterval := 0..!0
# Try all subsequences beginning and ending with such intervals.
for firstIntervalIx => firstInterval in intervals {
for lastInterval in intervals(firstIntervalIx) {
def interval :=
(firstInterval.getOptStart())..!(lastInterval.getOptBound())
def value :=
accum 0 for i in interval { _ + seq[i] }
if (value > maxValue) {
maxValue := value
maxInterval := interval
}
}
}
return ["value" => maxValue,
"indexes" => maxInterval]
}
|
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)
|
#Common_Lisp
|
Common Lisp
|
(defun guess-the-number-feedback (&optional (min 1) (max 100))
(let ((num-guesses 0)
(num (+ (random (1+ (- max min))) min))
(guess nil))
(format t "Try to guess a number from ~:d to ~:d!~%" min max)
(loop do (format t "Guess? ")
(incf num-guesses)
(setf guess (read))
(format t "Your guess is ~[not a number.~;too small.~;too large.~;correct!~]~%"
(cond ((not (numberp guess)) 0)
((< guess num) 1)
((> guess num) 2)
((= guess num) 3)))
until (and (numberp guess)
(= guess num)))
(format t "You got the number correct on the ~:r guess!~%" num-guesses)))
|
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.
|
#Racket
|
Racket
|
#lang racket/gui
(require slideshow/pict)
(define-values (*width* *height*) (values 400 40))
(define (shades inc)
(for/list ([scale (in-range 0 (+ 1 inc) inc)])
(round (* 255 scale))))
(define (grays increment direction)
(define colors (shades increment))
(apply hc-append
((if (eq? direction 'right) identity reverse)
(for/list ([c colors])
(colorize (filled-rectangle
(/ *width* (length colors)) *height*)
(make-color c c c))))))
(vc-append (grays 1/8 'right) (grays 1/16 'left)
(grays 1/32 'right) (grays 1/64 'left))
|
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.
|
#Raku
|
Raku
|
my ($width,$height) = 1280,768;
my $PGM = open "Greyscale-bars-perl6.pgm", :w orelse die "Can't create Greyscale-bars-perl6.pgm: $_";
$PGM.print: qq:to/EOH/;
P2
# Greyscale-bars-perl6.pgm
$width $height
65535
EOH
my ($h1,$h2,$h3,$h4) = divvy($height,4);
my @nums = ((0/7,1/7...7/7) X* 65535)».floor;
my $line = ~(@nums Zxx divvy($width,8));
$PGM.say: $line for ^$h1;
@nums = ((15/15,14/15...0/15) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,16));
$PGM.say: $line for ^$h2;
@nums = ((0/31,1/31...31/31) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,32));
$PGM.say: $line for ^$h3;
@nums = ((63/63,62/63...0/63) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,64));
$PGM.say: $line for ^$h4;
$PGM.close;
sub divvy($all, $div) {
my @marks = ((1/$div,2/$div ... 1) X* $all)».round;
@marks Z- 0,|@marks;
}
|
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
|
#PARI.2FGP
|
PARI/GP
|
guessnumber2(b)={
my(c=0,d=b,a=0);
for(x=1,b,
for(y=1,b,
if(a<c||a==c||a==d||a>d,
a=random(b),
break()
)
);
print("I guess "a" am I h,l,or e ?");
g=input();
if(g==h,
d=a,
if(g==l,
c=a,
if(g==e,
break()
)
)
)
);
}
|
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
|
#E
|
E
|
def isHappyNumber(var x :int) {
var seen := [].asSet()
while (!seen.contains(x)) {
seen with= x
var sum := 0
while (x > 0) {
sum += (x % 10) ** 2
x //= 10
}
x := sum
if (x == 1) { return true }
}
return false
}
var count := 0
for x ? (isHappyNumber(x)) in (int >= 1) {
println(x)
if ((count += 1) >= 8) { break }
}
|
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.
|
#OCaml
|
OCaml
|
(* Preamble -- some math, and an "angle" type which might be part of a common library. *)
let pi = 4. *. atan 1.
let radians_of_degrees = ( *. ) (pi /. 180.)
let haversin theta = 0.5 *. (1. -. cos theta)
(* The angle type can track radians or degrees, which I'll use for automatic conversion. *)
type angle = Deg of float | Rad of float
let as_radians = function
| Deg d -> radians_of_degrees d
| Rad r -> r
(* Demonstrating use of a module, and record type. *)
module LatLong = struct
type t = { lat: float; lng: float }
let of_angles lat lng = { lat = as_radians lat; lng = as_radians lng }
let sub a b = { lat = a.lat-.b.lat; lng = a.lng-.b.lng }
let dist radius a b =
let d = sub b a in
let h = haversin d.lat +. haversin d.lng *. cos a.lat *. cos b.lat in
2. *. radius *. asin (sqrt h)
end
(* Now we can use the LatLong module to construct coordinates and calculate
* great-circle distances.
* NOTE radius and resulting distance are in the same measure, and units could
* be tracked for this too... but who uses miles? ;) *)
let earth_dist = LatLong.dist 6372.8
and bna = LatLong.of_angles (Deg 36.12) (Deg (-86.67))
and lax = LatLong.of_angles (Deg 33.94) (Deg (-118.4))
in
earth_dist bna 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
|
#GFA_Basic
|
GFA Basic
|
PRINT "Hello World"
|
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
|
#Phix
|
Phix
|
integer n = 0
sequence digits={0}
procedure nNiven()
while 1 do
n += 1
for i=length(digits) to 0 by -1 do
if i=0 then
digits = prepend(digits,1)
exit
end if
if digits[i]<9 then
digits[i] += 1
exit
end if
digits[i] = 0
end for
if remainder(n,sum(digits))=0 then exit end if
end while
end procedure
sequence s = {}
for i=1 to 20 do
nNiven()
s &= n
end for
?s
while n<=1000 do
nNiven()
end while
?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
|
#Jsish
|
Jsish
|
prompt$ jsish
Jsish interactive: see 'help [cmd]'. \ cancels > input. ctrl-c aborts running script.
# require('JsiAgarGUI')
1
# JsiAgarGUI.alert("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
|
#Julia
|
Julia
|
using Tk
window = Toplevel("Hello World", 200, 100, false)
pack_stop_propagate(window)
fr = Frame(window)
pack(fr, expand=true, fill="both")
txt = Label(fr, "Hello World")
pack(txt, expand=true)
set_visible(window, true)
# sleep(7)
|
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).
|
#Raku
|
Raku
|
use GTK::Simple;
use GTK::Simple::App;
my GTK::Simple::App $app .= new(title => 'GUI component interaction');
$app.set-content(
my $box = GTK::Simple::VBox.new(
my $value = GTK::Simple::Entry.new(text => '0'),
my $increment = GTK::Simple::Button.new(label => 'Increment'),
my $random = GTK::Simple::Button.new(label => 'Random'),
)
);
$app.size-request(400, 100);
$app.border-width = 20;
$box.spacing = 10;
$value.changed.tap: {
($value.text ||= '0') ~~ s:g/<-[0..9]>//;
}
$increment.clicked.tap: {
my $val = $value.text; $val += 1; $value.text = $val.Str
}
$random.clicked.tap: {
# Dirty hack to work around the fact that GTK::Simple doesn't provide
# access to GTK message dialogs yet :P
if run «zenity --question --text "Reset to random value?"» {
$value.text = (^100).pick.Str
}
}
$app.run;
|
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.
|
#AWK
|
AWK
|
# Tested using GAWK
function bits2str(bits, data, mask)
{
# Source: https://www.gnu.org/software/gawk/manual/html_node/Bitwise-Functions.html
if (bits == 0)
return "0"
mask = 1
for (; bits != 0; bits = rshift(bits, 1))
data = (and(bits, mask) ? "1" : "0") data
while ((length(data) % 8) != 0)
data = "0" data
return data
}
function gray_encode(n){
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
return xor(n,rshift(n,1))
}
function gray_decode(n){
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
mask = rshift(n,1)
while(mask != 0){
n = xor(n,mask)
mask = rshift(mask,1)
}
return n
}
BEGIN{
for (i=0; i < 32; i++)
printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i)))
}
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Aime
|
Aime
|
o_("-- ", sshell().plan("expr", "8", "*", "9").link.b_dump('\n'), " --\n");
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Amazing_Hopper
|
Amazing Hopper
|
/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Main
sys = `cat jm/sys1.jambo`
Set( sys ) Prnl
End
|
http://rosettacode.org/wiki/Get_system_command_output
|
Get system command output
|
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
|
#Applesoft_BASIC
|
Applesoft BASIC
|
100 HIMEM: 24576
110 LET A = 24576
120 LET P = 768
130 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256
140 DEF FN H(A) = INT (A / 256)
150 DEF FN L(A) = A - FN H(A) * 256
160 POKE P + 00,073: REM EOR
170 POKE P + 01,128: REM #$80
180 POKE P + 02,141: REM STA
190 POKE P + 03, FN L(A)
200 POKE P + 04, FN H(A)
210 POKE P + 05,073: REM EOR
220 POKE P + 06,128: REM #$80
230 POKE P + 07,238: REM INC
240 POKE P + 08, FN L(P + 3)
250 POKE P + 09, FN H(P + 3)
260 POKE P + 10,208: REM BNE
270 POKE P + 11,3
280 POKE P + 12,238: REM INC
290 POKE P + 13, FN L(P + 4)
300 POKE P + 14, FN H(P + 4)
310 POKE P + 15,096: REM RTS
320 POKE 54, FN L(P)
330 POKE 55, FN H(P)
340 CALL 1002
350 PRINT CHR$ (4)"CATALOG"
360 PRINT CHR$ (4)"PR#0"
370 LET C = - 1
380 LET I = 0
390 LET S = 0
400 LET E = FN P(P + 3)
410 DIM S$(54)
420 LET S$(0) = ""
430 POKE 236, PEEK (131)
440 POKE 237, PEEK (132)
450 LET S = FN P(236)
460 FOR I = A TO E STEP 255
470 LET C = C + 1
480 POKE S + C * 3,255
490 IF E - I < 255 THEN POKE S + C * 3,E - I
500 POKE S + C * 3 + 1, FN L(I)
510 POKE S + C * 3 + 2, FN H(I)
520 PRINT S$(C);
530 NEXT
|
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.
|
#ALGOL_W
|
ALGOL W
|
begin
% simple list type %
record IntList( integer val; reference(IntList) next );
% find the maximum element of an IntList, returns 0 for an empty list %
integer procedure maxElement( reference(IntList) value list ) ;
begin
integer maxValue;
reference(IntList) listPos;
maxValue := 0;
listPos := list;
if listPos not = null then begin
% non-empty list %
maxValue := val(listPos);
listPos := next(listPos);
while listPos not = null do begin
if val(listPos) > maxValue then maxValue := val(listPos);
listPos := next(listPos)
end while_listPos_ne_null ;
end if_listPos_ne_null ;
maxValue
end maxElement ;
% test the maxElement procedure %
write( maxElement( IntList( -767, IntList( 2397, IntList( 204, null ) ) ) ) )
end.
|
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.
|
#AArch64_Assembly
|
AArch64 Assembly
|
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program calPgcd64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Number 1 : @ number 2 : @ PGCD : @ \n"
szCarriageReturn: .asciz "\n"
szMessError: .asciz "Error PGCD !!\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,36
mov x21,18
mov x0,x20
mov x1,x21
bl calPGCDmod
bcs 99f // error ?
mov x2,x0 // pgcd
mov x0,x20
mov x1,x21
bl displayResult
mov x20,37
mov x21,15
mov x0,x20
mov x1,x21
bl calPGCDmod
bcs 99f // error ?
mov x2,x0 // pgcd
mov x0,x20
mov x1,x21
bl displayResult
b 100f
99: // display error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessError: .quad szMessError
/***************************************************/
/* Compute pgcd modulo use */
/***************************************************/
/* x0 contains first number */
/* x1 contains second number */
/* x0 return PGCD */
/* if error carry set to 1 */
calPGCDmod:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
cbz x0,99f // if = 0 error
cbz x1,99f
cmp x0,0
bgt 1f
neg x0,x0 // if negative inversion number 1
1:
cmp x1,0
bgt 2f
neg x1,x1 // if negative inversion number 2
2:
cmp x0,x1 // compare two numbers
bgt 3f
mov x2,x0 // inversion
mov x0,x1
mov x1,x2
3:
udiv x2,x0,x1 // division
msub x0,x2,x1,x0 // compute remainder
cmp x0,0
bgt 2b // loop
mov x0,x1
cmn x0,0 // clear carry
b 100f
99: // error
mov x0,0
cmp x0,0 // set carry
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/***************************************************/
/* display result */
/***************************************************/
/* x0 contains first number */
/* x1 contains second number */
/* x2 contains PGCD */
displayResult:
stp x1,lr,[sp,-16]! // save registres
mov x3,x1 // save x1
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
mov x4,x0 // save message address
mov x0,x3 // conversion second number
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
mov x0,x4 // move message address
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
mov x4,x0 // save message address
mov x0,x2 // conversion pgcd
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
mov x0,x4 // move message address
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
bl affichageMess // display message
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
|
#BASIC
|
BASIC
|
CONST matchtext = "Goodbye London!"
CONST repltext = "Hello New York!"
CONST matchlen = LEN(matchtext)
DIM L0 AS INTEGER, x AS INTEGER, filespec AS STRING, linein AS STRING
L0 = 1
WHILE LEN(COMMAND$(L0))
filespec = DIR$(COMMAND$(L0))
WHILE LEN(filespec)
OPEN filespec FOR BINARY AS 1
linein = SPACE$(LOF(1))
GET #1, 1, linein
DO
x = INSTR(linein, matchtext)
IF x THEN
linein = LEFT$(linein, x - 1) & repltext & MID$(linein, x + matchlen)
' If matchtext and repltext are of equal length (as in this example)
' then you can replace the above line with this:
' MID$(linein, x) = repltext
' This is somewhat more efficient than having to rebuild the string.
ELSE
EXIT DO
END IF
LOOP
' If matchtext and repltext are of equal length (as in this example), or repltext
' is longer than matchtext, you could just write back to the file while it's open
' in BINARY mode, like so:
' PUT #1, 1, linein
' But since there's no way to reduce the file size via BINARY and PUT, we do this:
CLOSE
OPEN filespec FOR OUTPUT AS 1
PRINT #1, linein;
CLOSE
filespec = DIR$
WEND
L0 += 1
WEND
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
FindThis$ = "Goodbye London!"
ReplaceWith$ = "Hello New York!"
DIM Files$(3)
Files$() = "C:\test1.txt", "C:\test2.txt", "C:\test3.txt", "C:\test4.txt"
FOR f% = 0 TO DIM(Files$(),1)
infile$ = Files$(f%)
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Failed to open file " + infile$
tmpfile$ = @tmp$+"replace.txt"
tmpfile% = OPENOUT(tmpfile$)
WHILE NOT EOF#infile%
INPUT #infile%, a$
IF ASCa$=10 a$ = MID$(a$,2)
l% = LEN(FindThis$)
REPEAT
here% = INSTR(a$, FindThis$)
IF here% a$ = LEFT$(a$,here%-1) + ReplaceWith$ + MID$(a$,here%+l%)
UNTIL here% = 0
PRINT #tmpfile%, a$ : BPUT #tmpfile%,10
ENDWHILE
CLOSE #infile%
CLOSE #tmpfile%
OSCLI "DEL """ + infile$ + """"
OSCLI "REN """ + tmpfile$ + """ """ + infile$ + """"
NEXT
END
|
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).
|
#ALGOL_60
|
ALGOL 60
|
begin
comment Hailstone sequence - Algol 60;
integer array collatz[1:400]; integer icollatz;
integer procedure mod(i,j); value i,j; integer i,j;
mod:=i-(i div j)*j;
integer procedure hailstone(num);
value num; integer num;
begin
integer i,n;
icollatz:=1; n:=num; i:=0;
collatz[icollatz]:=n;
for i:=i+1 while n notequal 1 do begin
if mod(n,2)=0 then n:=n div 2
else n:=(3*n)+1;
icollatz:=icollatz+1;
collatz[icollatz]:=n
end;
hailstone:=icollatz
end hailstone;
integer i,nn,ncollatz,count,nlongest,nel,nelcur,nnn;
nn:=27;
ncollatz:=hailstone(nn);
outstring(1,"sequence for"); outinteger(1,nn); outstring(1," :\n");
for i:=1 step 1 until ncollatz do outinteger(1,collatz[i]);
outstring(1,"\n");
outstring(1,"number of elements:"); outinteger(1,ncollatz);
outstring(1,"\n\n");
nlongest:=0; nel:=0; nnn:=100000;
for count:=1, count+1 while count<nnn do begin
nelcur:=hailstone(count);
if nelcur>nel then begin
nel:=nelcur;
nlongest:=count
end
end;
outstring(1,"number <"); outinteger(1,nnn);
outstring(1,"with the longest sequence:"); outinteger(1,nlongest);
outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
outstring(1,"\n")
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.
|
#zkl
|
zkl
|
fcn colorGraph(nodeStr){ // "0-1 1-2 2-0 3"
numEdges,graph := 0,Dictionary(); // ( 0:(1,2), 1:L(0,2), 2:(1,0), 3:() )
foreach n in (nodeStr.split(" ")){ // parse string to graph
n=n - " ";
if(n.holds("-")){
a,b := n.split("-"); // keep as string
graph.appendV(a,b); graph.appendV(b,a);
numEdges+=1;
}
else graph[n]=T; // island
}
colors,colorPool := Dictionary(), ["A".."Z"].walk();
graph.pump(Void,'wrap([(node,nbrs)]){ // ( "1",(0,2), "3",() )
clrs:=colorPool.copy(); // all colors are available, then remove neighbours
foreach i in (nbrs){ clrs.remove(colors.find(i)) } // if nbr has color, color not available
colors[node] = clrs[0]; // first available remaining color
});
return(graph,colors,numEdges)
}
|
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.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
Dim As Integer ancho = 143, alto = 188, x, y, p, red, green, blue, luminancia
Dim As String imagen = "Mona_Lisa.bmp"
Screenres ancho,alto,32
Bload imagen
For x = 0 To ancho-1
For y = 0 To alto-1
p = Point(x,y)
red = p Mod 256
p = p \ 256
green = p Mod 256
p = p \ 256
blue = p Mod 256
luminancia = 0.2126*red + 0.7152*green + 0.0722*blue
Pset(x,y), Rgb(luminancia,luminancia,luminancia)
Next y
Next x
Bsave "Grey_"+imagen+".bmp",0
Sleep
|
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.
|
#FreeBASIC
|
FreeBASIC
|
Dim As Integer ancho = 143, alto = 188, x, y, p, red, green, blue, luminancia
Dim As String imagen = "Mona_Lisa.bmp"
Screenres ancho,alto,32
Bload imagen
For x = 0 To ancho-1
For y = 0 To alto-1
p = Point(x,y)
red = p Mod 256
p = p \ 256
green = p Mod 256
p = p \ 256
blue = p Mod 256
luminancia = 0.2126*red + 0.7152*green + 0.0722*blue
Pset(x,y), Rgb(luminancia,luminancia,luminancia)
Next y
Next x
Bsave "Grey_"+imagen+".bmp",0
Sleep
|
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
|
#J
|
J
|
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH !!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
}
|
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).
|
#Common_Lisp
|
Common Lisp
|
(defun next-hamm (factors seqs)
(let ((x (apply #'min (map 'list #'first seqs))))
(loop for s in seqs
for f in factors
for i from 0
with add = t do
(if (= x (first s)) (pop s))
;; prevent a value from being added to multiple lists
(when add
(setf (elt seqs i) (nconc s (list (* x f))))
(if (zerop (mod x f)) (setf add nil)))
finally (return x))))
(loop with factors = '(2 3 5)
with seqs = (loop for i in factors collect '(1))
for n from 1 to 1000001 do
(let ((x (next-hamm factors seqs)))
(if (or (< n 21)
(= n 1691)
(= n 1000000)) (format t "~d: ~d~%" n x))))
|
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
|
#ERRE
|
ERRE
|
PROGRAM GUESS_NUMBER
!
! for rosettacode.org
!
BEGIN
RANDOMIZE(TIMER)
N=0
R=INT(RND(1)*100+1) ! RND function gives a random number from 0 to 1
G=0
C$=""
WHILE G<>R DO
INPUT("Pick a number between 1 and 100";G)
IF G=R THEN
PRINT("You got it!")
N+=1
PRINT("It took";N;"tries to pick the right Number.")
ELSIF G<R THEN
PRINT("Try a larger number.")
N+=1
ELSE
PRINT("Try a smaller number.")
N+=1
END IF
END WHILE
END PROGRAM
|
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
|
#Euphoria
|
Euphoria
|
include get.e
integer n,g
n = rand(10)
puts(1,"I have thought of a number from 1 to 10.\n")
puts(1,"Try to guess it!\n")
while 1 do
g = prompt_number("Enter your guess: ",{1,10})
if n = g then
exit
end if
puts(1,"Your guess was wrong. Try again!\n")
end while
puts(1,"Well done! You guessed it.")
|
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.
|
#EchoLisp
|
EchoLisp
|
(lib 'struct)
(struct result (score starter))
;; the score of i in sequence ( .. i j ...) is max (i , i + score (j))
;; to compute score of (a b .. x y z) :
;; start with score(z) and compute scores of y , z , ..c, b , a.
;; this is O(n)
;; return value of sub-sequence
(define (max-max L into: result)
(define value
(if
(empty? L) -Infinity
(max (first L) (+ (first L) (max-max (cdr L) result )))))
(when (> value (result-score result))
(set-result-score! result value) ;; remember best score
(set-result-starter! result L)) ;; and its location
value)
;; return (best-score (best sequence))
(define (max-seq L)
(define best (result -Infinity null))
(max-max L into: best)
(define score (result-score best))
(list score
(for/list (( n (result-starter best)))
#:break (zero? score)
(set! score (- score n))
n)))
(define L '(-1 -2 3 5 6 -2 -1 4 -4 2 -1))
(max-seq L)
→ (15 (3 5 6 -2 -1 4))
|
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)
|
#Crystal
|
Crystal
|
number = rand(1..10)
puts "Guess the number between 1 and 10"
loop do
begin
user_number = gets.to_s.to_i
if user_number == number
puts "You guessed it."
break
elsif user_number > number
puts "Too high."
else
puts "Too low."
end
rescue ArgumentError
puts "Please enter an integer."
end
end
|
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.
|
#RapidQ
|
RapidQ
|
Declare Sub PaintCanvas
Create Form as Qform
Caption = "Rosetta Greyscale"
Center
create Canv as QCanvas
align = 5
onPaint = PaintCanvas
end create
end create
Sub PaintCanvas
NumRows = 4 'Change for number of rows
for curbar = 0 to NumRows-1
Bars = 2^(curbar+3)
for x = 0 to (Bars -1)
x1=Canv.Width/Bars*x
y1=Canv.Height/NumRows*CurBar
x2=Canv.Width/Bars*(x+1)
y2=Canv.Height/NumRows*(CurBar+1)
c=(255/(Bars-1))*x
c=iif(curbar mod 2, 255-c, c)
Canv.FillRect(x1, y1, x2, y2, rgb(c, c, c))
next x
next curbar
end sub
Form.showmodal
|
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.
|
#Ring
|
Ring
|
# Project : Greyscale bars/Display
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Greyscale bars/Display")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
for row=1 to 4
n=pow(2,(row+2))
w=1280/n
py=256*(4-row)
for b=0 to n-1
g=floor(255*b/(n-1))
if n=16 or n=64
g=255-g
ok
color2 = new qcolor()
color2.setrgb(g,g,g,255)
mybrush = new qbrush() {setstyle(1) setcolor(color2)}
paint.setbrush(mybrush)
paint.drawrect(w*b,py,w,256)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
|
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.
|
#Run_BASIC
|
Run BASIC
|
for i = 1 to 4
incr = int(256 / (i * 8))
c = 256
html "<table style='width: 200px; height: 11px;' border=0 cellpadding=0 cellspacing=0><tr>"
for j = 1 to i * 8
html "<td style='background-color: rgb(";c;",";c;",";c;");'></td>"
c = c - incr
next j
html "</tr>"
next i
html "</table>"
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
|
#Pascal
|
Pascal
|
Program GuessIt(input, output);
var
done, ok: boolean;
guess, upp, low: integer;
res: char;
begin
writeln ('Choose a number between 0 and 1000.');
write ('Press Enter and I will start to guess the number.');
readln;
upp := 1000;
low := 0;
repeat
ok := false;
guess := ( ( upp - low ) div 2 ) + low;
write ('My guess is: ', guess:4);
write ('. How did i score? ''l'' = too low, ''h'' = too high, ''c'' = correct : ');
repeat
readln (res);
res := lowercase(res);
until (res = 'c') or (res = 'l') or (res = 'h');
case res of
'l': low := guess;
'h': upp := guess;
else
ok := true
end;
until ok;
writeln ('So the number is: ', guess:4);
writeln ('It was nice to play with you.');
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
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
l_val: INTEGER
do
from
l_val := 1
until
l_val > 100
loop
if is_happy_number (l_val) then
print (l_val.out)
print ("%N")
end
l_val := l_val + 1
end
end
feature -- Happy number
is_happy_number (a_number: INTEGER): BOOLEAN
-- Is `a_number' a happy number?
require
positive_number: a_number > 0
local
l_number: INTEGER
l_set: ARRAYED_SET [INTEGER]
do
from
l_number := a_number
create l_set.make (10)
until
l_number = 1 or l_set.has (l_number)
loop
l_set.put (l_number)
l_number := square_sum_of_digits (l_number)
end
Result := (l_number = 1)
end
feature{NONE} -- Implementation
square_sum_of_digits (a_number: INTEGER): INTEGER
-- Sum of the sqares of digits of `a_number'.
require
positive_number: a_number > 0
local
l_number, l_digit: INTEGER
do
from
l_number := a_number
until
l_number = 0
loop
l_digit := l_number \\ 10
Result := Result + l_digit * l_digit
l_number := l_number // 10
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.