task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#ActionScript
|
ActionScript
|
function sumOfSquares(n:uint)
{
var sum:uint = 0;
while(n != 0)
{
sum += (n%10)*(n%10);
n /= 10;
}
return sum;
}
function isInArray(n:uint, array:Array)
{
for(var k = 0; k < array.length; k++)
if(n == array[k]) return true;
return false;
}
function isHappy(n)
{
var sequence:Array = new Array();
while(n != 1)
{
sequence.push(n);
n = sumOfSquares(n);
if(isInArray(n,sequence))return false;
}
return true;
}
function printHappy()
{
var numbersLeft:uint = 8;
var numberToTest:uint = 1;
while(numbersLeft != 0)
{
if(isHappy(numberToTest))
{
trace(numberToTest);
numbersLeft--;
}
numberToTest++;
}
}
printHappy();
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Raku
|
Raku
|
signal(SIGINT).tap: {
note "Took { now - INIT now } seconds.";
exit;
}
for 0, 1, *+* ... * {
sleep 0.5;
.say;
}
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#REXX
|
REXX
|
/*REXX program displays integers until a Ctrl─C is pressed, then shows the number of */
/*────────────────────────────────── seconds that have elapsed since start of execution.*/
call time 'Reset' /*reset the REXX elapsed timer. */
signal on halt /*HALT: signaled via a Ctrl─C in DOS.*/
do j=1 /*start with unity and go ye forth. */
say right(j,20) /*display the integer right-justified. */
t=time('E') /*get the REXX elapsed time in seconds.*/
do forever; u=time('Elapsed') /* " " " " " " " */
if u<t | u>t+.5 then iterate j /* ◄═══ passed midnight or ½ second. */
end /*forever*/
end /*j*/
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
/*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#Sidef
|
Sidef
|
func hashJoin(table1, index1, table2, index2) {
var a = []
var h = Hash()
# hash phase
table1.each { |s|
h{s[index1]} := [] << s
}
# join phase
table2.each { |r|
a += h{r[index2]}.map{[_,r]}
}
return a
}
var t1 = [[27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]]
var t2 = [["Jonah", "Whales"],
["Jonah", "Spiders"],
["Alan", "Ghosts"],
["Alan", "Zombies"],
["Glory", "Buffy"]]
hashJoin(t1, 1, t2, 0).each { .say }
|
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.
|
#D
|
D
|
import std.stdio, std.math;
real haversineDistance(in real dth1, in real dph1,
in real dth2, in real dph2)
pure nothrow @nogc {
enum real R = 6371;
enum real TO_RAD = PI / 180;
alias imr = immutable real;
imr ph1d = dph1 - dph2;
imr ph1 = ph1d * TO_RAD;
imr th1 = dth1 * TO_RAD;
imr th2 = dth2 * TO_RAD;
imr dz = th1.sin - th2.sin;
imr dx = ph1.cos * th1.cos - th2.cos;
imr dy = ph1.sin * th1.cos;
return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) / 2) * 2 * R;
}
void main() {
writefln("Haversine distance: %.1f km",
haversineDistance(36.12, -86.67, 33.94, -118.4));
}
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Limbo
|
Limbo
|
implement HelloWorld;
include "sys.m"; sys: Sys;
include "draw.m";
HelloWorld: module {
init: fn(nil: ref Draw->Context, nil: list of string);
};
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
sys->print("Goodbye, World!"); # No automatic newline.
}
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#LLVM
|
LLVM
|
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
$"OUTPUT_STR" = comdat any
@"OUTPUT_STR" = linkonce_odr unnamed_addr constant [16 x i8] c"Goodbye, World!\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
define i32 @main() {
%1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"OUTPUT_STR", i32 0, i32 0))
ret i32 0
}
|
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
|
#Emacs_Lisp
|
Emacs Lisp
|
(message "Hello world!")
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#LiveCode
|
LiveCode
|
put "a,b,c" into list1
put 10,20,30 into list2
split list1 using comma
split list2 using comma
repeat with i=1 to the number of elements of list1
put list2[i] into list3[list1[i]]
end repeat
combine list3 using comma and colon
put list3
-- ouput
-- a:10,b:20,c:30
|
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
|
#F.23
|
F#
|
let divides d n =
match bigint.DivRem(n, d) with
| (_, rest) -> rest = 0I
let splitToInt (str:string) = List.init str.Length (fun i -> ((int str.[i]) - (int "0".[0])))
let harshads =
let rec loop n = seq {
let sum = List.fold (+) 0 (splitToInt (n.ToString()))
if divides (bigint sum) n then yield n
yield! loop (n + 1I)
}
loop 1I
[<EntryPoint>]
let main argv =
for h in (Seq.take 20 harshads) do printf "%A " h
printfn ""
printfn "%A" (Seq.find (fun n -> n > 1000I) harshads)
0
|
http://rosettacode.org/wiki/Hello_world/Newbie
|
Hello world/Newbie
|
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in installing software for the platform.
Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).
Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).
Remember to state where to view the output.
If particular IDE's or editors are required that are not standard, then point to/explain their installation too.
Note:
If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.
You may use sub-headings if giving instructions for multiple platforms.
|
#zkl
|
zkl
|
Extract to ~
Open a termninal
|
http://rosettacode.org/wiki/Hello_world/Newbie
|
Hello world/Newbie
|
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in installing software for the platform.
Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).
Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).
Remember to state where to view the output.
If particular IDE's or editors are required that are not standard, then point to/explain their installation too.
Note:
If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.
You may use sub-headings if giving instructions for multiple platforms.
|
#Zoomscript
|
Zoomscript
|
10 PRINT "Hello"
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#PureBasic
|
PureBasic
|
If OpenWindow(0, 0, 0, 5, 5, "", #PB_Window_Maximize + #PB_Window_Invisible)
maxX = WindowWidth(0)
maxY = WindowHeight(0)
CloseWindow(0)
MessageRequester("Result", "Maximum Window Width: " + Str(maxX) + ", Maximum Window Height: " + Str(maxY))
EndIf
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Python
|
Python
|
#!/usr/bin/env python3
import tkinter as tk # import the module.
root = tk.Tk() # Create an instance of the class.
root.state('zoomed') # Maximized the window.
root.update_idletasks() # Update the display.
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack() # add a label and set the size to text.
root.mainloop()
|
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
|
#C.2B.2B.2FCLI
|
C++/CLI
|
using namespace System::Windows::Forms;
int main(array<System::String^> ^args)
{
MessageBox::Show("Goodbye, World!", "Rosetta Code");
return 0;
}
|
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.
|
#BBC_BASIC
|
BBC BASIC
|
INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
ES_NUMBER = 8192
form% = FN_newdialog("Rosetta Code", 100, 100, 100, 52, 8, 1000)
idInc% = FN_setproc(PROCinc)
idDec% = FN_setproc(PROCdec)
PROC_static(form%, "Value:", 100, 10, 10, 24, 14, 0)
PROC_editbox(form%, "0", 101, 40, 8, 52, 14, ES_NUMBER)
PROC_pushbutton(form%, "Increment", idInc%, 7, 30, 40, 16, 0)
PROC_pushbutton(form%, "Decrement", idDec%, 52, 30, 40, 16, 0)
PROC_showdialog(form%)
REPEAT
WAIT 1
SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
SYS "GetDlgItem", !form%, 101 TO hedit%
SYS "EnableWindow", hedit%, number% = 0
SYS "GetDlgItem", !form%, idInc% TO hinc%
SYS "EnableWindow", hinc%, number% < 10
SYS "GetDlgItem", !form%, idDec% TO hdec%
SYS "EnableWindow", hdec%, number% > 0
UNTIL !form% = 0
QUIT
DEF PROCinc
LOCAL number%
SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
SYS "SetDlgItemInt", !form%, 101, number% + 1, 1
ENDPROC
DEF PROCdec
LOCAL number%
SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
SYS "SetDlgItemInt", !form%, 101, number% - 1, 1
ENDPROC
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
procedure Test_Happy_Digits is
function Is_Happy (N : Positive) return Boolean is
package Sets_Of_Positive is new Ada.Containers.Ordered_Sets (Positive);
use Sets_Of_Positive;
function Next (N : Positive) return Natural is
Sum : Natural := 0;
Accum : Natural := N;
begin
while Accum > 0 loop
Sum := Sum + (Accum mod 10) ** 2;
Accum := Accum / 10;
end loop;
return Sum;
end Next;
Current : Positive := N;
Visited : Set;
begin
loop
if Current = 1 then
return True;
elsif Visited.Contains (Current) then
return False;
else
Visited.Insert (Current);
Current := Next (Current);
end if;
end loop;
end Is_Happy;
Found : Natural := 0;
begin
for N in Positive'Range loop
if Is_Happy (N) then
Put (Integer'Image (N));
Found := Found + 1;
exit when Found = 8;
end if;
end loop;
end Test_Happy_Digits;
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Ruby
|
Ruby
|
t1 = Time.now
catch :done do
Signal.trap('INT') do
Signal.trap('INT', 'DEFAULT') # reset to default
throw :done
end
n = 0
loop do
sleep(0.5)
n += 1
puts n
end
end
tdelt = Time.now - t1
puts 'Program has run for %5.3f seconds.' % tdelt
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Rust
|
Rust
|
#[cfg(unix)]
fn main() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use libc::{sighandler_t, SIGINT};
// The time between ticks of our counter.
let duration = Duration::from_secs(1) / 2;
// "SIGINT received" global variable.
static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);
unsafe {
// Initially, "SIGINT received" is false.
GOT_SIGINT.store(false, Ordering::Release);
// Interrupt handler that handles the SIGINT signal
unsafe fn handle_sigint() {
// It is dangerous to perform any system calls in interrupts, so just set the atomic
// "SIGINT received" global to true when it arrives.
GOT_SIGINT.store(true, Ordering::Release);
}
// Make handle_sigint the signal handler for SIGINT.
libc::signal(SIGINT, handle_sigint as sighandler_t);
}
// Get the start time...
let start = Instant::now();
// Integer counter
let mut i = 0u32;
// Every `duration`...
loop {
thread::sleep(duration);
// Break if SIGINT was handled
if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
break;
}
// Otherwise, increment and display the integer and continue the loop.
i += 1;
println!("{}", i);
}
// Get the elapsed time.
let elapsed = start.elapsed();
// Print the difference and exit
println!("Program has run for {} seconds", elapsed.as_secs());
}
#[cfg(not(unix))]
fn main() {
println!("Not supported on this platform");
}
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Scala
|
Scala
|
import sun.misc.Signal
import sun.misc.SignalHandler
object SignalHandl extends App {
val start = System.nanoTime()
var counter = 0
Signal.handle(new Signal("INT"), new SignalHandler() {
def handle(sig: Signal) {
println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n")
exit(0)
}
})
while (true) {
counter += 1
println(counter)
Thread.sleep(500)
}
}
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#SQL
|
SQL
|
-- setting up the test data
CREATE TABLE people (age NUMBER(3), name varchar2(30));
INSERT INTO people (age, name)
SELECT 27, 'Jonah' FROM dual UNION ALL
SELECT 18, 'Alan' FROM dual UNION ALL
SELECT 28, 'Glory' FROM dual UNION ALL
SELECT 18, 'Popeye' FROM dual UNION ALL
SELECT 28, 'Alan' FROM dual
;
CREATE TABLE nemesises (name varchar2(30), nemesis varchar2(30));
INSERT INTO nemesises (name, nemesis)
SELECT 'Jonah', 'Whales' FROM dual UNION ALL
SELECT 'Jonah', 'Spiders' FROM dual UNION ALL
SELECT 'Alan' , 'Ghosts' FROM dual UNION ALL
SELECT 'Alan' , 'Zombies' FROM dual UNION ALL
SELECT 'Glory', 'Buffy' FROM dual
;
|
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.
|
#Dart
|
Dart
|
import 'dart:math';
class Haversine {
static final R = 6372.8; // In kilometers
static double haversine(double lat1, lon1, lat2, lon2) {
double dLat = _toRadians(lat2 - lat1);
double dLon = _toRadians(lon2 - lon1);
lat1 = _toRadians(lat1);
lat2 = _toRadians(lat2);
double a = pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(lat1) * cos(lat2);
double c = 2 * asin(sqrt(a));
return R * c;
}
static double _toRadians(double degree) {
return degree * pi / 180;
}
static void main() {
print(haversine(36.12, -86.67, 33.94, -118.40));
}
}
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Logtalk
|
Logtalk
|
:- object(error_message).
% the initialization/1 directive argument is automatically executed
% when the object is compiled loaded into memory:
:- initialization(write('Goodbye, World!')).
:- end_object.
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Lua
|
Lua
|
io.write("Goodbye, World!")
|
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
|
#Emojicode
|
Emojicode
|
🏁 🍇
😀 🔤Hello world!🔤
🍉
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Lua
|
Lua
|
function(keys,values)
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module CheckAll {
Module CheckVectorType {
Dim Keys$(4), Values(4)
Keys$(0):= "one","two","three","four"
Values(0):=1,2,3,4
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values(i)
}
Print Dict("one")+Dict("four")=Dict("two")+Dict("three") ' true
}
Module CheckVectorType1 {
Dim Keys$(4), Values$(4)
Keys$(0):= "one","two","three","four"
Values$(0):="*","**","***","****"
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values$(i)
}
Print Dict$("one")+Dict$("four")=Dict$("two")+Dict$("three") ' true
}
CheckVectorType
CheckVectorType1
}
CheckAll
|
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
|
#Factor
|
Factor
|
USING: math.text.utils lists lists.lazy ;
: niven? ( n -- ? ) dup 1 digit-groups sum mod 0 = ;
: first-n-niven ( n -- seq )
1 lfrom [ niven? ] lfilter ltake list>array ;
: next-niven ( n -- m ) 1 + [ dup niven? ] [ 1 + ] until ;
20 first-n-niven .
1000 next-niven .
|
http://rosettacode.org/wiki/Hello_world/Newbie
|
Hello world/Newbie
|
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in installing software for the platform.
Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).
Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).
Remember to state where to view the output.
If particular IDE's or editors are required that are not standard, then point to/explain their installation too.
Note:
If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.
You may use sub-headings if giving instructions for multiple platforms.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 PRINT "Hello"
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Racket
|
Racket
|
#lang racket/gui
(define-values [W H]
(let ([f (new frame% [label "test"])])
(begin0 (send* f (maximize #t) (show #t) (get-client-size))
(send f show #f))))
(printf "~ax~a\n" W H)
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Raku
|
Raku
|
use X11::libxdo;
my $xdo = Xdo.new;
my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );
say "Desktop viewport dimensions: (maximum-fullscreen size) $dw x $dh";
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#REXX
|
REXX
|
load "guilib.ring"
new qApp {
win1 = new qWidget() {
new qPushButton(win1) {
resize(200,200)
settext("Info")
setclickevent(' win1{ setwindowtitle("Width: " + width() + " Height : " + height() ) }')
}
showMaximized()}
exec()
}
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Ring
|
Ring
|
load "guilib.ring"
new qApp {
win1 = new qWidget() {
new qPushButton(win1) {
resize(200,200)
settext("Info")
setclickevent(' win1{ setwindowtitle("Width: " + width() + " Height : " + height() ) }')
}
showMaximized()}
exec()
}
|
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
|
#Casio_BASIC
|
Casio BASIC
|
ViewWindow 1,127,1,1,63,1
AxesOff
CoordOff
GridOff
LabelOff
|
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.
|
#C
|
C
|
file main.c
|
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
|
#ALGOL_68
|
ALGOL 68
|
INT base10 = 10, num happy = 8;
PROC next = (INT in n)INT: (
INT n := in n;
INT out := 0;
WHILE n NE 0 DO
out +:= ( n MOD base10 ) ** 2;
n := n OVER base10
OD;
out
);
PROC is happy = (INT in n)BOOL: (
INT n := in n;
FOR i WHILE n NE 1 AND n NE 4 DO n := next(n) OD;
n=1
);
INT count := 0;
FOR i WHILE count NE num happy DO
IF is happy(i) THEN
count +:= 1;
print((i, new line))
FI
OD
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Sidef
|
Sidef
|
var start = Time.sec;
Sig.INT { |_|
Sys.say("Ran for #{Time.sec - start} seconds.");
Sys.exit;
}
{ |i|
Sys.say(i);
Sys.sleep(0.5);
} * Math.inf;
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Smalltalk
|
Smalltalk
|
|n|
n := 0.
UserInterrupt
catch:[
[true] whileTrue:[
n := n + 1.
n printCR.
Delay waitForSeconds: 0.5.
]
]
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#Swift
|
Swift
|
func hashJoin<A, B, K: Hashable>(_ first: [(K, A)], _ second: [(K, B)]) -> [(A, K, B)] {
var map = [K: [B]]()
for (key, val) in second {
map[key, default: []].append(val)
}
var res = [(A, K, B)]()
for (key, val) in first {
guard let vals = map[key] else {
continue
}
res += vals.map({ (val, key, $0) })
}
return res
}
let t1 = [
("Jonah", 27),
("Alan", 18),
("Glory", 28),
("Popeye", 18),
("Alan", 28)
]
let t2 = [
("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")
]
print("Age | Character Name | Nemesis")
print("----|----------------|--------")
for (age, name, nemesis) in hashJoin(t1, t2) {
print("\(age) | \(name) | \(nemesis)")
}
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#Tcl
|
Tcl
|
package require Tcl 8.6
# Only for lmap, which can be replaced with foreach
proc joinTables {tableA a tableB b} {
# Optimisation: if the first table is longer, do in reverse order
if {[llength $tableB] < [llength $tableA]} {
return [lmap pair [joinTables $tableB $b $tableA $a] {
lreverse $pair
}]
}
foreach value $tableA {
lappend hashmap([lindex $value $a]) [lreplace $value $a $a]
#dict version# dict lappend hashmap [lindex $value $a] [lreplace $value $a $a]
}
set result {}
foreach value $tableB {
set key [lindex $value $b]
if {![info exists hashmap($key)]} continue
#dict version# if {![dict exists $hashmap $key]} continue
foreach first $hashmap($key) {
#dict version# foreach first [dict get $hashmap $key]
lappend result [list {*}$first $key {*}[lreplace $value $b $b]]
}
}
return $result
}
set tableA {
{27 "Jonah"} {18 "Alan"} {28 "Glory"} {18 "Popeye"} {28 "Alan"}
}
set tableB {
{"Jonah" "Whales"} {"Jonah" "Spiders"} {"Alan" "Ghosts"} {"Alan" "Zombies"}
{"Glory" "Buffy"}
}
set joined [joinTables $tableA 1 $tableB 0]
foreach row $joined {
puts $row
}
|
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.
|
#Delphi
|
Delphi
|
program HaversineDemo;
uses Math;
function HaversineDist(th1, ph1, th2, ph2:double):double;
const diameter = 2 * 6372.8;
var dx, dy, dz:double;
begin
ph1 := degtorad(ph1 - ph2);
th1 := degtorad(th1);
th2 := degtorad(th2);
dz := sin(th1) - sin(th2);
dx := cos(ph1) * cos(th1) - cos(th2);
dy := sin(ph1) * cos(th1);
Result := arcsin(sqrt(sqr(dx) + sqr(dy) + sqr(dz)) / 2) * diameter;
end;
begin
Writeln('Haversine distance: ', HaversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#m4
|
m4
|
`Goodbye, World!'dnl
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#MANOOL
|
MANOOL
|
{{extern "manool.org.18/std/0.3/all"} in Out.Write["Goodbye, World!"]}
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Maple
|
Maple
|
printf( "Goodbye, World!" );
|
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
|
#Erlang
|
Erlang
|
io:format("Hello world!~n").
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Maple
|
Maple
|
A := [1, 2, 3];
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
?? Hash
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three
|
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
|
#FBSL
|
FBSL
|
#APPTYPE CONSOLE
CLASS harshad
PRIVATE:
memo[]
SUB INITIALIZE()
DIM i = 1, c
DO
IF isNiven(i) THEN
c = c + 1
memo[c] = i
END IF
i = i + 1
IF c = 20 THEN EXIT DO
LOOP
memo[] = "..."
i = 1000
WHILE NOT isNiven(INCR(i)): WEND
memo[] = i
END SUB
FUNCTION isNiven(n)
RETURN NOT (n MOD sumdigits(n))
END FUNCTION
FUNCTION sumdigits(n)
DIM num = n, m, sum
WHILE num
sum = sum + num MOD 10
num = num \ 10
WEND
RETURN sum
END FUNCTION
PUBLIC:
METHOD Yield()
FOREACH DIM e IN memo
PRINT e, " ";
NEXT
END METHOD
END CLASS
DIM niven AS NEW harshad
niven.Yield()
PAUSE
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Run_BASIC
|
Run BASIC
|
html "<INPUT TYPE='HIDDEN' id='winHigh' name='winHigh' VALUE='";winHigh;"'></input>"
html "<INPUT TYPE='HIDDEN' id='winWide' name='winWide' VALUE='";winWide;"'></input>"
html "<script>
<!--
function winSize()
{
var myWide = 0, myHigh = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWide = window.innerWidth;
myHigh = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWide = document.documentElement.clientWidth;
myHigh = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWide = document.body.clientWidth;
myHigh = document.body.clientHeight;
}
// window.alert( 'Width = ' + myWide + ' Height = ' + myHigh );
document.getElementById('winHigh').value = myHigh;
document.getElementById('winWide').value = myWide;
}
window.onresize = function()
{
var x = winSize();
}
var x = winSize();
//--></script>
"
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Scala
|
Scala
|
import java.awt.{Dimension, Insets, Toolkit}
import javax.swing.JFrame
class MaxWindowDims() extends JFrame {
val toolkit: Toolkit = Toolkit.getDefaultToolkit
val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration), toolkit.getScreenSize)
println("Physical screen size: " + screenSize)
System.out.println("Insets: " + insets0)
screenSize.width -= (insets0.left + insets0.right)
screenSize.height -= (insets0.top + insets0.bottom)
System.out.println("Max available: " + screenSize)
}
object MaxWindowDims {
def main(args: Array[String]): Unit = {
new MaxWindowDims
}
}
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Sidef
|
Sidef
|
require('Tk')
func max_window_size() -> (Number, Number) {
%s'MainWindow'.new.maxsize;
}
var (width, height) = max_window_size();
say (width, 'x', height);
|
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
|
#Clean
|
Clean
|
import StdEnv, StdIO
Start :: *World -> *World
Start world = startIO NDI Void (snd o openDialog undef hello) [] world
where
hello = Dialog "" (TextControl "Goodbye, World!" [])
[WindowClose (noLS closeProcess)]
|
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.
|
#C.23
|
C#
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
class RosettaInteractionForm : Form
{
// Model used for DataBinding.
// Notifies bound controls about Value changes.
class NumberModel: INotifyPropertyChanged
{
// initialize event with empty delegate to avoid checks on null
public event PropertyChangedEventHandler PropertyChanged = delegate {};
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
// Notify bound control about value change
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
//MaskedTextBox is a TextBox variety with built-in input validation
var tbNumber = new MaskedTextBox
{
Mask="0000", // allow 4 decimal digits only
ResetOnSpace = false, // don't enter spaces
Dock = DockStyle.Top // place at the top of form
};
// bound TextBox.Text to NumberModel.Value;
tbNumber.DataBindings.Add("Text", model, "Value");
var enabledIfZero = new Binding("Enabled", model, "Value");
EnableControlWhen(tbNumber, value => value == 0);
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
EnableControlWhen(btIncrement, value => value < 10);
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
EnableControlWhen(btDecrement, value => value > 0);
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
}
// common part of creating bindings for Enabled property
void EnableControlWhen(Control ctrl, Func<int, bool> predicate)
{
// bind Control.Enabled to NumberModel.Value
var enabledBinding = new Binding("Enabled", model, "Value");
// Format event is called when model value should be converted to Control value.
enabledBinding.Format += (sender, args) =>
{
// Enabled property is of bool type.
if (args.DesiredType != typeof(bool)) return;
// set resulting value by applying condition
args.Value = predicate((int)args.Value);
};
// as a result, control will be enabled if predicate returns true
ctrl.DataBindings.Add(enabledBinding);
}
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}
|
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
|
#ALGOL-M
|
ALGOL-M
|
begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;
integer function sumdgtsq(n);
integer n;
sumdgtsq :=
if n = 0 then 0
else mod(n,10)*mod(n,10) + sumdgtsq(n/10);
integer function happy(n);
integer n;
begin
integer i;
integer array seen[0:200];
for i := 0 step 1 until 200 do seen[i] := 0;
while seen[n] = 0 do
begin
seen[n] := 1;
n := sumdgtsq(n);
end;
happy := if n = 1 then 1 else 0;
end;
integer i, n;
i := n := 0;
while n < 8 do
begin
if happy(i) = 1 then
begin
write(i);
n := n + 1;
end;
i := i + 1;
end;
end
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Swift
|
Swift
|
import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Tcl
|
Tcl
|
package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#TXR
|
TXR
|
(set-sig-handler sig-int
(lambda (signum async-p)
(throwf 'error "caught signal ~s" signum)))
(let ((start-time (time)))
(catch (each ((num (range 1)))
(format t "~s\n" num)
(usleep 500000))
(error (msg)
(let ((end-time (time)))
(format t "\n\n~a after ~s seconds of execution\n"
msg (- end-time start-time))))))
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#TXR
|
TXR
|
(defvar age-name '((27 Jonah)
(18 Alan)
(28 Glory)
(18 Popeye)
(28 Alan)))
(defvar nemesis-name '((Jonah Whales)
(Jonah Spiders)
(Alan Ghosts)
(Alan Zombies)
(Glory Buffy)))
(defun hash-join (left left-key right right-key)
(let ((join-hash [group-by left-key left])) ;; hash phase
(append-each ((r-entry right)) ;; join phase
(collect-each ((l-entry [join-hash [right-key r-entry]]))
^(,l-entry ,r-entry)))))
(format t "~s\n" [hash-join age-name second nemesis-name first])
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#VBScript
|
VBScript
|
Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"
Call hash_join(t_age,1,t_nemesis,0)
Sub hash_join(table_1,index_1,table_2,index_2)
Set hash = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(table_1)
hash.Add i,Array(table_1(i,0),table_1(i,1))
Next
For j = 0 To UBound(table_2)
For Each key In hash.Keys
If hash(key)(index_1) = table_2(j,index_2) Then
WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
" = " & table_2(j,0) & "," & table_2(j,1)
End If
Next
Next
End Sub
|
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.
|
#Elena
|
Elena
|
import extensions;
import system'math;
Haversine(lat1,lon1,lat2,lon2)
{
var R := 6372.8r;
var dLat := (lat2 - lat1).Radian;
var dLon := (lon2 - lon1).Radian;
var dLat1 := lat1.Radian;
var dLat2 := lat2.Radian;
var a := (dLat / 2).sin() * (dLat / 2).sin() + (dLon / 2).sin() * (dLon / 2).sin() * dLat1.cos() * dLat2.cos();
^ R * 2 * a.sqrt().arcsin()
}
public program()
{
console.printLineFormatted("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12r, -86.67r, 33.94r, -118.40r,
Haversine(36.12r, -86.67r, 33.94r, -118.40r))
}
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
NotebookWrite[EvaluationNotebook[], "Goodbye, World!"]
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
fprintf('Goodbye, World!');
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#min
|
min
|
"Goodbye, World!" print
|
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
|
#ERRE
|
ERRE
|
! Hello World in ERRE language
PROGRAM HELLO
BEGIN
PRINT("Hello world!")
END PROGRAM
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function s = StructFromArrays(allKeys, allVals)
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
% Assumes arrays are same size and valid types
s = struct;
if iscell(allVals)
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals{k};
end
else
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals(k);
end
end
end
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#MiniScript
|
MiniScript
|
keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]
d = {}
for i in range(keys.len-1)
d[keys[i]] = values[i]
end for
print d
|
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
|
#FOCAL
|
FOCAL
|
01.10 S N=0
01.20 S P=0
01.30 D 3
01.40 I (19-P)1.7
01.50 T %4,N,!
01.60 S P=P+1
01.70 I (N-1001)1.3
01.80 T N,!
01.90 Q
02.10 S A=0
02.20 S B=N
02.30 S C=FITR(B/10)
02.40 S A=A+B-C*10
02.50 S B=C
02.60 I (-B)2.3
03.10 S N=N+1
03.20 D 2
03.30 I (FITR(N/A)*A-N)3.1
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Tcl
|
Tcl
|
package require Tk
proc maxSize {} {
# Need a dummy window; max window can be changed by scripts
set top .__defaultMaxSize__
if {![winfo exists $top]} {
toplevel $top
wm withdraw $top
}
# Default max size of window is value we want
return [wm maxsize $top]
}
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Visual_Basic
|
Visual Basic
|
TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
' Determine the height and width of the screen
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
' Make adjustments for window decorations and menubars
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Drawing
Imports System.Windows.Forms
Module Program
Sub Main()
Dim bounds As Rectangle = Screen.PrimaryScreen.Bounds
Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}")
Dim workingArea As Rectangle = Screen.PrimaryScreen.WorkingArea
Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}")
End Sub
End Module
|
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
|
#Clojure
|
Clojure
|
(ns experimentation.core
(:import (javax.swing JOptionPane JFrame JTextArea JButton)
(java.awt FlowLayout)))
(JOptionPane/showMessageDialog nil "Goodbye, World!")
(let [button (JButton. "Goodbye, World!")
window (JFrame. "Goodbye, World!")
text (JTextArea. "Goodbye, World!")]
(doto window
(.setLayout (FlowLayout.))
(.add button)
(.add text)
(.pack)
(.setDefaultCloseOperation (JFrame/EXIT_ON_CLOSE))
(.setVisible true)))
|
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.
|
#C.2B.2B
|
C++
|
file task.h
|
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
|
#11l
|
11l
|
V (target_min, target_max) = (1, 10)
V (mn, mx) = (target_min, target_max)
print(
‘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(target_min, target_max))
V i = 0
L
i++
V guess = (mn + mx) I/ 2
V txt = input(‘Guess #2 is: #2. The score for which is (h,l,=): ’.format(i, guess)).trim(‘ ’).lowercase()[0]
I txt !C ‘hl=’
print(‘ I don't understand your input of '#.' ?’.format(txt))
L.continue
I txt == ‘h’
mx = guess - 1
I txt == ‘l’
mn = guess + 1
I txt == ‘=’
print(‘ Ye-Haw!!’)
L.break
I (mn > mx) | (mn < target_min) | (mx > target_max)
print(‘Please check your scoring as I cannot find the value’)
L.break
print("\nThanks for keeping score.")
|
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
|
#ALGOL_W
|
ALGOL W
|
begin
% find some happy numbers %
% returns true if n is happy, false otherwise; n must be >= 0 %
logical procedure isHappy( integer value n ) ;
if n < 2 then true
else begin
% seen is used to hold the values of the cycle of the %
% digit square sums, as noted in the Batch File %
% version, we do not need a large array. The digit %
% square sum of 9 999 999 999 is 810... %
integer array seen( 0 :: 32 );
integer number, trys;
number := n;
trys := -1;
while begin
logical terminated;
integer tPos;
terminated := false;
tPos := 0;
while not terminated and tPos <= trys do begin
terminated := seen( tPos ) = number;
tPos := tPos + 1
end while_not_terminated_and_tPos_lt_trys ;
number > 1 and not terminated
end do begin
integer sum;
trys := trys + 1;
seen( trys ) := number;
sum := 0;
while number > 0 do begin
integer digit;
digit := number rem 10;
number := number div 10;
sum := sum + ( digit * digit )
end while_number_gt_0 ;
number := sum
end while_number_gt_1_and_not_terminated ;
number = 1
end isHappy ;
% print the first 8 happy numbers %
begin
integer happyCount, n;
happyCount := 0;
n := 1;
write( "first 8 happy numbers: " );
while happyCount < 8 do begin
if isHappy( n ) then begin
writeon( i_w := 1, " ", n );
happyCount := happyCount + 1
end if_isHappy_n ;
n := n + 1
end while_happyCount_lt_8
end
end.
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#UNIX_Shell
|
UNIX Shell
|
c="1"
# Trap signals for SIGQUIT (3), SIGABRT (6) and SIGTERM (15)
trap "echo -n 'We ran for ';echo -n `expr $c /2`; echo " seconds"; exit" 3 6 15
while [ "$c" -ne 0 ]; do # infinite loop
# wait 0.5 # We need a helper program for the half second interval
c=`expr $c + 1`
done
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
' Add event handler for Cntrl+C command
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#Visual_FoxPro
|
Visual FoxPro
|
LOCAL i As Integer, n As Integer
CLOSE DATABASES ALL
*!* Create and populate the hash tables
CREATE CURSOR people_ids(id I, used L DEFAULT .F.)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON used TAG used BINARY COLLATE "Machine"
SET ORDER TO 0
CREATE CURSOR nem_ids(id I, used L DEFAULT .F.)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON used TAG used BINARY COLLATE "Machine"
SET ORDER TO 0
n = 100
FOR i = 1 TO n
INSERT INTO people_ids (id) VALUES (i)
INSERT INTO nem_ids (id) VALUES (i)
ENDFOR
CREATE CURSOR people (age I, name V(16), id I)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON name TAG name COLLATE "Machine"
SET ORDER TO 0
INSERT INTO people (age, name) VALUES (27, "Jonah")
INSERT INTO people (age, name) VALUES (18, "Alan")
INSERT INTO people (age, name) VALUES (28, "Glory")
INSERT INTO people (age, name) VALUES (18, "Popeye")
INSERT INTO people (age, name) VALUES (28, "Alan")
REPLACE id WITH HashMe("people_ids") ALL
*!* The plural of nemesis is nemeses
CREATE CURSOR nemeses (name V(16), nemesis V(16), p_id I, id I)
INDEX ON id TAG id COLLATE "Machine"
INDEX ON p_id TAG p_id COLLATE "Machine"
INDEX ON name TAG name COLLATE "Machine"
SET ORDER TO 0
INSERT INTO nemeses (name, nemesis) VALUES ("Jonah", "Whales")
INSERT INTO nemeses (name, nemesis) VALUES ("Jonah", "Spiders")
INSERT INTO nemeses (name, nemesis) VALUES ("Alan", "Ghosts")
INSERT INTO nemeses (name, nemesis) VALUES ("Alan", "Zombies")
INSERT INTO nemeses (name, nemesis) VALUES ("Glory", "Buffy")
REPLACE id WITH HashMe("nem_ids") ALL
UPDATE nemeses SET p_id = people.id FROM people ;
WHERE nemeses.name = people.name
*!* Show the join
SELECT pe.age, pe.name, ne.nemesis FROM people pe ;
JOIN nemeses ne ON pe.id = ne.p_id TO FILE "hashjoin.txt"
FUNCTION HashMe(cTable As String) As Integer
LOCAL ARRAY a[1]
SELECT MIN(id) FROM (cTable) WHERE NOT used INTO ARRAY a
UPDATE (cTable) SET used = .T. WHERE id = a[1]
RETURN a[1]
ENDFUNC
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#Wren
|
Wren
|
import "/fmt" for Fmt
class A {
construct new(age, name) {
_age = age
_name = name
}
age { _age }
name { _name }
}
class B {
construct new(character, nemesis) {
_character = character
_nemesis = nemesis
}
character { _character }
nemesis { _nemesis }
}
var tableA = [
A.new(27, "Jonah"), A.new(18, "Alan"), A.new(28, "Glory"),
A.new(18, "Popeye"), A.new(28, "Alan")
]
var tableB = [
B.new("Jonah", "Whales"), B.new("Jonah", "Spiders"), B.new("Alan", "Ghosts"),
B.new("Alan", "Zombies"), B.new("Glory", "Buffy")
]
var h = {}
var i = 0
for (a in tableA) {
var n = h[a.name]
if (n) {
n.add(i)
} else {
h[a.name] = [i]
}
i = i + 1
}
System.print("Age Name Character Nemesis")
System.print("--- ----- --------- -------")
for (b in tableB) {
var c = h[b.character]
if (c) {
for (i in c) {
var t = tableA[i]
Fmt.print("$3d $-5s $-9s $s", t.age, t.name, b.character, b.nemesis)
}
}
}
|
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.
|
#Elixir
|
Elixir
|
defmodule Haversine do
@v :math.pi / 180
@r 6372.8 # km for the earth radius
def distance({lat1, long1}, {lat2, long2}) do
dlat = :math.sin((lat2 - lat1) * @v / 2)
dlong = :math.sin((long2 - long1) * @v / 2)
a = dlat * dlat + dlong * dlong * :math.cos(lat1 * @v) * :math.cos(lat2 * @v)
@r * 2 * :math.asin(:math.sqrt(a))
end
end
bna = {36.12, -86.67}
lax = {33.94, -118.40}
IO.puts Haversine.distance(bna, lax)
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#mIRC_Scripting_Language
|
mIRC Scripting Language
|
echo -ag Goodbye, World!
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#ML.2FI
|
ML/I
|
Goodbye, World!
|
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
|
#Euler_Math_Toolbox
|
Euler Math Toolbox
|
"Hello world!"
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Neko
|
Neko
|
/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
var sprintf = $loader.loadprim("std@sprintf", 2)
var array_keys = $array("one",2,"three",4,"five")
var array_vals = $array("six",7,"eight",9,"zero")
var elements = $asize(array_keys)
var table = $hnew(elements)
var step = elements
while (step -= 1) >= 0 $hadd(table, $hkey(array_keys[step]), array_vals[step])
/*
$hiter accepts a hashtable and a function that accepts two args, key, val
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)
|
http://rosettacode.org/wiki/Hash_from_two_arrays
|
Hash from two arrays
|
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
|
#Nemerle
|
Nemerle
|
using System;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections.NCollectionsExtensions;
module AssocArray
{
Main() : void
{
def list1 = ["apples", "oranges", "bananas", "kumquats"];
def list2 = [13, 34, 12];
def inventory = Hashtable(ZipLazy(list1, list2));
foreach (item in inventory)
WriteLine("{0}: {1}", item.Key, item.Value);
}
}
|
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
|
#Fortran
|
Fortran
|
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 13:15:59
!
!a=./f && make $a && $a < unixdict.txt
!gfortran -std=f2003 -Wall -ffree-form f.f03 -o f
! 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002
!
!Compilation finished at Tue May 21 13:15:59
program Harshad
integer :: i, h = 0
do i=1, 20
call nextHarshad(h)
write(6, '(i5)', advance='no') h
enddo
h = 1000
call nextHarshad(h)
write(6, '(i5)') h
contains
subroutine nextHarshad(h) ! alter input integer h to be the next greater Harshad number.
integer, intent(inout) :: h
h = h+1 ! bigger
do while (.not. isHarshad(h))
h = h+1
end do
end subroutine nextHarshad
logical function isHarshad(a)
integer, intent(in) :: a
integer :: mutable, digit_sum
isHarshad = .false.
if (a .lt. 1) return ! false if a < 1
mutable = a
digit_sum = 0
do while (mutable /= 0)
digit_sum = digit_sum + mod(mutable, 10)
mutable = mutable / 10
end do
isHarshad = 0 .eq. mod(a, digit_sum)
end function isHarshad
end program Harshad
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#Wren
|
Wren
|
import "input" for Keyboard
import "dome" for Window, Process
import "graphics" for Canvas, Color
class Game {
static init() {
Canvas.print("Maximize the window and press 'm'", 0, 0, Color.white)
}
static update() {
if (Keyboard.isKeyDown("m") ) {
System.print("Maximum window dimensions are %(Window.width) x %(Window.height)")
Process.exit(0)
}
}
static draw(alpha) {}
}
|
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
|
GUI/Maximum window dimensions
|
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.
This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.
The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).
The values calculated should represent the usable desktop area of a window maximized to fit the the screen.
Considerations
--- Multiple Monitors
For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.: the monitor which would display a window if such instructions were given).
--- Tiling Window Managers
For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).
|
#XPL0
|
XPL0
|
int A;
[A:= GetFB;
Text(0, "Width = "); IntOut(0, A(0)); CrLf(0);
Text(0, "Height = "); IntOut(0, A(1)); CrLf(0);
]
|
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
|
#COBOL
|
COBOL
|
CLASS-ID ProgramClass.
METHOD-ID Main STATIC.
PROCEDURE DIVISION.
INVOKE TYPE Application::EnableVisualStyles() *> Optional
INVOKE TYPE MessageBox::Show("Goodbye, World!")
END METHOD.
END CLASS.
|
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.
|
#Delphi
|
Delphi
|
type
TForm1 = class(TForm)
MaskEditValue: TMaskEdit; // Set Editmask on: "99;0; "
SpeedButtonIncrement: TSpeedButton;
SpeedButtonDecrement: TSpeedButton;
procedure MaskEditValueChange(Sender: TObject);
procedure SpeedButtonDecrementClick(Sender: TObject);
procedure SpeedButtonIncrementClick(Sender: TObject);
end;
var
Form1: TForm1;
implementation
procedure TForm1.MaskEditValueChange(Sender: TObject);
begin
TMaskEdit(Sender).Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) = 0;
SpeedButtonIncrement.Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) < 10;
SpeedButtonDecrement.Enabled := StrToIntDef(Trim(TMaskEdit(Sender).Text), 0) > 0;
end;
procedure TForm1.SpeedButtonDecrementClick(Sender: TObject);
begin
MaskEditValue.Text := IntToStr(Pred(StrToIntDef(Trim(MaskEditValue.Text), 0)));
end;
procedure TForm1.SpeedButtonIncrementClick(Sender: TObject);
begin
MaskEditValue.Text := IntToStr(Succ(StrToIntDef(Trim(MaskEditValue.Text), 0)));
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
|
#Action.21
|
Action!
|
PROC Main()
BYTE n,min=[1],max=[100]
CHAR c
PrintF("Think a number in range %B-%B%E",min,max)
DO
n=(max+min) RSH 1
PrintF("My guess is %B%E",n)
PrintF("Is it (E)qual, (L)ower or (H)igher?")
c=GetD(7)
Put(c) PutE()
IF c='E THEN
Print("I guessed!")
EXIT
ELSEIF c='L THEN
max=n-1
ELSEIF c='H THEN
min=n+1
FI
IF max<min THEN
Print("You are cheating...")
EXIT
FI
OD
RETURN
|
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
|
#Ada
|
Ada
|
with Ada.Text_IO;
procedure Guess_Number_Player is
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
type Feedback is (Lower, Higher, Correct);
package Feedback_IO is new Ada.Text_IO.Enumeration_IO (Feedback);
My_Guess : Integer := Lower_Limit + (Upper_Limit - Lower_Limit) / 2;
Your_Feedback : Feedback;
begin
Ada.Text_IO.Put_Line ("Think of a number!");
loop
Ada.Text_IO.Put_Line ("My guess: " & Integer'Image (My_Guess));
Ada.Text_IO.Put ("Your answer (lower, higher, correct): ");
Feedback_IO.Get (Your_Feedback);
exit when Your_Feedback = Correct;
if Your_Feedback = Lower then
My_Guess := Lower_Limit + (My_Guess - Lower_Limit) / 2;
else
My_Guess := My_Guess + (Upper_Limit - My_Guess) / 2;
end if;
end loop;
Ada.Text_IO.Put_Line ("I guessed well!");
end Guess_Number;
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
Lower_Limit : Integer;
Upper_Limit : Integer;
begin
loop
Ada.Text_IO.Put ("Lower Limit: ");
Int_IO.Get (Lower_Limit);
Ada.Text_IO.Put ("Upper Limit: ");
Int_IO.Get (Upper_Limit);
exit when Lower_Limit < Upper_Limit;
Ada.Text_IO.Put_Line ("Lower limit must be lower!");
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Player;
|
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
|
#APL
|
APL
|
∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
[3] ⎕IO←1 ⍝ Index origin
[4] ∆roof ∆first←2↑arg,10 ⍝
[5]
[6] bin←{
[7] ⍺←⍬ ⍝ Default left arg
[8] ⍵=1:1 ⍝ Always happy!
[9]
[10] numbers←⍎¨1⊂⍕⍵ ⍝ Split numbers into parts
[11] next←+/{⍵*2}¨numbers ⍝ Sum and square of numbers
[12]
[13] next∊⍺:0 ⍝ Return 0, if already exists
[14] (⍺,next)∇ next ⍝ Check next number (recursive)
[15]
[16] }¨iroof←⍳∆roof ⍝ Does all numbers upto ∆root smiles?
[17]
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
∇
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Visual_FoxPro
|
Visual FoxPro
|
*!* In VFP, Ctrl+C is normally used to copy text to the clipboard.
*!* Esc is used to stop execution.
CLEAR
SET ESCAPE ON
ON ESCAPE DO StopLoop
CLEAR DLLS
DECLARE Sleep IN WIN32API INTEGER nMilliSeconds
lLoop = .T.
n = 0
? "Press Esc to Cancel..."
t1 = INT(SECONDS())
DO WHILE lLoop
n = n + 1
? n
Sleep(500)
ENDDO
? "Elapsed time:", TRANSFORM(INT(SECONDS()) - t1) + " secs."
CLEAR DLLS
RETURN TO MASTER
PROCEDURE StopLoop
lLoop = .F.
ENDPROC
|
http://rosettacode.org/wiki/Handle_a_signal
|
Handle a signal
|
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.
Task
Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.
|
#Wren
|
Wren
|
import "scheduler" for Scheduler
import "timer" for Timer
import "io" for Stdin
var start = System.clock
var stop = false
Scheduler.add {
var n = 0
while (true) {
System.print(n)
if (stop) {
var elapsed = System.clock - start + n * 0.5
System.print("Program has run for %(elapsed) seconds.")
return
}
Timer.sleep(500)
n = n + 1
}
}
Stdin.isRaw = true // enable control characters to go into stdin
while (true) {
var b = Stdin.readByte()
if (b == 3 || b == 28) break // quits on pressing either Ctrl-C os Ctrl-\
}
Stdin.isRaw = false
stop = true
|
http://rosettacode.org/wiki/Hash_join
|
Hash join
|
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm.
Task[edit]
Implement the "hash join" algorithm, and demonstrate that it passes the test-case listed below.
You should represent the tables as data structures that feel natural in your programming language.
Guidance
The "hash join" algorithm consists of two steps:
Hash phase: Create a multimap from one of the two tables, mapping from each join column value to all the rows that contain it.
The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.
Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.
Join phase: Scan the other table, and find matching rows by looking in the multimap created before.
In pseudo-code, the algorithm could be expressed as follows:
let A = the first input table (or ideally, the larger one)
let B = the second input table (or ideally, the smaller one)
let jA = the join column ID of table A
let jB = the join column ID of table B
let MB = a multimap for mapping from single values to multiple rows of table B (starts out empty)
let C = the output table (starts out empty)
for each row b in table B:
place b in multimap MB under key b(jB)
for each row a in table A:
for each row b in multimap MB under key a(jA):
let c = the concatenation of row a and row b
place row c in table C
Test-case
Input
Output
A =
Age
Name
27
Jonah
18
Alan
28
Glory
18
Popeye
28
Alan
B =
Character
Nemesis
Jonah
Whales
Jonah
Spiders
Alan
Ghosts
Alan
Zombies
Glory
Buffy
jA =
Name (i.e. column 1)
jB =
Character (i.e. column 0)
A.Age
A.Name
B.Character
B.Nemesis
27
Jonah
Jonah
Whales
27
Jonah
Jonah
Spiders
18
Alan
Alan
Ghosts
18
Alan
Alan
Zombies
28
Glory
Glory
Buffy
28
Alan
Alan
Ghosts
28
Alan
Alan
Zombies
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
|
#zkl
|
zkl
|
ageName:=T(27,"Jonah", 18,"Alan", 28,"Glory", 18,"Popeye", 28,"Alan");
nameNemesis:=T("Jonah","Whales", "Jonah","Spiders", "Alan","Ghosts",
"Alan","Zombies", "Glory","Buffy");
fcn addAN(age,name,d){ // keys are names, values are ( (age,...),() )
if (r:=d.find(name)) d[name] = T(r[0].append(age),r[1]);
else d.add(name,T(T(age),T));
d // return d so pump will use that as result for assignment
}
fcn addNN(name,nemesis,d){ // values-->( (age,age...), (nemesis,...) )
if (r:=d.find(name)){
ages,nemesises := r;
d[name] = T(ages,nemesises.append(nemesis));
}
}
// Void.Read --> take existing i, read next one, pass both to next function
var d=ageName.pump(Void,Void.Read,T(addAN,Dictionary()));
nameNemesis.pump(Void,Void.Read,T(addNN,d));
d.println(); // the union of the two tables
d.keys.sort().pump(Console.println,'wrap(name){ //pretty print the join
val:=d[name]; if (not val[1])return(Void.Skip);
String(name,":",d[name][1].concat(","));
})
|
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.
|
#Elm
|
Elm
|
haversine : ( Float, Float ) -> ( Float, Float ) -> Float
haversine ( lat1, lon1 ) ( lat2, lon2 ) =
let
r =
6372.8
dLat =
degrees (lat2 - lat1)
dLon =
degrees (lon2 - lon1)
a =
(sin (dLat / 2))
^ 2
+ (sin (dLon / 2))
^ 2
* cos (degrees lat1)
* cos (degrees lat2)
in
r * 2 * asin (sqrt a)
view =
Html.div []
[ Html.text (toString (haversine ( 36.12, -86.67 ) ( 33.94, -118.4 )))
]
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Modula-2
|
Modula-2
|
MODULE HelloWorld;
FROM Terminal IMPORT WriteString,ReadChar;
BEGIN
WriteString("Goodbye, World!");
ReadChar
END HelloWorld.
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#N.2Ft.2Froff
|
N/t/roff
|
Goodbye, World!
|
http://rosettacode.org/wiki/Hello_world/Newline_omission
|
Hello world/Newline omission
|
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
|
#Nanoquery
|
Nanoquery
|
print "Goodbye, world!"
|
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
|
#Extended_BrainF.2A.2A.2A
|
Extended BrainF***
|
[.>]@Hello world!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.