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/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).
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB2" INSTALL @lib$+"WINLIB5"   IDYES = 6 ES_NUMBER = 8192 MB_YESNO = 4   form% = FN_newdialog("Rosetta Code", 100, 100, 100, 52, 8, 1000) PROC_static(form%, "Value:", 100, 10, 10, 24, 14, 0) PROC_editbox(form%, "0", 101, 40, 8, 52, 14, ES_NUMBER) PROC_pushbutton(form%, "Increment", FN_setproc(PROCinc), 7, 30, 40, 16, 0) PROC_pushbutton(form%, "Random", FN_setproc(PROCrandom), 52, 30, 40, 16, 0) PROC_showdialog(form%)   REPEAT WAIT 1 UNTIL !form% = 0 QUIT   DEF PROCinc LOCAL number% SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number% SYS "SetDlgItemInt", !form%, 101, number% + 1, 1 ENDPROC   DEF PROCrandom LOCAL reply% SYS "MessageBox", !form%, "Set to a random value?", "Confirm", MB_YESNO TO reply% IF reply% = IDYES THEN SYS "SetDlgItemInt", !form%, 101, RND(10000), 1 ENDPROC
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.
#Julia
Julia
  using Tk w = Toplevel("GUI enabling/disabling") fr = Frame(w) pack(fr, {:expand=>true, :fill => "both"})   value = Entry(fr) increment = Button(fr, "+") decrement = Button(fr, "-")   formlayout(value, "Value:") formlayout(increment, " ") formlayout(decrement, " ")   ## value stores a string set_value(value, "0") ## The field is initialized to zero. get(value::Tk_Entry) = try parseint(get_value(value)) catch e nothing end   function update() cur_value = get(value) set_enabled(value, isa(cur_value, Integer) && cur_value == 0) set_enabled(increment, isa(cur_value, Integer) && cur_value < 10) set_enabled(decrement, isa(cur_value, Integer) && cur_value > 0) end   crement = function(step) set_enabled(value, true) set_value(value, string(get(value) + step)) update() end tk_bind(increment, "command", path -> crement(1)) tk_bind(decrement, "command", path -> crement(-1)) update()   function validate_command(path, P) try if length(P) > 0 parseint(P); update() end tcl("expr", "TRUE") catch e tcl("expr", "FALSE") end end function invalid_command(path, W) println("Invalid value") tcl(W, "delete", "@0", "end") end   tk_configure(value, {:validate=>"focusout", :validatecommand=>validate_command, :invalidcommand=>invalid_command })      
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.
#Kotlin
Kotlin
// version 1.2.21   import javafx.application.Application import javafx.beans.property.SimpleLongProperty import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.control.TextField import javafx.scene.layout.HBox import javafx.scene.layout.VBox import javafx.stage.Stage import javafx.util.converter.NumberStringConverter import javafx.event.ActionEvent   val digits = Regex("[0-9]*")   class InteractFX : Application() {   override fun start(stage: Stage) { val input = object : TextField("0") { // only accept numbers as input override fun replaceText(start: Int, end: Int, text: String) { if (text.matches(digits)) super.replaceText(start, end, text) }   // only accept numbers on copy + paste override fun replaceSelection(text: String) { if (text.matches(digits)) super.replaceSelection(text) } }   // when the textfield is empty, replace text with "0" input.textProperty().addListener { _, _, newValue -> if (newValue == null || newValue.trim().isEmpty()) input.text = "0" }   // get a bi-directional bound long-property of the input value val inputValue = SimpleLongProperty() input.textProperty().bindBidirectional(inputValue, NumberStringConverter())   // textfield is disabled when the current value is other than "0" input.disableProperty().bind(inputValue.isNotEqualTo(0))   val increment = Button("Increment") increment.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() + 1) }   // increment button is disabled when input is >= 10 increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10))   val decrement = Button("Decrement") decrement.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() - 1) }   // decrement button is disabled when input is <= 0 decrement.disableProperty().bind(inputValue.lessThanOrEqualTo(0))   // layout val root = VBox() root.children.add(input) val buttons = HBox() buttons.children.addAll(increment, decrement) root.children.add(buttons)   stage.scene = Scene(root) stage.sizeToScene() stage.show() } }   fun main(args: Array<String>) { Application.launch(InteractFX::class.java, *args) }
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; //Remember to add this if you want the game to pause in RealisticGuess.Start()   namespace ConsoleApplication1 { class RealisticGuess //Simulates a guessing game between two people. Guessing efficiency is not a goal. { private int max; private int min; private int guess;   public void Start() { Console.Clear(); string input;   try { Console.WriteLine("Please enter the lower boundary"); input = Console.ReadLine(); min = Convert.ToInt32(input); Console.WriteLine("Please enter the upper boundary"); input = Console.ReadLine(); max = Convert.ToInt32(input); } catch (FormatException) { Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); Console.ReadKey(true); Start(); } Console.WriteLine("Think of a number between {0} and {1}.", min, max); Thread.Sleep(2500); Console.WriteLine("Ready?"); Console.WriteLine("Press any key to begin."); Console.ReadKey(true); Guess(min, max); } public void Guess(int min, int max) { int counter = 1; string userAnswer; bool correct = false; Random rand = new Random();   while (correct == false) { guess = rand.Next(min, max); Console.Clear(); Console.WriteLine("{0}", guess); Console.WriteLine("Is this number correct? {Y/N}"); userAnswer = Console.ReadLine(); if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") { Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); Console.WriteLine("Is the number correct? {Y/N}"); userAnswer = Console.ReadLine(); } if (userAnswer == "y" || userAnswer == "Y") { correct = true; } if (userAnswer == "n" || userAnswer == "N") { counter++; if (max == min) { Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); //This message should never pop up if the user enters good data. Console.ReadKey(true); //It handles the game-breaking exception that occurs Guess(1, 101); //when the max guess number is the same as the min number. } Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") { Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); } if (userAnswer == "l" || userAnswer == "L") { max = guess; } if (userAnswer == "h" || userAnswer == "H") { min = guess; } } } if (correct == true) { EndAndLoop(counter); } }   public void EndAndLoop(int iterations) { string userChoice; bool loop = false; Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); while (loop == false) { Console.WriteLine("Would you like to play again? {Y/N}"); userChoice = Console.ReadLine(); if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") { Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); } if (userChoice == "Y" || userChoice == "y") { Start(); } if (userChoice == "N" || userChoice == "n") { Environment.Exit(1); } } } } class Program { static void Main(string[] args) { Console.Title = "Random Number"; RealisticGuess game = new RealisticGuess(); game.Start(); } } }  
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
#Batch_File
Batch File
@echo off setlocal enableDelayedExpansion ::Define a list with 10 terms as a convenience for defining a loop set "L10=0 1 2 3 4 5 6 7 8 9" shift /1 & goto %1 exit /b     :list min count :: This routine prints all happy numbers > min (arg1) :: until it finds count (arg2) happy numbers. set /a "n=%~1, cnt=%~2" call :listInternal exit /b     :test min [max] :: This routine sequentially tests numbers between min (arg1) and max (arg2) :: to see if they are happy. If max is not specified then it defaults to min. set /a "min=%~1" if "%~2" neq "" (set /a "max=%~2") else set max=%min% ::The FOR /L loop does not detect integer overflow, so must protect against ::an infinite loop when max=0x7FFFFFFFF set end=%max% if %end% equ 2147483647 set /a end-=1 for /l %%N in (%min% 1 %end%) do ( call :testInternal %%N && (echo %%N is happy :^)) || echo %%N is sad :( ) if %end% neq %max% call :testInternal %max% && (echo %max% is happy :^)) || echo %max% is sad :( exit /b      :listInternal  :: This loop sequentially tests each number >= n. The loop conditionally  :: breaks within the body once cnt happy numbers have been found, or if  :: the max integer value is reached. Performance is improved by using a  :: FOR loop to perform most of the looping, with a GOTO only needed once  :: per 100 iterations. for %%. in ( %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% ) do ( call :testInternal !n! && ( echo !n! set /a cnt-=1 if !cnt! leq 0 exit /b 0 ) if !n! equ 2147483647 ( >&2 echo ERROR: Maximum integer value reached exit /b 1 ) set /a n+=1 ) goto :listInternal      :testInternal n  :: This routine loops until the sum of squared digits converges on 1 (happy)  :: or it detects a cycle (sad). It exits with errorlevel 0 for happy and 1 for sad.  :: Performance is improved by using a FOR loop for the looping instead of a GOTO.  :: Numbers less than 1000 never neeed more than 20 iterations, and any number  :: with 4 or more digits shrinks by at least one digit each iteration.  :: Since Windows batch can't handle more than 10 digits, allowance for 27  :: iterations is enough, and 30 is more than adequate. setlocal set n=%1 for %%. in (%L10% %L10% %L10%) do ( if !n!==1 exit /b 0 %= Only numbers < 1000 can cycle =% if !n! lss 1000 ( if defined t.!n! exit /b 1 set t.!n!=1 ) %= Sum the squared digits =% %= Batch can't handle numbers greater than 10 digits so we can use =% %= a constrained FOR loop and avoid a slow goto =% set sum=0 for /l %%N in (1 1 10) do ( if !n! gtr 0 set /a "sum+=(n%%10)*(n%%10), n/=10" ) set /a n=sum )
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.
#Forth
Forth
: s>f s>d d>f ; : deg>rad 174532925199433e-16 f* ; : difference f- deg>rad 2 s>f f/ fsin fdup f* ;   : haversine ( lat1 lon1 lat2 lon2 -- haversine) frot difference ( lat1 lat2 dLon^2) frot frot fover fover ( dLon^2 lat1 lat2 lat1 lat2) fswap difference ( dLon^2 lat1 lat2 dLat^2) fswap deg>rad fcos ( dLon^2 lat1 dLat^2 lat2) frot deg>rad fcos f* ( dLon^2 dLat2 lat1*lat2) frot f* f+ ( lat1*lat2*dLon^2+dLat^2) fsqrt fasin 127456 s>f f* 10 s>f f/ ( haversine) ;   36.12e -86.67e 33.94e -118.40e haversine cr f.
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
#PicoLisp
PicoLisp
(prin "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
#Pict
Pict
(pr "Hello 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
#Pike
Pike
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
#Pixilang
Pixilang
fputs("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
#ferite
ferite
uses "console"; Console.println( "Goodby, 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
#Picat
Picat
go => A = [a,b,c,d,e], B = [1,2,3,4,5], Map = new_map([K=V : {K,V} in zip(A,B)]), println(Map).
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
#PicoLisp
PicoLisp
(let (Keys '(one two three) Values (1 2 3)) (mapc println (mapcar cons Keys Values) ) )
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
#IS-BASIC
IS-BASIC
100 PROGRAM "Harshad.bas" 110 LET I=1:LET CNT=0 120 PRINT "First 20 Harshad numbers are:" 130 DO 140 IF HARSHAD(I) THEN PRINT I;:LET CNT=CNT+1 150 LET I=I+1 160 LOOP UNTIL CNT=20 170 PRINT :PRINT :PRINT "First Harshad number larger than 1000 is";:LET I=1001 180 DO 190 IF HARSHAD(I) THEN PRINT I:EXIT DO 200 LET I=I+1 210 LOOP 220 DEF HARSHAD(NUM) 230 LET TMP=NUM:LET SUM=0 240 DO WHILE TMP>0 250 LET SUM=SUM+MOD(TMP,10) 260 LET TMP=INT(TMP/10) 270 LOOP 280 LET HARSHAD=MOD(NUM,SUM)=0 290 END DEF
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
#EasyLang
EasyLang
move 10 20 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).
#C
C
file main.c
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).
#C.2B.2B
C++
file interaction.h
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.
#Liberty_BASIC
Liberty BASIC
nomainwin textbox #demo.val, 20, 50, 90, 24 button #demo.dec, "Decrement", [btnDecrement], UL, 20, 90, 90, 24 button #demo.inc, "Increment", [btnIncrement], UL, 20, 120, 90, 24 statictext #demo.txt, "Positive or negative whole numbers only.", 20, 170, 240, 24 open "Rosetta Task: GUI enabling/disabling of controls" for window as #demo #demo "trapclose [quit]" #demo.val 0 #demo.dec "!disable" wait   [quit] close #demo end   [btnDecrement] validNum = validNum() if validNum = 0 then #demo.val "!contents? nVal$" notice nVal$;" does not appear to be a valid whole number." else #demo.val "!contents? nVal" if nVal > 0 then nVal = nVal - 1 end if end if #demo.val nVal call disEnableControls nVal wait   [btnIncrement] validNum = validNum() if validNum = 0 then #demo.val "!contents? nVal$" notice nVal$;" does not appear to be a valid whole number." else #demo.val "!contents? nVal" if nVal < 10 then nVal = nVal + 1 end if end if #demo.val nVal call disEnableControls nVal wait   Function validNum() validNum$ = "0123456789" #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 for i = 1 to len(nVal$) if instr(validNum$, mid$(nVal$, i, 1)) = 0 then validNum = 0 end if next i End Function   Sub disEnableControls nVal if nVal > 9 then #demo.inc "!disable" else #demo.inc "!enable" end if if nVal < 1 then #demo.dec "!disable" else #demo.dec "!enable" end if if nVal = 0 then #demo.val "!enable" else #demo.val "!disable" end if End Sub
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
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <string> #include <iterator>   struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> { int i; GuessNumberIterator() { } GuessNumberIterator(int _i) : i(_i) { } GuessNumberIterator& operator++() { ++i; return *this; } GuessNumberIterator operator++(int) { GuessNumberIterator tmp = *this; ++(*this); return tmp; } bool operator==(const GuessNumberIterator& y) { return i == y.i; } bool operator!=(const GuessNumberIterator& y) { return i != y.i; } int operator*() { std::cout << "Is your number less than or equal to " << i << "? "; std::string s; std::cin >> s; return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1; } GuessNumberIterator& operator--() { --i; return *this; } GuessNumberIterator operator--(int) { GuessNumberIterator tmp = *this; --(*this); return tmp; } GuessNumberIterator& operator+=(int n) { i += n; return *this; } GuessNumberIterator& operator-=(int n) { i -= n; return *this; } GuessNumberIterator operator+(int n) { GuessNumberIterator tmp = *this; return tmp += n; } GuessNumberIterator operator-(int n) { GuessNumberIterator tmp = *this; return tmp -= n; } int operator-(const GuessNumberIterator &y) { return i - y.i; } int operator[](int n) { return *(*this + n); } bool operator<(const GuessNumberIterator &y) { return i < y.i; } bool operator>(const GuessNumberIterator &y) { return i > y.i; } bool operator<=(const GuessNumberIterator &y) { return i <= y.i; } bool operator>=(const GuessNumberIterator &y) { return i >= y.i; } }; inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }   const int lower = 0; const int upper = 100;   int main() { std::cout << "Instructions:\n" << "Think of integer number from " << lower << " (inclusive) to " << upper << " (exclusive) and\n" << "I will guess it. After each guess, I will ask you if it is less than\n" << "or equal to some number, and you will respond with \"yes\" or \"no\".\n"; int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i; std::cout << "Your number is " << answer << ".\n"; return 0; }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#BBC_BASIC
BBC BASIC
number% = 0 total% = 0 REPEAT number% += 1 IF FNhappy(number%) THEN PRINT number% " is a happy number" total% += 1 ENDIF UNTIL total% = 8 END   DEF FNhappy(num%) LOCAL digit&() DIM digit&(10) REPEAT digit&() = 0 $$^digit&(0) = STR$(num%) digit&() AND= 15 num% = MOD(digit&())^2 + 0.5 UNTIL num% = 1 OR num% = 4 = (num% = 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.
#Fortran
Fortran
  program example implicit none real :: d   d = haversine(36.12,-86.67,33.94,-118.40) ! BNA to LAX print '(A,F9.4,A)', 'distance: ',d,' km' ! distance: 2887.2600 km   contains   function to_radian(degree) result(rad) ! degrees to radians real,intent(in) :: degree real, parameter :: deg_to_rad = atan(1.0)/45 ! exploit intrinsic atan to generate pi/180 runtime constant real :: rad   rad = degree*deg_to_rad end function to_radian   function haversine(deglat1,deglon1,deglat2,deglon2) result (dist) ! great circle distance -- adapted from Matlab real,intent(in) :: deglat1,deglon1,deglat2,deglon2 real :: a,c,dist,dlat,dlon,lat1,lat2 real,parameter :: radius = 6372.8   dlat = to_radian(deglat2-deglat1) dlon = to_radian(deglon2-deglon1) lat1 = to_radian(deglat1) lat2 = to_radian(deglat2) a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2 c = 2*asin(sqrt(a)) dist = radius*c end function haversine   end program example  
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
#PL.2FI
PL/I
  put ('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
#Plain_English
Plain English
To run: Start up. Write "Goodbye, world!" on the console without advancing. Wait for the escape key. Shut down.
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
#PowerShell
PowerShell
Write-Host -NoNewLine "Goodbye, " Write-Host -NoNewLine "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
#Processing
Processing
  print("Goodbye, World!"); /* No automatic newline */  
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
#Fermat
Fermat
!!'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
#Pike
Pike
  array indices = ({ "a", "b", 42 }); array values = ({ Image.Color(0,0,0), "hello", "world" }); mapping m = mkmapping( indices, values ); write("%O\n", m);  
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
#Pop11
Pop11
vars keys = { 1 a b c}; vars vals = { 2 3 valb valc}; vars i; ;;; Create hash table vars ht = newmapping([], 500, 0, true); ;;; Loop over input arrays (vectors) for i from 1 to length(keys) do vals(i) -> ht(keys(i)); endfor;
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
#J
J
Until =: 2 : 'u^:(-.@:v)^:_' isHarshad =: 0 = ] |~ [: +/ #.inv NB. BASE isHarshad N assert 1 0 -: 10 isHarshad&> 42 38 nextHarshad =: (>: Until (10&isHarshad))@:>: assert 45 -: nextHarshad 42 assert 3 4 5 -: nextHarshad&> 2 3 4 assert 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 -: (, nextHarshad@:{:)Until (20 = #) 1 assert 1002 -: nextHarshad 1000     NB. next Harshad number in base 6. Input and output are in base 6. NB. Verification left to you, gentle programmer. nextHarshad_base_6 =: (>: Until (6&isHarshad))@:>: ' '-.~":6#.inv nextHarshad_base_6 6b23235 23253  
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
#eC
eC
import "ecere" MessageBox goodBye { contents = "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).
#C_sharp
C_sharp
using System; using System.ComponentModel; using System.Windows.Forms;   class RosettaInteractionForm : Form { // Model used for DataBinding. // Notifies bound controls about Value changes. class NumberModel: INotifyPropertyChanged {   Random rnd = new Random();   // initialize event with empty delegate to avoid checks on null public event PropertyChangedEventHandler PropertyChanged = delegate {};   int _value; public int Value { get { return _value; } set { _value = value; // Notify bound control about value change PropertyChanged(this, new PropertyChangedEventArgs("Value")); } }   public void ResetToRandom(){ Value = rnd.Next(5000); } }   NumberModel model = new NumberModel{ Value = 0};   RosettaInteractionForm() { //MaskedTextBox is a TextBox variety with built-in input validation var tbNumber = new MaskedTextBox { Mask="0000", // allow 4 decimal digits only ResetOnSpace = false, // don't enter spaces Dock = DockStyle.Top // place at the top of form }; // bound TextBox.Text to NumberModel.Value; tbNumber.DataBindings.Add("Text", model, "Value");   var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom}; btIncrement.Click += delegate { model.Value++; }; var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom}; btDecrement.Click += delegate { model.Value--; }; var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom }; btRandom.Click += delegate { if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes) model.ResetToRandom(); }; Controls.Add(tbNumber); Controls.Add(btIncrement); Controls.Add(btDecrement); Controls.Add(btRandom); } static void Main() { Application.Run(new RosettaInteractionForm()); } }  
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.
#LiveCode
LiveCode
command enableButtons v switch case v <= 0 put 0 into fld "Field1" set the enabled of btn "Button1" to true set the enabled of btn "Button2" to false break case v >= 10 put 10 into fld "Field1" set the enabled of btn "Button1" to false set the enabled of btn "Button2" to true break default set the enabled of btn "Button1" to true set the enabled of btn "Button2" to true put v into fld "Field1" end switch end enableButtons
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)
#11l
11l
V (target_min, target_max) = (1, 100)   print("Guess my target number that is between #. and #. (inclusive).\n".format(target_min, target_max)) V target = random:(target_min..target_max) V (answer, i) = (target_min - 1, 0) L answer != target i++ V txt = input(‘Your guess(#.): ’.format(i)) X.try answer = Int(txt) X.catch ValueError print(‘ I don't understand your input of '#.' ?’.format(txt)) L.continue I answer < target_min | answer > target_max print(‘ Out of range!’) L.continue I answer == target print(‘ Ye-Haw!!’) L.break I answer < target {print(‘ Too low.’)} I answer > target {print(‘ Too high.’)}   print("\nThanks for playing.")
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.
#ActionScript
ActionScript
package { import flash.display.Sprite;   [SWF(width="640", height="480")] public class GreyscaleBars extends Sprite {   public function GreyscaleBars() { _drawRow(8, 0); _drawRow(16, stage.stageHeight/4, true); _drawRow(32, stage.stageHeight/2); _drawRow(64, stage.stageHeight/4 * 3, true); }   private function _drawRow(nbSteps : uint, startingY : uint, reverse : Boolean = false) : void {   for (var i : int = 0; i < nbSteps; i++) { graphics.beginFill(0x00, reverse ? 1 - (i/nbSteps) : (i/nbSteps)); graphics.drawRect(i * stage.stageWidth / nbSteps, startingY, stage.stageWidth/nbSteps, stage.stageHeight/4); graphics.endFill(); } } } }
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
#Ceylon
Ceylon
shared void run() { while(true) { variable value low = 1; variable value high = 10; variable value attempts = 1; print("Please choose a number between ``low`` and ``high``. Press enter when ready."); process.readLine(); while(true) { if(low > high) { print("Something is wrong. I give up."); break; } variable value guess = (low + high) / 2; print("Is ``guess`` (e)qual, (h)igher or (l)ower to your number? (enter q to quit)"); value answer = process.readLine()?.trimmed?.lowercased; switch(answer) case("e") { print("I got it in only ``attempts`` ``attempts == 1 then "try" else "tries"``!"); break; } case("h") { high = guess - 1; attempts++; } case("l") { low = guess + 1; attempts++; } case("q") { return; } else { print("Please enter an e, h, l or q"); } } } }
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
#Clojure
Clojure
(require '[clojure.string :as str])   (defn guess-game [low high] (printf "Think of a number between %s and %s.\n (use (h)igh (l)ow (c)orrect)\n" low high) (loop [guess (/ (inc (- high low)) 2) [step & more] (next (iterate #(/ % 2) guess))] (printf "I guess %s\n=> " (Math/round (float guess))) (flush) (case (first (str/lower-case (read))) \h (recur (- guess step) more) \l (recur (+ guess step) more) \c (println "Huzzah!") (do (println "Invalid input.") (recur guess step)))))
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
#BCPL
BCPL
get "libhdr"   let sumdigitsq(n) = n=0 -> 0, (n rem 10)*(n rem 10)+sumdigitsq(n/10)   let happy(n) = valof $( let seen = vec 255 for i = 0 to 255 do i!seen := false $( n!seen := true n := sumdigitsq(n) $) repeatuntil n!seen resultis 1!seen $)   let start() be $( let n, i = 0, 0 while n < 8 do $( if happy(i) do $( n := n + 1 writef("%N ",i) $) i := i + 1 $) wrch('*N') $)
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.
#Free_Pascal
Free Pascal
program HaversineDemo; uses Math;   function HaversineDistance(const lat1, lon1, lat2, lon2:double):double;inline; const rads = pi / 180; dia = 2 * 6372.8; begin HaversineDistance := dia * arcsin(sqrt(sqr(cos(rads * (lon1 - lon2)) * cos(rads * lat1) - cos(rads * lat2)) + sqr(sin(rads * (lon1 - lon2)) * cos(rads * lat1)) + sqr(sin(rads * lat1) - sin(rads * lat2))) / 2); end;   begin Writeln('Haversine distance between BNA and LAX: ', HaversineDistance(36.12, -86.67, 33.94, -118.4):7:2, ' km.'); end.
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#PureBasic
PureBasic
OpenConsole() Print("Goodbye, World!") Input() ;wait for enter key to be pressed
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
#Python
Python
import sys sys.stdout.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
#Quackery
Quackery
say "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
#R
R
cat("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
#Fexl
Fexl
say "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
#PostScript
PostScript
  % push our arrays [/a /b /c /d /e] [1 2 3 4 5] % create a dict with it {aload pop} dip let currentdict end % show that we have created the hash {= =} forall  
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
#PowerShell
PowerShell
function create_hash ([array] $keys, [array] $values) { $h = @{} if ($keys.Length -ne $values.Length) { Write-Error -Message "Array lengths do not match" ` -Category InvalidData ` -TargetObject $values } else { for ($i = 0; $i -lt $keys.Length; $i++) { $h[$keys[$i]] = $values[$i] } } return $h }
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
#Java
Java
public class Harshad{ private static long sumDigits(long n){ long sum = 0; for(char digit:Long.toString(n).toCharArray()){ sum += Character.digit(digit, 10); } return sum; } public static void main(String[] args){ for(int count = 0, i = 1; count < 20;i++){ if(i % sumDigits(i) == 0){ System.out.println(i); count++; } } System.out.println(); for(int i = 1001; ; i++){ if(i % sumDigits(i) == 0){ System.out.println(i); break; } } } }
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
#EchoLisp
EchoLisp
  (alert "Goodbye, World!")  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#EGL
EGL
  import org.eclipse.edt.rui.widgets.*; import dojo.widgets.*;   handler HelloWorld type RUIhandler{initialUI =[ui]}   ui Box {columns=1, children=[nameField, helloLabel, goButton]};   nameField DojoTextField {placeHolder = "What's your name?", text = "World"}; helloLabel TextLabel {}; goButton DojoButton {text = "Say Goodbye", onClick ::= onClick_goButton};   function onClick_goButton(e Event in) helloLabel.text = "Goodbye, " + nameField.text + "!"; end   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).
#Common_Lisp
Common Lisp
  ;; Using the LTK library...   (defun gui-test () "the main window for the input test" (ltk:with-ltk () (ltk:wm-title ltk:*tk* "GUI Test") (ltk:bind ltk:*tk* "<Alt-q>" (lambda (evt) (declare (ignore evt)) (setf ltk:*exit-mainloop* t))) (let* (;; Initializing random generator (*random-state* (make-random-state t)) ;; Creating widgets (the-input (make-instance 'ltk:entry :text "0" :validate :key)) (f (make-instance 'ltk:frame)) (btn1 (make-instance 'ltk:button :text "random" :master f)) (btn2 (make-instance 'ltk:button :text "increment" :master f))) ;; Associating actions with widgets (ltk:bind btn1 "<Button-1>" (lambda (evt) (declare (ignore evt)) (when (ltk:ask-yesno "Really reset to random?" :title "Question") (setf (ltk:text the-input) (write-to-string (random 10000)))))) (ltk:bind btn2 "<Button-1>" (lambda (evt) (declare (ignore evt)) (setf (ltk:text the-input) (write-to-string (1+ (parse-integer (ltk:text the-input))))))) (ltk:format-wish "~A configure -validatecommand {string is int %P}" (ltk:widget-path the-input)) (ltk:focus the-input) ;; Placing widgets on the window (ltk:pack the-input :side :top) (ltk:pack f :side :bottom) (ltk:pack btn1 :side :left) (ltk:pack btn2 :side :right))))   (gui-test)    
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.
#M2000_Interpreter
M2000 Interpreter
  \\ this is global, but call as local in events, which means with local visibility for identifiers \\ so thispos and this$ has to exist in caller 's context   Function Global Local1(new Feed$) { \\ this function can be used from other Integer \\ this$ and thispos, exist just before the call of this function local sgn$ if feed$="" and this$="-" then thispos-- : exit if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2) if this$<>Trim$(this$) then this$=Feed$ : thispos-- : exit If Trim$(this$)="" then this$="0" : thispos=2 : exit if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$="" if instr(this$,"-")>0 and sgn$="" then this$=filter$(this$, "-") : sgn$="-" if filter$(this$,"0123456789")<>"" then this$=Feed$ : thispos-- : exit if len(this$)>1 then While left$(this$,1)="0" {this$=mid$(this$, 2)} this$=sgn$+this$ if this$="-0" then this$="-" : thispos=2 } Module CheckIt { Declare form1 form Declare textbox1 textbox form form1 Declare buttonInc Button form form1 Declare buttonDec Button form form1 Method textbox1, "move", 2000,2000,4000,600 Method buttonInc, "move", 2000,3000,2000,600 Method buttonDec, "move", 4000,3000,2000,600 With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:" ', "ShowAlways", True With buttonInc,"Caption","Increment" With buttonDec,"Caption","Decrement","Locked", True textbox1.value$="0"   Function controlIncDec(what$){ With buttonInc, "locked", not val(what$)<10 With buttonDec, "locked", not val(what$)>0 } finishEnter=false Function TextBox1.ValidString { \\ this function called direct from textbox Read New &this$, &thispos Call Local local1(textbox1.value$) Call Local controlIncDec(this$) } Function TextBox1.Enable { With TextBox1, "Enabled", true finishEnter=false } Function TextBox1.Disable { With TextBox1, "Enabled", false finishEnter=true } Function TextBox1.Enter { Call Local TextBox1.Disable() } Function buttonInc.Click { if not finishEnter then Call Local TextBox1.Disable() textbox1.value$=str$(val(textbox1.value$)+1, "") if val(textbox1.value$)=0 then Call Local TextBox1.Enable() } function buttonDec.Click { if not finishEnter then Call Local TextBox1.Disable() textbox1.value$=str$(val(textbox1.value$)-1, "") if val(textbox1.value$)=0 then Call Local TextBox1.Enable() } Call Local controlIncDec(textBox1.Value$) Method form1, "show", 1 Declare form1 nothing } Checkit    
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)
#Action.21
Action!
PROC Main() BYTE x,n,min=[1],max=[100]   PrintF("Try to guess a number %B-%B: ",min,max) x=Rand(max-min+1)+min DO n=InputB() IF n<min OR n>max THEN Print("The input is incorrect. Try again: ") ELSEIF n<x THEN Print("My number is higher. Try again: ") ELSEIF n>x THEN Print("My number is lower. Try again: ") ELSE PrintE("Well guessed!") EXIT FI OD RETURN
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.
#Ada
Ada
with Gtk.Window; use Gtk.Window; with Gtk.Enums; with Gtk.Handlers; with Gtk.Main; with Gdk; with Gdk.Event; with Glib; use Glib; with Cairo; use Cairo; with Gdk.Cairo; pragma Elaborate_All (Gtk.Handlers);   procedure Greyscale is   Win  : Gtk_Window; Width  : constant := 640; Height : constant := 512;   package Handlers is new Gtk.Handlers.Callback (Gtk_Window_Record); package Event_Cb is new Gtk.Handlers.Return_Callback ( Widget_Type => Gtk_Window_Record, Return_Type => Boolean);   procedure Quit (Win : access Gtk_Window_Record'Class) is pragma Warnings (Off, Win); begin Gtk.Main.Main_Quit; end Quit;   function Expose (Drawing : access Gtk_Window_Record'Class; Event  : Gdk.Event.Gdk_Event) return Boolean is subtype Dub is Glib.Gdouble; Cr  : Cairo_Context; Revert  : Boolean; Grey  : Dub; DH  : constant Dub := Dub (Height) / 4.0; X, Y, DW : Dub; N  : Natural;   begin Cr := Gdk.Cairo.Create (Get_Window (Drawing)); for Row in 1 .. 4 loop   N  := 2 ** (Row + 2); Revert := (Row mod 2) = 0; DW  := Dub (Width) / Dub (N); X  := 0.0; Y  := DH * Dub (Row - 1); for B in 0 .. (N - 1) loop Grey := Dub (B) / Dub (N - 1); if Revert then Grey := 1.0 - Grey; end if; Cairo.Set_Source_Rgb (Cr, Grey, Grey, Grey); Cairo.Rectangle (Cr, X, Y, DW, DH); Cairo.Fill (Cr); X := X + DW; end loop; end loop; Cairo.Destroy (Cr); return False; end Expose;   begin Gtk.Main.Set_Locale; Gtk.Main.Init;   Gtk_New (Win); Gtk.Window.Initialize (Win, Gtk.Enums.Window_Toplevel); Set_Title (Win, "Greyscale with GTKAda"); Set_Default_Size (Win, Width, Height); Set_App_Paintable (Win, True); -- Attach handlers Handlers.Connect (Win, "destroy", Handlers.To_Marshaller (Quit'Access)); Event_Cb.Connect (Win, "expose_event", Event_Cb.To_Marshaller (Expose'Access));   Show_All (Win);   Gtk.Main.Main; end Greyscale;  
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
#Common_Lisp
Common Lisp
  (defun guess-the-number (&optional (max 1000) (min 0)) (flet ((get-feedback (guess) (loop initially (format t "I choose ~a.~%" guess) for answer = (read) if (member answer '(greater lower correct)) return answer else do (write-line "Answer greater, lower, or correct.")))) (loop initially (format t "Think of a number between ~a and ~a.~%" min max) for guess = (floor (+ min max) 2) for answer = (get-feedback guess) until (eq answer 'correct) if (eq answer 'greater) do (setf min guess) else do (setf max guess) finally (write-line "I got it!"))))  
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
#Bori
Bori
bool isHappy (int n) { ints cache;   while (n != 1) { int sum = 0;   if (cache.contains(n)) return false;   cache.add(n); while (n != 0) { int digit = n % 10; sum += (digit * digit); n = (int)(n / 10); } n = sum; } return true; }   void test () { int num = 1; ints happynums;   while (happynums.count() < 8) { if (isHappy(num)) happynums.add(num); num++; } puts("First 8 happy numbers : " + str.newline + happynums); }
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.
#FreeBASIC
FreeBASIC
' version 09-10-2016 ' compile with: fbc -s console   ' Nashville International Airport (BNA) in Nashville, TN, USA, ' N 36°07.2', W 86°40.2' (36.12, -86.67) ' Los Angeles International Airport (LAX) in Los Angeles, CA, USA, ' N 33°56.4', W 118°24.0' (33.94, -118.40). ' 6372.8 km is an approximation of the radius of the average circumference   #Define Pi Atn(1) * 4 ' define Pi = 3.1415.. #Define deg2rad Pi / 180 ' define deg to rad 0.01745.. #Define earth_radius 6372.8 ' earth radius in km.   Function Haversine(lat1 As Double, long1 As Double, lat2 As Double, _ long2 As Double , radius As Double) As Double   Dim As Double d_long = deg2rad * (long1 - long2) Dim As Double theta1 = deg2rad * lat1 Dim As Double theta2 = deg2rad * lat2 Dim As Double dx = Cos(d_long) * Cos(theta1) - Cos(theta2) Dim As Double dy = Sin(d_long) * Cos(theta1) Dim As Double dz = Sin(theta1) - Sin(theta2) Return Asin(Sqr(dx*dx + dy*dy + dz*dz) / 2) * radius * 2   End Function   Print Print " Haversine distance between BNA and LAX = "; _ Haversine(36.12, -86.67, 33.94, -118.4, earth_radius); " km."     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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
#Ra
Ra
  class HelloWorld **Prints "Goodbye, World!" without a new line**   on start   print "Goodbye, World!" without new line  
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
#Racket
Racket
#lang racket (display "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
#Raku
Raku
print "Goodbye, World!"; printf "%s", "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
#RASEL
RASEL
"!dlroW ,olleH">:?@,Gj
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
#Fhidwfe
Fhidwfe
puts$ "Hello, world!\n"
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Prolog
Prolog
% this one with side effect hash table creation   :-dynamic hash/2.   make_hash([],[]). make_hash([H|Q],[H1|Q1]):- assert(hash(H,H1)), make_hash(Q,Q1).   :-make_hash([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]])     % this one without side effects   make_hash_pure([],[],[]). make_hash_pure([H|Q],[H1|Q1],[hash(H,H1)|R]):- make_hash_pure(Q,Q1,R).   :-make_hash_pure([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]],L),findall(M,(member(M,L),assert(M)),L).
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
#JavaScript
JavaScript
function isHarshad(n) { var s = 0; var n_str = new String(n); for (var i = 0; i < n_str.length; ++i) { s += parseInt(n_str.charAt(i)); } return n % s === 0; }   var count = 0; var harshads = [];   for (var n = 1; count < 20; ++n) { if (isHarshad(n)) { count++; harshads.push(n); } }   console.log(harshads.join(" "));   var h = 1000; while (!isHarshad(++h)); console.log(h);  
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
#Elena
Elena
import forms;   public class MainWindow : SDIDialog { Label goodByeWorldLabel; Button closeButton;   constructor new() <= new() { self.Caption := "ELENA";   goodByeWorldLabel := Label.new(); closeButton  := Button.new();   self .appendControl(goodByeWorldLabel) .appendControl(closeButton);   self.setRegion(250, 200, 200, 110);   goodByeWorldLabel.Caption := "Goodbye, World!"; goodByeWorldLabel.setRegion(40, 10, 150, 30);   closeButton.Caption := "Close"; closeButton.setRegion(20, 40, 150, 30); closeButton.onClick := (args){ forward program.stop() }; } }
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
#Euphoria
Euphoria
include msgbox.e   integer response response = message_box("Goodbye, World!","Bye",MB_OK)
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).
#Delphi
Delphi
FILE: Unit1.pas
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).
#Echolisp
Echolisp
  (require 'interface)   ;; helper new button with text (define (ui-add-button text) (define b (ui-create-element "button" '((type "button")))) (ui-set-html b text) (ui-add b))     (define (panel ) (ui-clear) (info-text "My rosetta application" "blue")   ;; input field (checked for numeric) (define f-input (ui-create-element "input" '((type number)))) (ui-set-value f-input 0) (ui-add f-input) (ui-on-focus f-input (lambda(e) (info-text "")))   ;; Increment button (define btn-inc (ui-add-button "Increment")) (define (increment elem) (define val (ui-get-numvalue f-input)) (if val ;; checked legal numeric (ui-set-value f-input (1+ val)) (info-text "Need a number" "red"))) (ui-on-click btn-inc increment) (ui-add btn-inc)   (define btn-random (ui-add-button "Random")) (define (set-random elem) (when (confirm "Really random?") (ui-set-value f-input (random-prime 1000000)))) (ui-on-click btn-random set-random)   (ui-focus btn-inc) (stdout-hide #t) (stdin-hide #t)) ;; end panel   (panel)  
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.
#Maple
Maple
  Increase();  
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)
#Ada
Ada
with Ada.Numerics.Discrete_Random; with Ada.Text_IO; procedure Guess_Number_Feedback is function Get_Int (Prompt : in String) return Integer is begin loop Ada.Text_IO.Put (Prompt); declare Response : constant String := Ada.Text_IO.Get_Line; begin if Response /= "" then return Integer'Value (Response); end if; exception when others => Ada.Text_IO.Put_Line ("Invalid response, not an integer!"); end; end loop; end Get_Int; procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is subtype Number is Integer range Lower_Limit .. Upper_Limit; package Number_RNG is new Ada.Numerics.Discrete_Random (Number); Generator  : Number_RNG.Generator; My_Number  : Number; Your_Guess : Integer; begin Number_RNG.Reset (Generator); My_Number := Number_RNG.Random (Generator); Ada.Text_IO.Put_Line ("Guess my number!"); loop Your_Guess := Get_Int ("Your guess: "); exit when Your_Guess = My_Number; if Your_Guess > My_Number then Ada.Text_IO.Put_Line ("Wrong, too high!"); else Ada.Text_IO.Put_Line ("Wrong, too low!"); end if; end loop; Ada.Text_IO.Put_Line ("Well guessed!"); end Guess_Number; Lower_Limit : Integer; Upper_Limit : Integer; begin loop Lower_Limit := Get_Int ("Lower Limit: "); Upper_Limit := Get_Int ("Upper Limit: "); exit when Lower_Limit < Upper_Limit; Ada.Text_IO.Put_Line ("Lower limit must be lower!"); end loop; Guess_Number (Lower_Limit, Upper_Limit); end Guess_Number_Feedback;
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.
#Amazing_Hopper
Amazing Hopper
  #include <flow.h> #include <flow-term.h>   #define SPACE(_T_,_N_) REPLICATE( " ", {_T_}DIV-INTO(_N_) )   DEF-MAIN(argv,argc) CLR-SCR GOSUB( Print Grey Scale ) END   RUTINES   DEF-FUN( Print Grey Scale ) SET( nrcolors, 8 ) SET( direction, 1 ) MSET( quarter, color ) LOCATE( 0, 0 ) FOR( LT?( quarter, 4 ), ++quarter ) SET( height, 0 ) FOR( LT?( height, 5 ), ++height ) SET( width, 0 ) FOR( LT?( width, nrcolors ), ++width ) LET( color := CEIL( MUL( width, DIV( 255, SUB(nrcolors,1) ) ) ) ) WHEN( NOT( MOD( direction, 2 ) ) ){ LET( color := SUB( 255, color ) ) } PRN( COLOR-RGBB( color, color, color) SPACE( 128, nrcolors ) ) NEXT PRNL("\OFF") NEXT nrcolors*=2 ++direction NEXT RET  
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.
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 SET WINDOW 0,1279,0,1023 110 REM (0,0) is the bottom left of the display 120 SET AREA COLOR 1 ! Select color one for drawing 130 FOR row=1 TO 4 140 LET n=IP(2^(row+2)) 150 LET w=IP(1280/n) 160 LET py=IP(256*(4-row)) 170 FOR b=0 TO n-1 180 LET g=b/(n-1) 190 IF n=16 OR n=64 THEN LET g=1-g 200 SET COLOR MIX(1) g,g,g  ! Reprogram color 1 to the gray we want 210 PLOT AREA: w*b,py; w*b+w,py; w*b+w,py+256; w*b,py+256 220 NEXT b 230 NEXT row 240 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
#D
D
import std.stdio, std.string;   void main() { immutable mnOrig = 1, mxOrig = 10; int mn = mnOrig, mx = mxOrig;   writefln( "Think of a number between %d and %d and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by typing h, l, or =", mn, mx);   LOOP: for (int i = 1; ; i++) { immutable guess = (mn + mx) / 2; writef("Guess %2d is: %2d. The score for which is (h,l,=): ", i, guess); immutable string txt = readln().strip().toLower();   switch (txt) { case "h": mx = guess - 1; break; case "l": mn = guess + 1; break; case "=": writeln(" Yeehaw!!"); break LOOP; default: writefln(" I don't understand your input '%s'.", txt); continue LOOP; }   if (mn > mx || mn < mnOrig || mx > mxOrig) { writeln("Please check your scoring as" ~ " I cannot find the value"); break; } } writeln("\nThanks for keeping score."); }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#BQN
BQN
SumSqDgt ← +´2⋆˜ •Fmt-'0'˙ Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢ 8↑Happy¨⊸/↕50
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.
#Frink
Frink
haversine[theta] := (1-cos[theta])/2   dist[lat1, long1, lat2, long2] := 2 earthradius arcsin[sqrt[haversine[lat2-lat1] + cos[lat1] cos[lat2] haversine[long2-long1]]]   d = dist[36.12 deg, -86.67 deg, 33.94 deg, -118.40 deg] println[d-> "km"]
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.
#FunL
FunL
import math.*   def haversin( theta ) = (1 - cos( theta ))/2   def radians( deg ) = deg Pi/180   def haversine( (lat1, lon1), (lat2, lon2) ) = R = 6372.8 h = haversin( radians(lat2 - lat1) ) + cos( radians(lat1) ) cos( radians(lat2) ) haversin( radians(lon2 - lon1) ) 2R asin( sqrt(h) )   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
#REBOL
REBOL
prin "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
#Red
Red
prin "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
#Retro
Retro
'Goodbye,_World! s:put
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
#REXX
REXX
/*REXX pgm displays a "Goodbye, World!" without a trailing newline. */   call charout ,'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
#Fish
Fish
!v"Hello world!"r! >l?!;o
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
#PureBasic
PureBasic
Dim keys.s(3) Dim vals.s(3) NewMap Hash.s()   keys(0)="a" : keys(1)="b" : keys(2)="c" : keys(3)="d" vals(0)="1" : vals(1)="2" : vals(2)="3" : vals(3)="4" For n = 0 To 3 Hash(keys(n))= vals(n) Next ForEach Hash() Debug Hash() Next
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
#Python
Python
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
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
#jq
jq
def is_harshad: def digits: tostring | [explode[] | ([.]| implode) | tonumber]; if . >= 1 then (. % (digits|add)) == 0 else false end ;   # produce a stream of n Harshad numbers def harshads(n): # [candidate, count] def _harshads: if .[0]|is_harshad then .[0], ([.[0]+1, .[1]-1]| _harshads) elif .[1] > 0 then [.[0]+1, .[1]] | _harshads else empty end; [1, n] | _harshads ;   # First Harshad greater than n where n >= 0 def harshad_greater_than(n): # input: next candidate def _harshad: if is_harshad then . else .+1 | _harshad end; (n+1) | _harshad ;   # Task: [ harshads(20), "...", harshad_greater_than(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
#F.23
F#
#light open System open System.Windows.Forms [<EntryPoint>] let main _ = MessageBox.Show("Hello World!") |> ignore 0
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Factor
Factor
USING: ui ui.gadgets.labels ; [ "Goodbye World" <label> "Rosetta Window" open-window ] with-ui
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).
#Elena
Elena
import forms; import extensions;   public class MainWindow : SDIDialog { Button btmIncrement; Button btmRandom; Edit txtNumber;   constructor new() <= new() { btmIncrement := Button.new(); btmRandom  := Button.new(); txtNumber  := Edit.new();   self .appendControl:btmIncrement .appendControl:btmRandom .appendControl:txtNumber;   self.Caption := "Rosseta Code"; self.setRegion(100, 100, 160, 120);   txtNumber.setRegion(7, 7, 140, 25); txtNumber.Caption := "0";   btmIncrement.setRegion(7, 35, 140, 25); btmIncrement.Caption := "Increment"; btmIncrement.onClick := (args){ self.onButtonIncrementClick() };   btmRandom.setRegion(7, 65, 140, 25); btmRandom.Caption := "Random"; btmRandom.onClick := (args){ self.onButtonRandomClick() }; }   private onButtonIncrementClick() { var number := txtNumber.Value.toInt();   number := number + 1; self.changeTextBoxValue(number) }   private onButtonRandomClick() { if(messageDialog.showQuestion("Inf", "Really reset to random value?")) { self.changeTextBoxValue(randomGenerator.eval(99999999)) } }   private changeTextBoxValue(number) { txtNumber.Caption := number.toString() } }
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).
#Euphoria
Euphoria
  include GtkEngine.e -- see OpenEuphoria.org   constant -- interface win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"), pan = create(GtkBox,"orientation=vertical;spacing=10"), inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"), box = create(GtkButtonBox), btn1 = create(GtkButton,"gtk-add#_Increment","Increment"), btn2 = create(GtkButton,"gtk-help#_Random","Random")   add(win,pan) add(pan,inp) add(box,{btn1,btn2}) pack(pan,-box)   show_all(win) main()   ----------------------------- global function Validate() -- warns about invalid entry, does not prevent it; ----------------------------- if not t_digit(trim_head(get("Input.text"),"- ")) then return Warn(win,"Validate","This is not a valid number","Try again!") end if return 1 end function   --------------------------- global function Increment() --------------------------- set("Input.value",get("Input.value")+1) return 1 end function   ------------------------ global function Random() ------------------------ if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then set("Input.value",rand(1000)) end if return 1 end function    
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
#11l
11l
V t = random:(1..10) V g = Int(input(‘Guess a number that's between 1 and 10: ’)) L t != g g = Int(input(‘Guess again! ’)) print(‘That's right!’)
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number, Enabled -> Dynamic[value == 0]] &}, Row@{Button["increment", value++, Enabled -> Dynamic[value < 10]], Button["decrement", value--, Enabled -> Dynamic[value > 0]]}]
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#NewLISP
NewLISP
; file: gui-enable.lsp ; url: http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls ; author: oofoe 2012-02-02   ; Load library and initialize GUI server: (load (append (env "NEWLISPDIR") "/guiserver.lsp")) (gs:init)   ; The "interlock" function maintains GUI consistency by disabling all ; controls, then selectively re-enabling them depending on the value ; in the textbox. (define (interlock) (gs:disable 'value 'increment 'decrement) (let ((v (int (gs:get-text 'value)))) (if (= 0 v) (gs:enable 'value)) (if (< v 10) (gs:enable 'increment)) (if (< 0 v) (gs:enable 'decrement)) ))   ; Callbacks. (define (update f) (gs:set-text 'value (string (f (int (gs:get-text 'value)) 1))) (interlock))   (define (incrementing id) (update +))   (define (decrementing id) (update -))   (define (valuing id) (interlock))   ; Create main window frame and set layout direction. (gs:frame 'main 100 100 200 75 "GUI Enable") (gs:set-flow-layout 'main "center" 4 4)   ; Create and add widgets. (gs:button 'decrement 'decrementing "-" 30) (gs:text-field 'value 'valuing 8) (gs:set-text 'value "0") (gs:button 'increment 'incrementing "+" 30) (gs:add-to 'main 'decrement 'value 'increment)   ; Show main window. (gs:set-visible 'main true)   ; Start event loop. (gs:listen)   (exit)
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)
#ALGOL_68
ALGOL 68
# simple guess-the-number game #   main:(   BOOL valid input := TRUE;   # register an error handler so we can detect and recover from # # invalid input # on value error( stand in , ( REF FILE f )BOOL: BEGIN valid input := FALSE; TRUE END );   # construct a random integer between 1 and 100 # INT number = 1 + ROUND ( random * 99 );   print( ( "I'm thinking of a number between 1 and 100", newline ) );   # read the user's guesses until they guess correctly # # we give feedback so they can find the number using interval # # halving # WHILE print( ( "What do you think it is? " ) ); INT guess; WHILE valid input := TRUE; read( ( guess, newline ) ); NOT valid input DO print( ( "Please guess a number between 1 and 100", newline ) ) OD; number /= guess DO IF number > guess THEN # the user's guess was too small # print( ( newline, "My number is higher than that", newline ) ) ELSE # the user's guess was too large # print( ( newline, "My number is lower than that", newline ) ) FI OD; print( ( "That's correct!", newline ) ) )
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.
#AutoHotkey
AutoHotkey
h := A_ScreenHeight w := A_ScreenWidth pToken := gdip_Startup() hdc := CreateCompatibleDC() hbm := CreateDIBSection(w, h) obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc)   OnExit, Exit   Gui +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop hwnd := WinExist() Gui Show, NA   columnHeight := h/4   Loop 4 { columnY := (A_Index-1) * columnHeight columnCount := 2**(A_Index+2) colorgap := 255 / (columnCount-1) columnWidth := w/ColumnCount If (A_Index & 1) colorComp := 0 else colorComp := 255 ,colorgap *= -1 MsgBox % colorGap * columnCount Loop % columnCount { columnX := (A_Index-1) * columnWidth pBrush := Gdip_BrushCreateSolid(QColor(colorComp, colorComp, colorComp)) Gdip_FillRectangle(G, pBrush, columnX, columnY, columnWidth, columnHeight) Gdip_DeleteBrush(pBrush) colorComp += colorgap } SetFormat, IntegerFast, hex SetFormat, IntegerFast, D }   UpdateLayeredWindow(hwnd, hdc, 0, 0, W, H)   SelectObject(hdc, obm) DeleteObject(hbm) DeleteDC(hdc) Gdip_DeleteGraphics(G) Return   Esc:: Exit: Gdip_Shutdown(pToken) ExitApp   QColor(r, g, b){ return 0xFF000000 | (r << 16) | (g << 8) | (b) }
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
#Delphi
Delphi
  program Guess_the_number;   {$APPTYPE CONSOLE}   uses System.SysUtils, system.console;   type TCharSet = set of char;   var PlayerNumber, CPUNumber: word; CPULow: word = 0; CPUHi: word = 1000; PlayerLow: word = 0; PlayerHi: word = 1000; CPUWin, PlayerWin: boolean; CPUGuessList: string = 'Previus guesses:'#10; PlayerGuessList: string = 'Previus guesses:'#10;   function WaitKey(validSet: TCharSet): char; begin repeat Result := Console.ReadKey.KeyChar; until (Result in validSet); end;   function QueryNumber(msg: string): Integer; var buf: string; begin repeat Console.WriteLine(msg); buf := Console.ReadLine.Replace(#10, '').Replace(#13, ''); until TryStrToInt(buf, result); end;   procedure Wait; begin Console.ForegroundColor := TConsoleColor.Yellow; Console.WriteLine(#10'Press Enter to continue'); WaitKey([#13]); Console.ForegroundColor := TConsoleColor.White; end;   function PlayLuck: integer; var cpu, player: double; begin cpu := CPUHi - CPULow + 1; player := PlayerHi - PlayerLow + 1;   Result := round(100 * cpu / (cpu + player)); end;   function PlayerTurn: boolean; var guess: word; begin Console.Clear; Console.WriteLine('Player Turn({0}%%):'#10, [PlayLuck]); Console.ForegroundColor := TConsoleColor.Gray; console.WriteLine(PlayerGuessList + #10);   console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [PlayerLow, PlayerHi]); Console.ForegroundColor := TConsoleColor.Red;   guess := QueryNumber('Enter your guess number:'); Console.ForegroundColor := TConsoleColor.White;   if guess > CPUNumber then begin Console.WriteLine('{0} is to high', [guess]); PlayerGuessList := PlayerGuessList + ' ' + guess.tostring + ' is to high'#10; PlayerHi := guess - 1; end;   if guess < CPUNumber then begin Console.WriteLine('{0} is to Low', [guess]); PlayerGuessList := PlayerGuessList + ' ' + guess.tostring + ' is to low'#10; PlayerLow := guess + 1; end;   Result := guess = CPUNumber; if Result then Console.WriteLine('Your guess is correct, you rock!') else Wait; end;   function CPUTurn: boolean; var guess: word; ans: char; begin guess := ((CPUHi - CPULow) div 2) + CPULow;   Console.Clear; Console.WriteLine('CPU Turn({0}%%):'#10, [100 - PlayLuck]); Console.ForegroundColor := TConsoleColor.Gray; console.WriteLine(CPUGuessList + #10); console.WriteLine(#10 + 'Tip: {0}..{1}' + #10, [CPULow, CPUHi]); Console.ForegroundColor := TConsoleColor.Red; Console.WriteLine('My guess number is {0}'#10, [guess]); Console.ForegroundColor := TConsoleColor.White;   Console.WriteLine('Press "l" = too low, "h" = too high, "c" = correct', [guess]); ans := WaitKey(['l', 'h', 'c']);   Result := false; case ans of 'l': begin CPULow := guess + 1; Console.WriteLine(#10'Then my guess is to low'#10); CPUGuessList := CPUGuessList + ' ' + guess.tostring + ' is to low'#10; end; 'h': begin CPUHi := guess - 1; Console.WriteLine(#10'Then my guess is to high'#10); CPUGuessList := CPUGuessList + ' ' + guess.tostring + ' is to high'#10; end else Result := True; end;   if Result then Console.WriteLine(#10'My guess is correct, Good luck in the next time') else Wait; end;   begin Randomize; CPUNumber := Random(1001); Console.WriteLine('Press Enter and I will start to guess the number.');   repeat PlayerWin := PlayerTurn(); if PlayerWin then Break; CPUWin := CPUTurn(); if CPUWin then Break; until false;   Console.ForegroundColor := TConsoleColor.Green;   if PlayerWin then Console.WriteLine('Player win!') else begin Console.WriteLine('CPU win!'); Console.WriteLine('If you wanna know, my number was {0}', [CPUNumber]); end;   readln; 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
#Brat
Brat
include :set   happiness = set.new 1 sadness = set.new   sum_of_squares_of_digits = { num | num.to_s.dice.reduce 0 { sum, n | sum = sum + n.to_i ^ 2 } }   happy? = { n, seen = set.new | when {true? happiness.include? n } { happiness.merge seen << n; true } { true? sadness.include? n } { sadness.merge seen; false } { true? seen.include? n } { sadness.merge seen; false } { true } { seen << n; happy? sum_of_squares_of_digits(n), seen } }   num = 1 happies = []   while { happies.length < 8 } { true? happy?(num) { happies << num }   num = num + 1 }   p "First eight happy numbers: #{happies}" p "Happy numbers found: #{happiness.to_array.sort}" p "Sad numbers found: #{sadness.to_array.sort}"
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.
#FutureBasic
FutureBasic
window 1   local fn Haversine( lat1 as double, lon1 as double, lat2 as double, lon2 as double, miles as ^double, kilometers as ^double ) double deg2rad, dLat, dLon, a, c, earth_radius_miles, earth_radius_kilometers   earth_radius_miles = 3959.0 // Radius of the Earth in miles earth_radius_kilometers = 6372.8 // Radius of the Earth in kilometers deg2rad = Pi / 180 // Pi is predefined in FutureBasic   dLat = deg2rad * ( lat2 - lat1 ) dLon = deg2rad * ( lon2 - lon1 ) a = sin( dLat / 2 ) * sin( dLat / 2 ) + cos( deg2rad * lat1 ) * cos( deg2rad * lat2 ) * sin( dLon / 2 ) * sin( dLon / 2 ) c = 2 * asin( sqr(a) )   miles.nil# = earth_radius_miles * c kilometers.nil# = earth_radius_kilometers * c end fn   double miles, kilometers   fn Haversine( 36.12, -86.67, 33.94, -118.4, @miles, @kilometers )   print "Distance in miles between BNA and LAX: "; using "####.####"; miles; " miles." print "Distance in kilometers between BNA LAX: "; using "####.####"; kilometers; " km."   HandleEvents
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.
#Go
Go
package main   import ( "fmt" "math" )   func haversine(θ float64) float64 { return .5 * (1 - math.Cos(θ)) }   type pos struct { φ float64 // latitude, radians ψ float64 // longitude, radians }   func degPos(lat, lon float64) pos { return pos{lat * math.Pi / 180, lon * math.Pi / 180} }   const rEarth = 6372.8 // km   func hsDist(p1, p2 pos) float64 { return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+ math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ))) }   func main() { fmt.Println(hsDist(degPos(36.12, -86.67), degPos(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
#Ring
Ring
see "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
#Ruby
Ruby
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
#Run_BASIC
Run BASIC
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
#Rust
Rust
fn main () { 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
#FOCAL
FOCAL
TYPE "Hello, world" !