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/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Arturo
Arturo
n: random 1 10   while [notEqual? to :integer input "Guess the number: " n] [ print "Wrong!" ]   print "Well guessed!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#AutoHotkey
AutoHotkey
Random, rand, 1, 10 ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister msgbox I am thinking of a number between 1 and 10.   loop { InputBox, guess, Guess the number, Type in a number from 1 to 10 If (guess = rand) { msgbox Well Guessed! Break ; exits loop } Else Msgbox Try again. }  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Arturo
Arturo
subarraySum: function [arr][ curr: 0 mx: 0 fst: size arr lst: 0 currFst: 0   loop.with: 'i arr [e][ curr: curr + e if e > curr [ curr: e currFst: i ] if curr > mx [ mx: curr fst: currFst lst: i ] ] if? lst > fst -> return @[mx, slice arr fst lst] else -> return [0, []] ]   sequences: @[ @[1, 2, 3, 4, 5, neg 8, neg 9, neg 20, 40, 25, neg 5] @[neg 1, neg 2, 3, 5, 6, neg 2, neg 1, 4, neg 4, 2, neg 1] @[neg 1, neg 2, neg 3, neg 4, neg 5] @[] ]   loop sequences 'seq [ print [pad "sequence:" 15 seq] processed: subarraySum seq print [pad "max sum:" 15 first processed] print [pad "subsequence:" 15 last processed "\n"] ]
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.
#PureBasic
PureBasic
Enumeration #TextGadget #AddButton #SubButton EndEnumeration   Procedure UpdateGadgets(Value,UpdateValue=0) Overmax=0: UnderMin=0 If Value>=10 Overmax=1 ElseIf Value<=0 UnderMin=1 EndIf DisableGadget(#AddButton,Overmax) DisableGadget(#SubButton,UnderMin) If UpdateValue SetGadgetText(#TextGadget,Str(Value)) EndIf EndProcedure   If OpenWindow(0,#PB_Ignore,#PB_Ignore,110,70,"PB-GUI",#PB_Window_SystemMenu) StringGadget(#TextGadget,10,10,90,20,"") ButtonGadget(#AddButton,10,40,30,20,"+") ButtonGadget(#SubButton,70,40,30,20,"-") UpdateGadgets(Value,1) Repeat Event=WaitWindowEvent() If Event=#PB_Event_Gadget Gadget=EventGadget() Select Gadget Case #AddButton Value+1 UpdateGadgets(Value,1) Case #SubButton Value-1 UpdateGadgets(Value,1) Default EType=EventType() If EType=#PB_EventType_Change Value=Val(GetGadgetText(#TextGadget)) UpdateGadgets(Value) EndIf EndSelect EndIf Until Event=#PB_Event_CloseWindow EndIf
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#BASIC
BASIC
100 L% = 1 110 U% = 10 120 N% = RND(1) * (U% - L% + 1) + L% 130 PRINT "A NUMBER FROM " L%; 140 PRINT " TO " U%; 150 PRINT ", CALLED A TARGET, HAS BEEN RANDOMLY CHOSEN." 160 FOR Q = 0 TO 1 STEP 0 170 INPUT "GUESS THE TARGET NUMBER: "; G% 180 IF G% < L% OR G% > U% THEN PRINT "THE INPUT WAS INAPPROPRIATE." 190 IF G% > N% THEN PRINT "THE GUESS WAS HIGHER THAN THE TARGET." 200 IF G% < N% THEN PRINT "THE GUESS WAS LESS THAN THE TARGET." 210 Q = G% = N% 220 NEXT 230 PRINT "THE GUESS WAS EQUAL TO THE TARGET."
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#EasyLang
EasyLang
n = 8 for row range 4 sz = 100 / n for i range n c = i / (n - 1) if row mod 2 = 1 c = 1 - c . color3 c c c move sz * i row * 25 rect sz + 1 25 . n *= 2 .
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Euler_Math_Toolbox
Euler Math Toolbox
  >function grayscale(y1,y2,n,direction=1) ... $ loop 0 to n-1; $ s=#/(n-1); barcolor(rgb(s,s,s)); $ if direction==1 then plotbar(#/n,y1,1/n,y2-y1); $ else plotbar(1-(#+1)/n,y1,1/n,y2-y1); $ endif; $ end; $endfunction >function grayscales () ... $ aspect(2); barstyle("#"); $ window(0,0,1023,1023); margin(0); setplot(0,1,0,1); $ clg; $ hold on; $ grayscale(3/4,1,8,1); $ grayscale(1/2,3/4,14,-1); $ grayscale(1/4,1/2,32,1); $ grayscale(0,1/4,64,-1); $ hold off; $endfunction >grayscales:  
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#FreeBASIC
FreeBASIC
' version 01-09-2017 ' compile with: fbc -s console ' or compile with: fbc -s gui ' hit any key to stop   Dim As UInteger d, blocks, blocksize, ps, col, h, w, x, y1, y2   ScreenInfo w, h ' create display size window, 8bit color (palette), no frame ScreenRes w, h, 8,, 8   For x = 0 To 255 ' create grayscale palette for Palette x, x, x, x ' the window we just opened Next   h = h \ 4 : y2 = h -1   If w Mod 64 <> 0 Then w -= (w Mod 64) blocks = 8 : blocksize = w \ 8   For ps = 1 To 4 For x = 0 To blocks -1 col = 255 * x \ (blocks -1) ' from black to white If (ps And 1) = 0 Then col = 255 - col ' from white to black Line (x * blocksize, y1) - (((x +1) * blocksize) -1, y2), col, bf Next y1 += h : y2 += h blocks *= 2 : blocksize \= 2 Next   ' empty keyboard buffer While Inkey <> "" : Wend   Sleep 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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim hle As String Dim lowest As Integer = 1 Dim highest As Integer = 20 Dim guess As Integer = 10 Print "Please choose a number between 1 and 20 but don't tell me what it is yet" Print Do Print "My guess is"; guess Do Input "Is this higher/lower or equal to your chosen number h/l/e : "; hle hle = LCase(hle) If hle = "l" AndAlso guess = highest Then Print "It can't be more than"; highest; ", try again" hle = "i" '' invalid ElseIf hle = "h" AndAlso guess = lowest Then Print "It can't be less than"; lowest; ", try again" hle = "i" End If Loop Until hle = "h" OrElse hle = "l" OrElse hle = "e" If hle = "e" Then Print "Good, thanks for playing the gaame with me!" Exit Do ElseIf hle = "h" Then If highest > guess - 1 Then highest = guess - 1 Else If lowest < guess + 1 Then lowest = guess + 1 End If guess = (lowest + highest)\2 Loop End
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#CLU
CLU
sum_dig_sq = proc (n: int) returns (int) sum_sq: int := 0 while n > 0 do sum_sq := sum_sq + (n // 10) ** 2 n := n / 10 end return (sum_sq) end sum_dig_sq   is_happy = proc (n: int) returns (bool) nn: int := sum_dig_sq(n) while nn ~= n cand nn ~= 1 do n := sum_dig_sq(n) nn := sum_dig_sq(sum_dig_sq(nn)) end return (nn = 1) end is_happy   happy_numbers = iter (start, num: int) yields (int) n: int := start while num > 0 do if is_happy(n) then yield (n) num := num-1 end n := n+1 end end happy_numbers   start_up = proc () po: stream := stream$primary_output()   for i: int in happy_numbers(1, 8) do stream$putl(po, int$unparse(i)) end end start_up
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.
#J
J
require 'trig' haversin=: 0.5 * 1 - cos Rearth=: 6372.8 haversineDist=: Rearth * haversin^:_1@((1 , *&(cos@{.)) +/ .* [: haversin -)&rfd  
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
#Verbexx
Verbexx
@STDOUT "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
#Verilog
Verilog
module main; initial begin $write("Goodbye, World!"); $finish ; end endmodule
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
#Vim_Script
Vim Script
echon "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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.Write("Goodbye, World!") End Sub   End Module
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
#Frege
Frege
module HelloWorld where main _ = println "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
#Scheme
Scheme
(define (lists->hash-table keys values . rest) (apply alist->hash-table (map cons keys values) rest))
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: numericHash is hash [string] integer; var numericHash: myHash is numericHash.value;   const proc: main is func local var array string: keyList is [] ("one", "two", "three"); var array integer: valueList is [] (1, 2, 3); var integer: number is 0; begin for number range 1 to length(keyList) do myHash @:= [keyList[number]] valueList[number]; end for; end func;
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
nextHarshad = NestWhile[# + 1 &, # + 1, ! Divisible[#, Total@IntegerDigits@#] &] &; Print@Rest@NestList[nextHarshad, 0, 20]; Print@nextHarshad@1000;
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
#Gambas
Gambas
Message.Info("Goodbye, World!") ' Display a simple message box
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
#Genie
Genie
[indent=4] /* Genie GTK+ hello valac --pkg gtk+-3.0 hello-gtk.gs ./hello-gtk */ uses Gtk   init Gtk.init (ref args) var window = new Window (WindowType.TOPLEVEL) var label = new Label("Goodbye, World!") window.add(label) window.set_default_size(160, 100) window.show_all() window.destroy.connect(Gtk.main_quit) Gtk.main()
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Icon_and_Unicon
Icon and Unicon
  import gui $include "guih.icn"   # Provides a basic message dialog class MessageDialog : Dialog (message) method component_setup () label := Label ("label="||message, "pos=20,20") add (label) button := TextButton("label=OK", "pos=100,60") button.connect (self, "dispose", ACTION_EVENT) add (button)   connect (self, "dispose", CLOSE_BUTTON_EVENT) attrib ("size=200,100", "bg=light gray") end   initially (message) self.Dialog.initially() self.message := message end   # Provides a basic yes/no question dialog class QuestionDialog : Dialog (answer, message) method answered_yes () return answer == "yes" end   method answer_yes () answer := "yes" dispose () end   method answer_no () answer := "no" dispose () end   method component_setup () label := Label ("label="||message, "pos=20,20") add (label) buttonYes := TextButton("label=Yes", "pos=40,60") buttonYes.connect (self, "answer_yes", ACTION_EVENT) add (buttonYes) buttonNo := TextButton("label=No", "pos=120,60") buttonNo.connect (self, "answer_no", ACTION_EVENT) add (buttonNo)   connect (self, "dispose", CLOSE_BUTTON_EVENT) attrib ("size=200,100", "bg=light gray") end   initially (message) self.Dialog.initially() self.answer := "no" self.message := message end   # The main window, displays the different components class WindowApp : Dialog (field, value) method increment () value +:= 1 field.set_contents (string(value)) end   method random () query := QuestionDialog ("Set to random?") query.show_modal () if query.answered_yes () then { value := ?100 field.set_contents (string(value)) } end   method handle_text_field () if not(integer(field.get_contents ())) then { warning := MessageDialog ("Not a number") warning.show_modal () field.set_contents (string(value)) } else { value := integer(field.get_contents ()) } end   method component_setup () value := 0 field := TextField("contents="||value, "pos=20,20", "size=150") field.connect (self, "handle_text_field", TEXTFIELD_CHANGED_EVENT) add (field) button1 := TextButton("label=Increment", "pos=20,60", "size=70") button1.connect (self, "increment", ACTION_EVENT) add (button1) button2 := TextButton("label=Random", "pos=100,60", "size=70") button2.connect (self, "random", ACTION_EVENT) add (button2)   connect (self, "dispose", CLOSE_BUTTON_EVENT) attrib ("size=200,100", "bg=light gray") end end   # create and show the window procedure main () w := WindowApp () w.show_modal () end  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Arturo
Arturo
hamming: function [limit][ if limit=1 -> return 1 h: map 0..limit-1 'z -> 1 x2: 2, x3: 3, x5: 5 i: 0, j: 0, k: 0   loop 1..limit-1 'n [ set h n min @[x2 x3 x5] if x2 = h\[n] [ i: i + 1 x2: 2 * h\[i] ] if x3 = h\[n] [ j: j + 1 x3: 3 * h\[j] ] if x5 = h\[n] [ k: k + 1 x5: 5 * h\[k] ] ] last h ] print map 1..20 => hamming print hamming 1691 print hamming 1000000
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#AutoIt
AutoIt
  $irnd = Random(1, 10, 1) $iinput = -1 While $input <> $irnd $iinput = InputBox("Choose a number", "Please chosse a Number between 1 and 10") WEnd MsgBox(0, "Success", "Well guessed!")  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#AWK
AWK
  # syntax: GAWK -f GUESS_THE_NUMBER.AWK BEGIN { srand() n = int(rand() * 10) + 1 print("I am thinking of a number between 1 and 10. Try to guess it.") while (1) { getline ans if (ans !~ /^[0-9]+$/) { print("Your input was not a number. Try again.") continue } if (n == ans) { print("Well done you.") break } print("Incorrect. Try again.") } exit(0) }  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#ATS
ATS
  (* ** This one is ** translated into ATS from the Ocaml entry *)   (* ****** ****** *) // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o maxsubseq maxsubseq.dats // (* ****** ****** *) // #include "share/atspre_staload.hats" // (* ****** ****** *)   typedef ints = List0(int)   (* ****** ****** *)   fun maxsubseq (xs: ints): (int, ints) = let // fun loop ( sum: int, seq: ints , maxsum: int, maxseq: ints, xs: ints ) : (int, ints) = ( case+ xs of | nil () => ( maxsum , list_vt2t(list_reverse(maxseq)) ) (* end of [nil] *) | cons (x, xs) => let val sum = sum + x and seq = cons (x, seq) in if sum < 0 then loop (0, nil, maxsum, maxseq, xs) else ( if sum > maxsum then loop (sum, seq, sum, seq, xs) else loop (sum, seq, maxsum, maxseq, xs) ) (* end of [else] *) end // end of [cons] ) // in loop (0, nil, 0, nil, xs) end // end of [maxsubseq]   implement main0 () = () where { val (maxsum ,maxseq) = maxsubseq ( $list{int}(~1,~2,3,5,6,~2,~1,4,~4,2,~1) ) // val () = println! ("maxsum = ", maxsum) val () = println! ("maxseq = ", maxseq) // } (* end of [main0] *)  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#AutoHotkey
AutoHotkey
seq = -1,-2,3,5,6,-2,-1,4,-4,2,-1 max := sum := start := 0 Loop Parse, seq, `, If (max < sum+=A_LoopField) max := sum, a := start, b := A_Index Else If sum <= 0 sum := 0, start := A_Index ; read out the best subsequence Loop Parse, seq, `, s .= A_Index > a && A_Index <= b ? A_LoopField "," : "" MsgBox % "Max = " max "`n[" SubStr(s,1,-1) "]"
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.
#Python
Python
  #!/usr/bin/env python3   import tkinter as tk   class MyForm(tk.Frame):   def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack(expand=True, fill="both", padx=10, pady=10) self.master.title("Controls") self.setupUI()   def setupUI(self): self.value_entry = tk.Entry(self, justify=tk.CENTER) self.value_entry.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky="nesw") self.value_entry.insert('end', '0') self.value_entry.bind("<KeyPress-Return>", self.eventHandler)   self.decre_btn = tk.Button(self, text="Decrement", state=tk.DISABLED) self.decre_btn.grid(row=1, column=0, padx=5, pady=5) self.decre_btn.bind("<Button-1>", self.eventHandler)   self.incre_btn = tk.Button(self, text="Increment") self.incre_btn.grid(row=1, column=1, padx=5, pady=5) self.incre_btn.bind("<Button-1>", self.eventHandler)   def eventHandler(self, event): value = int(self.value_entry.get()) if event.widget == self.value_entry: if value > 10: self.value_entry.delete("0", "end") self.value_entry.insert("end", "0") elif value == 10: self.value_entry.config(state=tk.DISABLED) self.incre_btn.config(state=tk.DISABLED) self.decre_btn.config(state=tk.NORMAL) elif value == 0: self.value_entry.config(state=tk.NORMAL) self.incre_btn.config(state=tk.NORMAL) self.decre_btn.config(state=tk.DISABLED) elif (value > 0) and (value < 10): self.value_entry.config(state=tk.DISABLED) self.incre_btn.config(state=tk.NORMAL) self.decre_btn.config(state=tk.NORMAL) else: if event.widget == self.incre_btn: if (value >= 0) and (value < 10): value += 1 self.value_entry.config(state=tk.NORMAL) self.value_entry.delete("0", "end") self.value_entry.insert("end", str(value)) if value > 0: self.decre_btn.config(state=tk.NORMAL) self.value_entry.config(state=tk.DISABLED) if value == 10: self.incre_btn.config(state=tk.DISABLED) elif event.widget == self.decre_btn: if (value > 0) and (value <= 10): value -= 1 self.value_entry.config(state=tk.NORMAL) self.value_entry.delete("0", "end") self.value_entry.insert("end", str(value)) self.value_entry.config(state=tk.DISABLED) if (value) < 10: self.incre_btn.config(state=tk.NORMAL) if (value) == 0: self.decre_btn.config(state=tk.DISABLED) self.value_entry.config(state=tk.NORMAL)   def main(): app = MyForm() app.mainloop()   if __name__ == "__main__": main()  
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Batch_File
Batch File
@echo off   :A set /a number=%random% %% 10 + 1 :B set /p guess=Choose a number between 1 and 10: if %guess equ %number% goto win if %guess% gtr 10 msg * "Number must be between 1 and 10." if %guess% leq 0 msg * "Number must be between 1 and 10." if %guess% gtr %number% echo Higher! if %guess% lss %number% echo Lower! goto B :win cls echo You won! The number was %number% pause>nul goto A
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Frink
Frink
  fakewidth =!= dummy   g = new graphics g.antialiased[false] drawBars[g, 0, 1, 0, 1/4, 8] drawBars[g, 1, 0, 1/4, 1/2, 16] drawBars[g, 0, 1, 1/2, 3/4, 32] drawBars[g, 1, 0, 3/4, 1, 64] g.show[640,480,1] // No portable fullscreen mode; user must maximize window.   drawBars[g is graphics, leftColor, rightColor, top, bottom, steps] := { colorStep = (rightColor - leftColor) / steps color = leftColor for i=0 to steps-1 { g.color[color, color, color] g.fillRectSides[i/dummy/steps, top, (i+1)/dummy/steps, bottom] color = color + colorStep } }  
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Gambas
Gambas
Public Sub Form_Open() Dim iRow, iCol, iClr As Integer 'For Row, Column and Colour Dim iInc As Integer = 4 'To calculate RGB colour Dim h1Panel As Panel 'Panels to display colours   With Me 'Setup the Form .Arrangement = Arrange.Row 'Arrange children in rows .Border = False 'No Border .Height = Desktop.Height 'Fill the screen .Width = Desktop.Width 'Fill the screen .Fullscreen = True 'Set the Form to Fullscreen End With   For iRow = 1 To 4 'For each row.. iInc += iInc 'Increase iInc by itself For iCol = 0 To iInc - 1 'For each column.. iClr = iCol * (256 / iInc) 'Set the RGB colour If iRow = 2 Or iRow = 4 Then iClr = 255 - (iCol * (256 / iInc)) 'If row 2 or 4 then reverse the colours h1Panel = New Panel(Me) 'Create a new Panel With h1Panel 'With the Panel.. .Width = Desktop.Width / iInc 'Set the width .Height = Desktop.Height / 4 'Set the height .Background = Color.RGB(iClr, iClr, iClr) 'Set the Background colour .Border = Border.Plain 'Set a Border (It's easier to see the colour changes) End With Next Next   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
#Go
Go
package main   import ( "fmt" "sort" )   func main() { lower, upper := 0, 100 fmt.Printf(`Instructions: Think of integer number from %d (inclusive) to %d (exclusive) and I will guess it. After each guess, I will ask you if it is less than or equal to some number, and you will respond with "yes" or "no". `, lower, upper) answer := sort.Search(upper-lower, func (i int) bool { fmt.Printf("Is your number less than or equal to %d? ", lower+i) s := "" fmt.Scanf("%s", &s) return s != "" && s[0] == 'y' }) fmt.Printf("Your number is %d.\n", lower+answer) }
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
#CoffeeScript
CoffeeScript
happy = (n) -> seen = {} while true n = sum_digit_squares(n) return true if n == 1 return false if seen[n] seen[n] = true   sum_digit_squares = (n) -> sum = 0 for c in n.toString() d = parseInt(c) sum += d*d sum   i = 1 cnt = 0 while cnt < 8 if happy(i) console.log i cnt += 1 i += 1
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.
#Java
Java
public class Haversine { public static final double R = 6372.8; // In kilometers public static double haversine(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2);   double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } public static void main(String[] args) { System.out.println(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
#Vlang
Vlang
fn main() { print("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
#Web_68
Web 68
@ @a@=#!/usr/bin/a68g -nowarn@>@\BEGIN print("Hello World") 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
#Wren
Wren
System.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
#XLISP
XLISP
(display "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
#friendly_interactive_shell
friendly interactive shell
echo 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
#SenseTalk
SenseTalk
  set keyList to ["red", "green", "blue"] set valueList to [150,0,128]   repeat with n=1 to the number of items in keyList set map.(item n of keyList) to item n of valueList end repeat   put map --> (blue:"128", green:"0", red:"150")    
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
#Sidef
Sidef
var keys = %w(a b c) var vals = [1, 2, 3]   var hash = Hash() hash{keys...} = vals... say hash
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
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(A,B) ENTRY TO REM. FUNCTION RETURN A-A/B*B END OF FUNCTION   INTERNAL FUNCTION(I) ENTRY TO DSUM. SUM = 0 REST = I DIGIT WHENEVER REST.NE.0 SUM = SUM + REM.(REST,10) REST = REST/10 TRANSFER TO DIGIT END OF CONDITIONAL FUNCTION RETURN SUM END OF FUNCTION   INTERNAL FUNCTION(I) ENTRY TO NEXT. LOOP THROUGH LOOP, FOR NX=I+1, 1, REM.(NX,DSUM.(NX)).E.0 FUNCTION RETURN NX END OF FUNCTION   PRINT COMMENT $ FIRST 20 HARSHAD NUMBERS:$ H = 0 N = 0 HARSHD WHENEVER N.LE.1000 N = NEXT.(N) H = H + 1 WHENEVER H.LE.20, PRINT FORMAT HSHD, H, N TRANSFER TO HARSHD END OF CONDITIONAL   PRINT FORMAT THSND, N   VECTOR VALUES HSHD = $8HHARSHAD(,I2,4H) = ,I2*$ VECTOR VALUES THSND = 0 $34HFIRST HARSHAD NUMBER ABOVE 1000 = ,I4*$   END OF PROGRAM
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
#GlovePIE
GlovePIE
debug="⡧⢼⣟⣋⣇⣀⣇⣀⣏⣹⠀⠀⣇⣼⣏⣹⡯⡽⣇⣀⣏⡱⢘⠀"
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
#GML
GML
draw_text(0,0,"Goodbye World!");
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#J
J
INTERACT=: noun define pc interact; cc Value edit center; cc increment button;cn "Increment"; cc random button;cn "Random"; pas 6 6;pcenter; )   interact_run=: verb define wd INTERACT wd 'set Value text 0;' wd 'pshow;' )   interact_cancel=: interact_close=: verb define wd'pclose' )   interact_Value_button=: verb define wd 'set Value text ' , ": {. 0 ". Value )   interact_increment_button=: verb define wd 'set Value text ' , ": 1 + {. 0 ". Value )   interact_random_button=: verb define if. 2 = 2 3 wdquery 'Confirm';'Reset to random number?' do. wd 'set Value text ' , ": ?100 end. )
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Java
Java
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;   import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField;   public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton;   public Interact(){ //stop the GUI threads when the user hits the X button setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random");   numberField.setText("0");//start at 0   //listen for button presses in the text field numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { //if the entered character is not a digit if(!Character.isDigit(e.getKeyChar())){ //eat the event (i.e. stop it from being processed) e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} });   //listen for button clicks on the increment button incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } });   //listen for button clicks on the random button randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { //show a dialog and if they answer "Yes" if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ //set the text field text to a random positive long numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } });   //arrange the components in a grid with 2 rows and 1 column setLayout(new GridLayout(2, 1));   //a secondary panel for arranging both buttons in one grid space in the window JPanel buttonPanel = new JPanel();   //the buttons are in a grid with 1 row and 2 columns buttonPanel.setLayout(new GridLayout(1, 2)); //add the buttons buttonPanel.add(incButton); buttonPanel.add(randButton);   //put the number field on top of the buttons add(numberField); add(buttonPanel); //size the window appropriately pack();   }   public static void main(String[] args){ new Interact().setVisible(true); } }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#ATS
ATS
  // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o hamming hamming.dats // #include "share/atspre_staload.hats"   fun min3 ( A: arrayref(int, 3) ) : natLt(3) = i where { var x: int = A[0] var i: natLt(3) = 0 val () = if A[1] < x then (x := A[1]; i := 1) val () = if A[2] < x then (x := A[2]; i := 2) } (* end of [min3] *)   fun hamming {n:pos} ( n: int(n) ) : int = let // var A = @[int](2, 3, 5) val A = $UNSAFE.cast{arrayref(int, 3)}(addr@A) var I = @[int](1, 1, 1) val I = $UNSAFE.cast{arrayref(int, 3)}(addr@I) val H = arrayref_make_elt<int> (i2sz(succ(n)), 0) val () = H[0] := 1 // fun loop{k:pos} (k: int(k)) : void = ( // if k < n then let val i = min3(A) val k = ( if A[i] > H[k-1] then (H[k] := A[i]; k+1) else k ) : intBtwe(k, k+1) val ii = I[i] val () = I[i] := ii+1 val ii = $UNSAFE.cast{natLte(n)}(ii) val () = if i = 0 then A[i] := 2*H[ii] val () = if i = 1 then A[i] := 3*H[ii] val () = if i = 2 then A[i] := 5*H[ii] in loop(k) end // end of [then] else () // end of [else] // ) (* end of [loop] *) // in loop (1); H[n-1] end (* end of [hamming] *)   implement main0 () = { val () = loop(1) where { fun loop {n:pos} ( n: int(n) ) : void = if n <= 20 then let val () = println! ("hamming(",n,") = ", hamming(n)) in loop(n+1) end // end of [then] // end of [if] } (* end of [val] *) val n = 1691 val () = println! ("hamming(",n,") = ", hamming(n)) // } (* end of [main0] *)  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#BASIC
BASIC
10 N% = RND(1) * 10 + 1 20 PRINT "A NUMBER FROM 1 "; 30 PRINT "TO 10 HAS BEEN "; 40 PRINT "RANDOMLY CHOSEN." 50 FOR Q = 0 TO 1 STEP 0 60 INPUT "ENTER A GUESS. "; G% 70 Q = G% = N% 80 NEXT 90 PRINT "WELL GUESSED!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#BASIC256
BASIC256
n = int(rand * 10) + 1 print "I am thinking of a number from 1 to 10" do input "Guess it > ",g if g <> n then print "No luck, Try again." endif until g = n print "Yea! You guessed my number."
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#AutoIt
AutoIt
  Local $iArray[11] = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] GREAT_SUB($iArray) Local $iArray[5] = [-1, -2, -3, -4, -5] GREAT_SUB($iArray) Local $iArray[15] = [7, -6, -8, 5, -2, -6, 7, 4, 8, -9, -3, 2, 6, -4, -6] GREAT_SUB($iArray)   Func GREAT_SUB($iArray) Local $iSUM = 0, $iBEGIN_MAX = 0, $iEND_MAX = -1, $iMAX_SUM = 0 For $i = 0 To UBound($iArray) - 1 $iSUM = 0 For $k = $i To UBound($iArray) - 1 $iSUM += $iArray[$k] If $iSUM > $iMAX_SUM Then $iMAX_SUM = $iSUM $iEND_MAX = $k $iBEGIN_MAX = $i EndIf Next Next ConsoleWrite("> Array: [") For $i = 0 To UBound($iArray) - 1 If $iArray[$i] > 0 Then ConsoleWrite("+") ConsoleWrite($iArray[$i]) If $i <> UBound($iArray) - 1 Then ConsoleWrite(",") Next ConsoleWrite("]" & @CRLF & "+>Maximal subsequence: [") $iSUM = 0 For $i = $iBEGIN_MAX To $iEND_MAX $iSUM += $iArray[$i] If $iArray[$i] > 0 Then ConsoleWrite("+") ConsoleWrite($iArray[$i]) If $i <> $iEND_MAX Then ConsoleWrite(",") Next ConsoleWrite("]" & @CRLF & "!>SUM of subsequence: " & $iSUM & @CRLF) EndFunc ;==>GREAT_SUB  
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.
#R
R
  library(gWidgets) options(guiToolkit="RGtk2") ## using gWidgtsRGtk2   w <- gwindow("Disable components")   g <- ggroup(cont=w, horizontal=FALSE) e <- gedit("0", cont=g, coerce.with=as.numeric) bg <- ggroup(cont=g)   down_btn <- gbutton("-", cont=bg) up_btn <- gbutton("+", cont=bg)   update_ctrls <- function(h,...) { val <- svalue(e) enabled(down_btn) <- val >= 0 enabled(up_btn) <- val <= 10 }   rement <- function(h,...) { svalue(e) <- svalue(e) + h$action update_ctrls(h,...) }   addHandlerChanged(e, handler=update_ctrls) addHandlerChanged(down_btn, handler=rement, action=-1) addHandlerChanged(up_btn, handler=rement, action=1)  
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#BBC_BASIC
BBC BASIC
Min% = 1 Max% = 10 chosen% = RND(Max%-Min%+1) + Min% - 1 REPEAT PRINT "Guess a number between "; Min% " and " ;Max% ; INPUT ": " guess% CASE TRUE OF WHEN guess% < Min% OR guess% > Max%: PRINT "That was an invalid number" WHEN guess% < chosen%: PRINT "Sorry, your number was too low" WHEN guess% > chosen%: PRINT "Sorry, your number was too high" OTHERWISE: PRINT "Well guessed!" EXIT REPEAT ENDCASE UNTIL FALSE END
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Go
Go
package main   import ( "github.com/fogleman/gg" "math" )   func greyBars(dc *gg.Context) { run := 0 colorComp := 0.0 // component of the color for colCount := 8; colCount < 128; colCount *= 2 { // by this gap we change the background color colorGap := 255.0 / float64(colCount-1) colWidth := float64(dc.Width() / colCount) colHeight := float64(dc.Height() / 4) // switches color directions with each iteration of for loop if run%2 == 0 { colorComp = 0.0 } else { colorComp = 255.0 colorGap = -colorGap } xstart, ystart := 0.0, colHeight*float64(run) for i := 0; i < colCount; i++ { icolor := int(math.Round(colorComp)) // round to nearer integer dc.SetRGB255(icolor, icolor, icolor) dc.DrawRectangle(xstart, ystart, colWidth, colHeight) dc.Fill() xstart += colWidth colorComp += colorGap } run++ } }   func main() { dc := gg.NewContext(640, 320) greyBars(dc) dc.SavePNG("greybars.png") }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Haskell
Haskell
import Graphics.UI.Gtk import Graphics.UI.Gtk.Gdk.GC import Control.Monad.Trans (liftIO)   -- click on the window to exit.   main = do initGUI   window <- windowNew   buf <- pixbufNewFromXPMData bars   widgetAddEvents window [ButtonPressMask] on window objectDestroy mainQuit on window exposeEvent (paint buf) on window buttonPressEvent $ liftIO $ do { widgetDestroy window; return True }   windowFullscreen window widgetShowAll window   mainGUI   paint :: Pixbuf -> EventM EExpose Bool paint buf = do pix <- eventWindow liftIO $ do (sx, sy) <- drawableGetSize pix newBuf <- pixbufScaleSimple buf sx sy InterpNearest gc <- gcNewWithValues pix newGCValues drawPixbuf pix gc newBuf 0 0 0 0 (-1) (-1) RgbDitherNone 0 0 return True   bars :: [String] bars = [ "64 4 65 1 1 1"," c None","A c #000000", "C c #080808","D c #0C0C0C","E c #101010","F c #141414", "G c #181818","H c #1C1C1C","I c #202020","J c #242424", "K c #282828","L c #2C2C2C","M c #303030","N c #343434", "O c #383838","P c #3C3C3C","Q c #404040","R c #444444", "S c #484848","T c #4C4C4C","U c #505050","V c #545454", "W c #585858","X c #5C5C5C","Y c #606060","Z c #646464", "a c #686868","b c #6C6C6C","c c #707070","d c #747474", "e c #787878","f c #7C7C7C","g c #808080","h c #848484", "i c #888888","j c #8C8C8C","k c #909090","l c #949494", "m c #989898","n c #9C9C9C","o c #A0A0A0","p c #A4A4A4", "q c #A8A8A8","r c #ACACAC","s c #B0B0B0","t c #B4B4B4", "u c #B8B8B8","v c #BCBCBC","w c #C0C0C0","x c #C4C4C4", "y c #C8C8C8","z c #CCCCCC","0 c #D0D0D0","1 c #D4D4D4", "2 c #D8D8D8","3 c #DCDCDC","4 c #E0E0E0","5 c #E4E4E4", "6 c #E8E8E8","7 c #ECECEC","8 c #F0F0F0","9 c #F4F4F4", ". c #F8F8F8","+ c #FCFCFC","* c #FFFFFF", "AAAAAAAAJJJJJJJJRRRRRRRRZZZZZZZZhhhhhhhhppppppppxxxxxxxx********", "****88881111xxxxttttppppllllhhhhddddZZZZVVVVRRRRNNNNJJJJFFFFAAAA", "AADDFFHHJJLLNNPPRRTTVVXXZZbbddffhhjjllnnpprrttvvxxzz11336688..**", "*+.9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCA" ]
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
#Haskell
Haskell
  main :: IO () main = do putStrLn "Please enter the range:" putStr "From: " from <- getLine putStr "To: " to <- getLine case (from, to) of (_) | [(from', "")] <- reads from , [(to' , "")] <- reads to , from' < to' -> loop from' to' (_) -> putStrLn "Invalid input." >> main   loop :: Integer -> Integer -> IO () loop from to = do let guess = (to + from) `div` 2 putStrLn $ "Is it " ++ show guess ++ "? ((l)ower, (c)orrect, (h)igher)" answer <- getLine case answer of "c" -> putStrLn "Awesome!" "l" -> loop from guess "h" -> loop guess to (_) -> putStrLn "Invalid answer." >> loop from to  
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
#Common_Lisp
Common Lisp
(defun sqr (n) (* n n))   (defun sum-of-sqr-dgts (n) (loop for i = n then (floor i 10) while (plusp i) sum (sqr (mod i 10))))   (defun happy-p (n &optional cache) (or (= n 1) (unless (find n cache) (happy-p (sum-of-sqr-dgts n) (cons n cache)))))   (defun happys (&aux (happys 0)) (loop for i from 1 while (< happys 8) when (happy-p i) collect i and do (incf happys)))   (print (happys))  
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.
#JavaScript
JavaScript
function haversine() { var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; }); var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3]; var R = 6372.8; // km var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.asin(Math.sqrt(a)); return R * c; } console.log(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
#XPath
XPath
'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
#XPL0
XPL0
code Text=12; Text(0, "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
#XSLT
XSLT
<xsl:text>Goodbye, World!</xsl:text>
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
#zkl
zkl
print("Goodbye, World!"); Console.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
#Zig
Zig
const std = @import("std");   pub fn main() !void { try std.io.getStdOut().writer().writeAll("Hello 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
#Frink
Frink
  println["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
#Smalltalk
Smalltalk
Array extend [ dictionaryWithValues: array [ |d| d := Dictionary new. 1 to: ((self size) min: (array size)) do: [:i| d at: (self at: i) put: (array at: i). ]. ^ d ] ].     ({ 'red' . 'one' . 'two' } dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.
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
#SNOBOL4
SNOBOL4
* # Fill arrays keys = array(5); vals = array(5) ks = 'ABCDE'; vs = '12345' kloop i = i + 1; ks len(1) . keys<i> = :s(kloop) vloop j = j + 1; vs len(1) . vals<j> = :s(vloop)   * # Create hash hash = table(5) hloop k = k + 1; hash<keys<k>> = vals<k> :s(hloop)   * # Test and display ts = 'ABCDE' tloop ts len(1) . ch = :f(out) str = str ch ':' hash<ch> ' ' :(tloop) out output = str end
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
#MATLAB_.2F_Octave
MATLAB / Octave
function v = isharshad(n) v = isinteger(n) && ~mod(n,sum(num2str(n)-'0')); end;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Go
Go
package main   import "github.com/mattn/go-gtk/gtk"   func main() { gtk.Init(nil) win := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) win.SetTitle("Goodbye, World!") win.SetSizeRequest(300, 200) win.Connect("destroy", gtk.MainQuit) button := gtk.NewButtonWithLabel("Goodbye, World!") win.Add(button) button.Connect("clicked", gtk.MainQuit) win.ShowAll() gtk.Main() }
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Julia
Julia
#= The task: For a minimal "application", write a program that presents a form with three components to the user: A numeric input field ("Value") and two buttons ("increment" and "random"). =#   using Tk   w = Toplevel("Component Interaction Example") fr = Frame(w) pack(fr, expand=true, fill="both")   value = Entry(fr, "") increment = Button(fr, "Increment") random = Button(fr, "Random")   formlayout(value, "Value:") formlayout(increment, " ") formlayout(random, " ")   set_value(value, "0") ## The field is initialized to zero.   incrementvalue(s) = (val = parse(Int, get_value(value)); set_value(value, string(val + 1))) bind(increment, "command", incrementvalue)   function validate_command(path, P) try length(P) > 0 && parse(Float64, P) tcl("expr", "TRUE") catch e tcl("expr", "FALSE") end end function invalid_command(path, W) println("Invalid value") tcl(W, "delete", "@0", "end") end   """ Pressing the "random" button presents a confirmation dialog and resets the field's value to a random value if the answer is "Yes". """ function randval(s) out = Messagebox(w, title="Randomize input", detail="Select a new random number?") if out == "ok" new_value = rand(collect(1:99)) set_value(value, string(new_value)) end end bind(random, "command", randval)   while true sleep(1); end  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Kotlin
Kotlin
import java.awt.GridLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.KeyListener import javax.swing.*   class Interact : JFrame() { val numberField = JTextField() val incButton = JButton("Increment") val randButton = JButton("Random") val buttonPanel = JPanel()   init { defaultCloseOperation = JFrame.EXIT_ON_CLOSE numberField.text = "0"   numberField.addKeyListener(object : KeyListener { override fun keyTyped(e : KeyEvent) : Unit { if (!Character.isDigit(e.keyChar)) e.consume() } override fun keyReleased(e : KeyEvent?) {} override fun keyPressed(e : KeyEvent) {} })   incButton.addActionListener { val num = (numberField.text ?: "").toDouble() numberField.text = (num + 1).toString() }   randButton.addActionListener(object : ActionListener { fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?") override fun actionPerformed(e : ActionEvent) { if(proceedOrNot() == JOptionPane.YES_OPTION) numberField.text = (Math.random() * Long.MAX_VALUE).toString() } })   layout = GridLayout(2, 1) buttonPanel.layout = GridLayout(1, 2) buttonPanel.add(incButton) buttonPanel.add(randButton) add(numberField) add(buttonPanel) pack() } }   fun main(args : Array<String>) { Interact().isVisible = true }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#AutoHotkey
AutoHotkey
SetBatchLines, -1 Msgbox % hamming(1,20) Msgbox % hamming(1690) return   hamming(first,last=0) { if (first < 1) ans=ERROR   if (last = 0) last := first   i:=0, j:=0, k:=0   num1 := ceil((last * 20)**(1/3)) num2 := ceil(num1 * ln(2)/ln(3)) num3 := ceil(num1 * ln(2)/ln(5))   loop { H := (2**i) * (3**j) * (5**k) if (H > 0) ans = %H%`n%ans% i++ if (i > num1) { i=0 j++ if (j > num2) { j=0 k++ } } if (k > num3) break } Sort ans, N   Loop, parse, ans, `n, `r { if (A_index > last) break if (A_index < first) continue Output = %Output%`n%A_LoopField% }   return Output }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Batch_File
Batch File
@echo off set /a answer=%random%%%(10-1+1)+1 set /p guess=Pick a number between 1 and 10: :loop if %guess%==%answer% (echo Well guessed! pause) else (set /p guess=Nope, guess again: goto loop)
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#BBC_BASIC
BBC BASIC
choose% = RND(10) REPEAT INPUT "Guess a number between 1 and 10: " guess% IF guess% = choose% THEN PRINT "Well guessed!" END ELSE PRINT "Sorry, try again" ENDIF UNTIL FALSE
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#AWK
AWK
# Finds the subsequence of ary[1] to ary[len] with the greatest sum. # Sets subseq[1] to subseq[n] and returns n. Also sets subseq["sum"]. # An empty subsequence has sum 0. function maxsubseq(subseq, ary, len, b, bp, bs, c, cp, i) { b = 0 # best sum c = 0 # current sum bp = 0 # position of best subsequence bn = 0 # length of best subsequence cp = 1 # position of current subsequence   for (i = 1; i <= len; i++) { c += ary[i] if (c < 0) { c = 0 cp = i + 1 } if (c > b) { b = c bp = cp bn = i + 1 - cp } }   for (i = 1; i <= bn; i++) subseq[i] = ary[bp + i - 1] subseq["sum"] = b return bn }
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.
#Racket
Racket
  #lang racket/gui   (define frame (new frame% [label "Interaction Demo"]))   (define (changed . _) (define s (send inp get-value)) (define v (string->number s)) (unless v (set! v (or (string->number (regexp-replace* #rx"[^0-9]+" s "")) 0)) (send inp set-value (~a v))) (send inc-b enable (< v 10)) (send dec-b enable (> v 0)) (send inp enable (zero? v))) (define ((change-value f) . _) (send inp set-value (number->string (f (string->number (send inp get-value))))) (changed))   (define inp (new text-field% [label "Value"] [parent frame] [init-value "0"] [callback changed]))   (define buttons (new horizontal-pane% [parent frame])) (define inc-b (new button% [parent buttons] [label "Increment"] [callback (change-value add1)])) (define dec-b (new button% [parent buttons] [label "Decrement"] [callback (change-value sub1)]))   (send frame show #t)  
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.
#Raku
Raku
use GTK::Simple; use GTK::Simple::App;   my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );   $app.set-content( my $box = GTK::Simple::HBox.new( my $inc = GTK::Simple::Button.new( label => ' + ' ), my $value = GTK::Simple::Entry.new, my $dec = GTK::Simple::Button.new( label => ' - ' ) ) );   $app.border-width = 10; $box.spacing = 10;   $value.changed.tap: { $value.text.=subst(/\D/, ''); $inc.sensitive = $value.text < 10; $dec.sensitive = $value.text > 0; }   $value.text = '0';   $inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str } $dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str }   $app.run;
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#BCPL
BCPL
get "libhdr" static $( randstate = ? $)   let rand(min,max) = valof $( let x = ? let range = max-min let mask = 1 while mask < range do mask := (mask << 1) | 1 $( randstate := random(randstate) x := (randstate >> 6) & mask $) repeatuntil 0 <= x < range resultis x + min $)   let readguess(min,max) = valof $( let x = ? writes("Guess? ") x := readn() if min <= x < max then resultis x writes("Invalid input.*N") $) repeat   let play(min,max,secret) be $( let tries, guess = 0, ? $( guess := readguess(min,max) if guess < secret then writes("Too low!*N") if guess > secret then writes("Too high!*N") tries := tries + 1 $) repeatuntil guess = secret writef("Correct! You guessed it in %N tries.*N", tries) $)   let start() be $( let min, max = ?, ? writes("Guess the number*N*N") writes("Random seed? ") ; randstate := readn() $( writes("Lower bound? ") ; min := readn() writes("Upper bound? ") ; max := readn() + 1 test max-1 > min break or writes("Invalid bounds.*N") $) repeat wrch('*N') play(min, max, rand(min, max)) $)
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Icon_and_Unicon
Icon and Unicon
link graphics,printf,numbers   procedure main() DrawTestCard(GreyScale_TestCard()) WDone() end   procedure greyscale(l,h,s) #: generate s greys over range l:h every i := round(l to h+1 by ((h-l)/(s-1.))) do suspend sprintf("%d,%d,%d",i,i,i) # return rgb black-grey-white end   procedure GreyScale_TestCard() #: return greyscale testcard TC := testcard(,"GreyScale Test Card", width := 800, height := 600, list(numbands := 4) ) maxv := 2^16-1 # largest colour value every (iv := [], i := 1 to numbands) do { # for each band every put(v := [], greyscale(0,maxv,2^(2+i))) # compute greyscale put(iv, if i%2 = 0 then v else reverse(v)) # switch directions }   every r := height/numbands * ((i := 1 to numbands)-1) + 1 do { TC.bands[i] := band(r,[]) every c := width/(*iv[i]) * ((j := 1 to *iv[i])-1) + 1 do put(TC.bands[i].bars, bar( c, iv[i,j])) put((TC.bands[i]).bars, bar(width)) # right sentinal } put(TC.bands,band(height)) # bottom sentinal return TC 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
#Icon_and_Unicon
Icon and Unicon
  procedure main () lower_limit := 1 higher_limit := 100   write ("Think of a number between 1 and 100") write ("Press 'enter' when ready") read ()   repeat { if (higher_limit < lower_limit) then { # check that player is not cheating! write ("Something has gone wrong ... I give up") exit () } my_guess := (higher_limit + lower_limit) / 2 write ("My guess is ", my_guess) write ("Enter 'H' if your number is higher, 'L' if lower, or 'E' if equal") reply := map(trim(read ())) case (reply) of { "e" : { write ("I got it correct - thankyou!") exit () # game over } "h" : lower_limit := my_guess + 1 "l" : higher_limit := my_guess - 1 default : write ("Pardon? Let's try that again") } } end  
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Cowgol
Cowgol
include "cowgol.coh";   sub sumDigitSquare(n: uint8): (s: uint8) is s := 0; while n != 0 loop var d := n % 10; s := s + d * d; n := n / 10; end loop; end sub;   sub isHappy(n: uint8): (h: uint8) is var seen: uint8[256]; MemZero(&seen[0], @bytesof seen);   while seen[n] == 0 loop seen[n] := 1; n := sumDigitSquare(n); end loop;   if n == 1 then h := 1; else h := 0; end if; end sub;   var n: uint8 := 1; var seen: uint8 := 0;   while seen < 8 loop if isHappy(n) != 0 then print_i8(n); print_nl(); seen := seen + 1; end if; n := n + 1; end loop;
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.
#jq
jq
def haversine(lat1;lon1; lat2;lon2): def radians: . * (1|atan)/45; def sind: radians|sin; def cosd: radians|cos; def sq: . * .;   (((lat2 - lat1)/2) | sind | sq) as $dlat | (((lon2 - lon1)/2) | sind | sq) as $dlon | 2 * 6372.8 * (( $dlat + (lat1|cosd) * (lat2|cosd) * $dlon ) | sqrt | asin) ;
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.
#Jsish
Jsish
/* Haversine formula, in Jsish */ function haversine() { var radians = arguments.map(function(deg) { return deg/180.0 * Math.PI; }); var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3]; var R = 6372.8; // km var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.asin(Math.sqrt(a)); return R * c; }   ;haversine(36.12, -86.67, 33.94, -118.40);   /* =!EXPECTSTART!= haversine(36.12, -86.67, 33.94, -118.40) ==> 2887.259950607112 =!EXPECTEND!= */
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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM The trailing semicolon prevents a newline 20 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
#FunL
FunL
println( '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
#Sparkling
Sparkling
let keys = { "foo", "bar", "baz" }; let vals = { 13, 37, 42 }; var hash = {}; for var i = 0; i < sizeof keys; i++ { hash[keys[i]] = vals[i]; }
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
#Standard_ML
Standard ML
structure StringMap = BinaryMapFn (struct type ord_key = string val compare = String.compare end);   val keys = [ "foo", "bar", "baz" ] and vals = [ 16384, 32768, 65536 ] and myMap = StringMap.empty;   val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));
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
#Modula-2
Modula-2
MODULE Harshad; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   VAR n, i: CARDINAL;   PROCEDURE DigitSum(n: CARDINAL): CARDINAL; VAR sum: CARDINAL; BEGIN sum := 0; WHILE n > 0 DO; sum := sum + n MOD 10; n := n DIV 10; END; RETURN sum; END DigitSum;   PROCEDURE NextHarshad(n: CARDINAL): CARDINAL; BEGIN REPEAT INC(n); UNTIL n MOD DigitSum(n) = 0; RETURN n; END NextHarshad;   BEGIN n := 0; WriteString("First 20 Harshad numbers:"); WriteLn(); FOR i := 1 TO 20 DO n := NextHarshad(n); WriteCard(n, 3); END; WriteLn(); WriteString("First Harshad number above 1000: "); WriteCard(NextHarshad(1000), 4); WriteLn(); END Harshad.
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
#Groovy
Groovy
import groovy.swing.SwingBuilder import javax.swing.JFrame   new SwingBuilder().edt { optionPane().showMessageDialog(null, "Goodbye, World!") frame(title:'Goodbye, World!', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show: true) { flowLayout() button(text:'Goodbye, World!') textArea(text:'Goodbye, World!') } }  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Lambdatalk
Lambdatalk
  {input {@ id="input" type="text" value="0"}} {input {@ type="button" value="increment" onclick="document.getElementById('input').value = parseInt( document.getElementById('input').value ) + 1;"}} {input {@ type="button" value="random" onclick="if (confirm( 'yes?' )) document.getElementById('input').value = Math.round(Math.random()*100);"}}  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Liberty_BASIC
Liberty BASIC
nomainwin textbox #demo.val, 20, 50, 90, 24 button #demo.inc, "Increment", [btnIncrement], UL, 20, 90, 90, 24 button #demo.rnd, "Random", [btnRandom], UL, 20, 120, 90, 24 open "Rosetta Task: GUI component interaction" for window as #demo #demo "trapclose [quit]" validNum$ = "0123456789." #demo.val 0 wait   [quit] close #demo end   [btnIncrement] #demo.val "!contents? nVal$" nVal$ = trim$(nVal$) if left$(nVal$, 1) = "-" then neg = 1 nVal$ = mid$(nVal$, 2) else neg = 0 end if validNum = 1 nDecs = 0 for i = 1 to len(nVal$) if instr(validNum$, mid$(nVal$, i, 1)) = 0 then validNum = 0 end if if mid$(nVal$, i, 1) = "." then nDecs = nDecs + 1 end if next i if nDecs > 1 then validNum = 0 end if if neg = 1 then nVal$ = "-";nVal$ end if if validNum = 0 then notice nVal$;" does not appear to be a valid number. " + _ "(Commas are not allowed.)" else nVal = val(nVal$) nVal = nVal + 1 end if #demo.val nVal wait   [btnRandom] confirm "Reset value to random number";yn$ if yn$ = "yes" then nVal = int(rnd(1) * 100) + 1 #demo.val nVal end if wait
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#11l
11l
T Colour Byte r, g, b   F (r, g, b) .r = r .g = g .b = b   F ==(other) R .r == other.r & .g == other.g & .b == other.b   V black = Colour(0, 0, 0) V white = Colour(255, 255, 255)   T Bitmap Int width, height Colour background [[Colour]] map   F (width = 40, height = 40, background = white) assert(width > 0 & height > 0) .width = width .height = height .background = background .map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))   F fillrect(x, y, width, height, colour = black) assert(x >= 0 & y >= 0 & width > 0 & height > 0) L(h) 0 .< height L(w) 0 .< width .map[y + h][x + w] = colour   F set(x, y, colour = black) .map[y][x] = colour   F get(x, y) R .map[y][x]   F togreyscale() L(h) 0 .< .height L(w) 0 .< .width V (r, g, b) = .get(w, h) V l = Int(0.2126 * r + 0.7152 * g + 0.0722 * b) .set(w, h, Colour(l, l, l))   F writeppmp3() V magic = "P3\n" V comment = "# generated from Bitmap.writeppmp3\n" V s = magic‘’comment‘’("#. #.\n#.\n".format(.width, .height, 255)) L(h) (.height - 1 .< -1).step(-1) L(w) 0 .< .width V (r, g, b) = .get(w, h) s ‘’= ‘ #3 #3 #3’.format(r, g, b) s ‘’= "\n" R s   V bitmap = Bitmap(4, 4, white) bitmap.fillrect(1, 0, 1, 2, Colour(127, 0, 63)) bitmap.set(3, 3, Colour(0, 127, 31)) print(‘Colour:’) print(bitmap.writeppmp3()) print(‘Grey:’) bitmap.togreyscale() print(bitmap.writeppmp3())
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#AWK
AWK
  # syntax: gawk -M -f hamming_numbers.awk BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return(h[limit-1]) } function min(x,y) { return((x < y) ? x : y) }  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Befunge
Befunge
v RNG anthouse > v ,,,,,,< v?v , vvvvv , v?????v , vvvvvvvvv , >?????????v , >vvvvvvvvvv< , >??????????< , >vvvvvvvvvv< , >??????????< , >vvvvvvvvvv< ^"Well guessed!"< >??????????< >"oN",,91v actual game unit 1234567899 ^_91+"!" ^ 1 ^-g22<&<>+,v +>,,,,,,,,,,,,,,,,^ >>>>>>>>>v^"guessthenumber!"+19< RNG unit > 22p ^
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Bracmat
Bracmat
( ( GuessTheNumber = mynumber . clk$:?mynumber & mod$(!mynumber*den$!mynumber.10)+1:?mynumber & whl ' ( put'"Guess my number:" & get':~!mynumber:?K ) & out'"Well guessed!" ) & GuessTheNumber$ );
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#BBC_BASIC
BBC BASIC
DIM A%(11) : A%() = 0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2 PRINT FNshowarray(A%()) " -> " FNmaxsubsequence(A%()) DIM B%(10) : B%() = -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 PRINT FNshowarray(B%()) " -> " FNmaxsubsequence(B%()) DIM C%(4) : C%() = -1, -2, -3, -4, -5 PRINT FNshowarray(C%()) " -> " FNmaxsubsequence(C%()) END   DEF FNmaxsubsequence(a%()) LOCAL a%, b%, i%, j%, m%, s%, a$ a% = 1 FOR i% = 0 TO DIM(a%(),1) s% = 0 FOR j% = i% TO DIM(a%(),1) s% += a%(j%) IF s% > m% THEN m% = s% a% = i% b% = j% ENDIF NEXT NEXT i% IF a% > b% THEN = "[]" a$ = "[" FOR i% = a% TO b% a$ += STR$(a%(i%)) + ", " NEXT = LEFT$(LEFT$(a$)) + "]"   DEF FNshowarray(a%()) LOCAL i%, a$ a$ = "[" FOR i% = 0 TO DIM(a%(),1) a$ += STR$(a%(i%)) + ", " NEXT = LEFT$(LEFT$(a$)) + "]"
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Bracmat
Bracmat
  ( 0:?max & :?seq & -1 -2 3 5 6 -2 -1 4 -4 2 -1  :  ? [%( ( = s sum . ( sum = A .  !arg:%?A ?arg&!A+sum$!arg | 0 ) & ( sum$!sjt:>!max:?max & !sjt:?seq | ) ) $ & ~ )  ? | !seq )  
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.
#Red
Red
Red[]   enable: does [ f/enabled?: 0 = n i/enabled?: 10 > n d/enabled?: 0 < n ]   view [ f: field "0" [either error? try [n: to-integer f/text] [f/text: "0"] [enable]] i: button "increment" [f/text: mold n: add to-integer f/text 1 enable] d: button "decrement" disabled [f/text: mold n: subtract to-integer f/text 1 enable] ]
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Befunge
Befunge
1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v <*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1? \1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+> :#,_@>"ess" >"eug uoY">
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#J
J
load 'viewmat' size=. 2{.".wd'qm' NB. J6 size=. getscreenwh_jgtk_ '' NB. J7 rows=. (2^3+i.4),._1^i.4 bars=. ((64%{.)#[:(<:@|%~i.)*/)"1 rows togreyscale=. (256#. [:<.255 255 255&*)"0 'rgb' viewmat (4<.@%~{:size)# (64<.@%~{.size)#"1 togreyscale bars
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Java
Java
import javax.swing.* ; import java.awt.* ;   public class Greybars extends JFrame { private int width ; private int height ;   public Greybars( ) { super( "grey bars example!" ) ; width = 640 ; height = 320 ; setSize( width , height ) ; setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ; setVisible( true ) ; }   public void paint ( Graphics g ) { int run = 0 ; double colorcomp = 0.0 ; //component of the color for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) { double colorgap = 255.0 / (columncount - 1) ; //by this gap we change the background color int columnwidth = width / columncount ; int columnheight = height / 4 ; if ( run % 2 == 0 ) //switches color directions with every for loop colorcomp = 0.0 ; else { colorcomp = 255.0 ; colorgap *= -1.0 ; } int ystart = 0 + columnheight * run ; int xstart = 0 ; for ( int i = 0 ; i < columncount ; i++ ) { int icolor = (int)Math.round(colorcomp) ; //round to nearer integer Color nextColor = new Color( icolor , icolor, icolor ) ; g.setColor( nextColor ) ; g.fillRect( xstart , ystart , columnwidth , columnheight ) ; xstart += columnwidth ; colorcomp += colorgap ; } run++ ; } }   public static void main( String[ ] args ) { Greybars gb = new Greybars( ) ; } }
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
#IS-BASIC
IS-BASIC
100 PROGRAM "GuessIt.bas" 110 LET N=100 120 TEXT 80 130 PRINT "Choose a number between 1 and;" N:PRINT "I will start guess the number." 140 LET BL=1:LET UL=100:LET NR=0 150 DO 160 LET GUESS=INT((BL+UL)/2):LET NR=NR+1 170 SET #102:INK 3:PRINT :PRINT "My";NR;". guess: ";GUESS:SET #102:INK 1 180 LET ANSWER=QUESTION 190 SELECT CASE ANSWER 200 CASE 1 210 LET UL=GUESS-1 220 CASE 2 230 LET BL=GUESS+1 240 CASE ELSE 250 END SELECT 260 IF BL>UL THEN PRINT "You are cheating!":LET ANSWER=9 270 LOOP UNTIL ANSWER=0 OR ANSWER=9 280 PRINT "So the number is:" GUESS 290 DEF QUESTION 300 PRINT "Your number: 1 - Is lower?; 2 - Is higher?; 0 - Is equal?" 310 DO 320 LET K$=INKEY$ 330 LOOP UNTIL K$>="0" AND K$<="3" 340 LET QUESTION=VAL(K$) 350 END DEF