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/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
#R
R
# Set up hash table keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker") values <- c(152, 1, 254, 152, 153) names(values) <- keys # Get value corresponding to a key values["Sam Doe"] # vals["Sam Doe"] # Get all keys corresponding to a value names(values)[values==152] # "John Smith" "Sandra Dee"
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
#Racket
Racket
  (make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))
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
#Julia
Julia
isharshad(x) = x % sum(digits(x)) == 0 nextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end   function harshads(n::Integer) h = Vector{typeof(n)}(n) h[1] = 1 for j in 2:n h[j] = nextharshad(h[j-1]) end return h end   println("First 20 harshad numbers: ", join(harshads(20), ", ")) println("First harshad number after 1001: ", nextharshad(1000))
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Fantom
Fantom
  using fwt   class Hello { public static Void main () { Dialog.openInfo (null, "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
#Forth
Forth
HWND z" Goodbye, World!" z" (title)" MB_OK MessageBox
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).
#F.23
F#
  // GUI component interaction. Nigel Galloway: June 13th., 2020 let n=new System.Windows.Forms.Form(Size=new System.Drawing.Size(250,150)) let i=new System.Windows.Forms.TextBox(Location=new System.Drawing.Point(30,30),Text="0") let g=new System.Windows.Forms.Label(Location=new System.Drawing.Point(135,33),Text="Value") let e=new System.Windows.Forms.Button(Location=new System.Drawing.Point(30,70),Text="Increment") let l=new System.Windows.Forms.Button(Location=new System.Drawing.Point(135,70),Text="Random") n.Controls.AddRange([|i;g;e;l|]) let rand=new System.Random() i.Leave.AddHandler(new System.EventHandler(fun _ _->i.Text<-try string(int(i.Text)) with |_->"0")) e.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(int(i.Text)+1)))) l.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(rand.Next())))) System.Windows.Forms.Application.Run(n)  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#11l
11l
F hamming(limit) V h = [1] * limit V (x2, x3, x5) = (2, 3, 5) V i = 0 V j = 0 V k = 0   L(n) 1 .< limit h[n] = min(x2, x3, x5) I x2 == h[n] i++ x2 = 2 * h[i] I x3 == h[n] j++ x3 = 3 * h[j] I x5 == h[n] k++ x5 = 5 * h[k] R h.last   print((1..20).map(i -> hamming(i))) print(hamming(1691))
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program guessNumber.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ BUFFERSIZE, 100     /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessNum: .asciz "I'm thinking of a number between 1 and 10. \n Try to guess it:\n"   szMessError: .asciz "That's not my number. Try another guess:\n" szMessSucces: .asciz "Correct.\n"   szCarriageReturn: .asciz "\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sBuffer: .skip BUFFERSIZE /*******************************************/ /* code section */ /*******************************************/ .text .global main main: mov x0,1 mov x1,10 bl extRandom // generate random number mov x5,x0   ldr x0,qAdrszMessNum bl affichageMess loop: mov x0,#STDIN // Linux input console ldr x1,qAdrsBuffer // buffer address mov x2,#BUFFERSIZE // buffer size mov x8,#READ // request to read datas svc 0 // call system ldr x1,qAdrsBuffer // buffer address mov x2,#0 // end of string sub x0,x0,#1 // replace character 0xA strb w2,[x1,x0] // store byte at the end of input string (x0 contains number of characters) ldr x0,qAdrsBuffer bl conversionAtoD // call routine conversion ascii to décimal cmp x0,x5 beq 1f ldr x0,qAdrszMessError // not Ok bl affichageMess b loop 1: ldr x0,qAdrszMessSucces // ok bl affichageMess   100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessNum: .quad szMessNum qAdrszMessError: .quad szMessError qAdrszMessSucces: .quad szMessSucces   qAdrszCarriageReturn: .quad szCarriageReturn qAdrsBuffer: .quad sBuffer /******************************************************************/ /* random number */ /******************************************************************/ /* x0 contains inferior value */ /* x1 contains maxi value */ /* x0 return random number */ extRandom: stp x1,lr,[sp,-16]! // save registers stp x2,x8,[sp,-16]! // save registers stp x19,x20,[sp,-16]! // save registers sub sp,sp,16 // reserve 16 octets on stack mov x19,x0 add x20,x1,1 mov x0,sp // store result on stack mov x1,8 // length 8 bytes mov x2,0 mov x8,278 // call system Linux 64 bits Urandom svc 0 mov x0,sp // load résult on stack ldr x0,[x0] sub x2,x20,x19 // calculation of the range of values udiv x1,x0,x2 // calculation range modulo msub x0,x1,x2,x0 add x0,x0,x19 // and add inferior value 100: add sp,sp,16 // alignement stack ldp x19,x20,[sp],16 // restaur 2 registers ldp x2,x8,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // retour adresse lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#ABAP
ABAP
REPORT guess_the_number.   DATA prng TYPE REF TO cl_abap_random_int.   cl_abap_random_int=>create( EXPORTING seed = cl_abap_random=>seed( ) min = 1 max = 10 RECEIVING prng = prng ).   DATA(number) = prng->get_next( ).   DATA(field) = VALUE i( ).   cl_demo_input=>add_field( EXPORTING text = |Choice one number between 1 and 10| CHANGING field = field ). cl_demo_input=>request( ).   WHILE number <> field. cl_demo_input=>add_field( EXPORTING text = |You miss, try again| CHANGING field = field ). cl_demo_input=>request( ). ENDWHILE.   cl_demo_output=>display( |Well Done| ).  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#11l
11l
F maxsumseq(sequence) V (start, end, sum_start) = (-1, -1, -1) V (maxsum_, sum_) = (0, 0) L(x) sequence sum_ += x I maxsum_ < sum_ maxsum_ = sum_ (start, end) = (sum_start, L.index) E I sum_ < 0 sum_ = 0 sum_start = L.index assert(maxsum_ == sum(sequence[start + 1 .. end])) R sequence[start + 1 .. end]   print(maxsumseq([-1, 2, -1])) print(maxsumseq([-1, 2, -1, 3, -1])) print(maxsumseq([-1, 1, 2, -5, -6])) print(maxsumseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]))
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#Nim
Nim
import gtk2, strutils, glib2   var valu: int = 0   proc thisDestroy(widget: PWidget, data: Pgpointer){.cdecl.} = main_quit()   nim_init() var window = window_new(gtk2.WINDOW_TOPLEVEL) var content = vbox_new(true,10) var hbox1 = hbox_new(true,10) var entry_fld = entry_new() entry_fld.set_text("0") var btn_quit = button_new("Quit") var btn_inc = button_new("Increment") var btn_dec = button_new("Decrement") add(hbox1,btn_inc) add(hbox1,btn_dec) pack_start(content, entry_fld, true, true, 0) pack_start(content, hbox1, true, true, 0) pack_start(content, btn_quit, true, true, 0) set_border_width(window, 5) add(window, content)   proc thisCheckBtns = set_sensitive(btn_inc, valu < 10) set_sensitive(btn_dec, valu > 0) set_sensitive(entry_fld, valu == 0)   proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} = inc(valu) entry_fld.set_text($valu) thisCheckBtns()   proc thisDec(widget: PWidget, data: Pgpointer){.cdecl.} = dec(valu) entry_fld.set_text($valu) thisCheckBtns()   proc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} = try: valu = parseInt($entry_fld.get_text()) except ValueError: entry_fld.set_text($valu) thisCheckBtns()   discard signal_connect(window, "destroy", SIGNAL_FUNC(thisDestroy), nil) discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil) discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil) discard signal_connect(btn_dec, "clicked", SIGNAL_FUNC(thisDec), nil) discard signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil)   show_all(window) thisCheckBtns() main()
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.
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings; use Tk; use Tk::Dialog; use Tk::LabFrame;   my $value = 0;   my $mw = MainWindow->new; $mw->title( 'GUI component enable/disable' ); my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1); my $entry = $lf->Entry( -width => 10, -textvariable => \$value, -validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ ? do{setenable($_[0]); 1} : 0 }, )->pack(-fill => 'x', -expand => 1); my $inc = $mw->Button( -text => 'increment', -command => sub { $value++; setenable($value) }, )->pack( -side => 'left' ); my $dec = $mw->Button( -text => 'decrement', -command => sub { $value--; setenable($value) }, )->pack( -side => 'right' );   setenable($value);   MainLoop;   sub setenable { $inc and $inc->configure( -state => $_[0] < 10 ? 'normal' : 'disabled' ); $dec and $dec->configure( -state => $_[0] > 0 ? 'normal' : 'disabled' ); $entry and $entry->configure( -state => $_[0] == 0 ? 'normal' : 'disabled' ); }
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)
#AppleScript
AppleScript
-- defining the range of the number to be guessed property minLimit : 1 property maxLimit : 100   on run -- define the number to be guessed set numberToGuess to (random number from minLimit to maxLimit) -- prepare a variable to store the user's answer set guessedNumber to missing value -- prepare a variable for feedback set tip to "" -- start a loop (will be exited by using "exit repeat" after a correct guess) repeat -- ask the user for his/her guess, the variable tip contains text after first guess only set usersChoice to (text returned of (display dialog "Guess the number between " & minLimit & " and " & maxLimit & " inclusive" & return & tip default answer "" buttons {"Check"} default button "Check")) -- try to convert the given answer to an integer and compare it the number to be guessed try set guessedNumber to usersChoice as integer if guessedNumber is greater than maxLimit or guessedNumber is less than minLimit then -- the user guessed a number outside the given range set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")" else if guessedNumber is less than numberToGuess then -- the user guessed a number less than the correct number set tip to "(Tipp: The number is greater than " & guessedNumber & ")" else if guessedNumber is greater than numberToGuess then -- the user guessed a number greater than the correct number set tip to "(Tipp: The number is less than " & guessedNumber & ")" else if guessedNumber is equal to numberToGuess then -- the user guessed the correct number and gets informed display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK" -- exit the loop (quits this application) exit repeat end if on error -- something went wrong, remind the user to enter a numeric value set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")" end try end repeat end run
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#AWK
AWK
  BEGIN { nrcolors = 8 direction = 1   for (quarter=0; quarter<4; quarter++) { for (height=0; height<5; height++) { for (width=0; width<nrcolors; width++) { # gradient goes white-to-black or black-to-white depending on direction if (direction % 2) color = width * (255 / (nrcolors-1)) else color = 255 - width * (255 / (nrcolors-1))   # print (ANSI) RGB greysacle color and amount of spaces printf("\033[48;2;%d;%d;%dm%*s", color, color, color, 64 / nrcolors, " ") } # reset color and print newline printf("\033[0m\n") }   # 8, 16, 32, 64 colors and alternating direction of gradient nrcolors *= 2 direction++ } }  
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.
#BASIC256
BASIC256
  h=ceil(graphheight/4) for row=1 to 4 w=ceil(graphwidth/(8*row)) c=255/(8*row-1) for n = 0 to (8*row-1) color 255-c*n,255-c*n,255-c*n if row/2 = int(row/2) then color c*n,c*n,c*n rect n*w,h*(row-1),w,h next n next row  
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
#Elixir
Elixir
defmodule Game do def guess(a..b) do x = Enum.random(a..b) guess(x, a..b, div(a+b, 2)) end   defp guess(x, a.._b, guess) when x < guess do IO.puts "Is it #{guess}? Too High." guess(x, a..guess-1, div(a+guess, 2)) end defp guess(x, _a..b, guess) when x > guess do IO.puts "Is it #{guess}? Too Low." guess(x, guess+1..b, div(guess+b+1, 2)) end defp guess(x, _, _) do IO.puts "Is it #{x}?" IO.puts " So the number is: #{x}" end end Game.guess(1..100)
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
#Erlang
Erlang
% Implemented by Arjun Sunel -module(guess_game). -export([main/0]).   main() -> L = 1 , % Lower Limit U = 100, % Upper Limit   io:fwrite("Player 1 : Guess my number between ~p and ", [L]), io:fwrite("and ~p until you get it right.\n", [U]), N = random:uniform(100), guess(L,U,N).   guess(L,U,N) -> K = (L+U) div 2, io:format("Player 2 : Number guessed : ~p~n",[K]), if K=:=N -> io:format("Well guessed!! by Player 2\n"); true -> if K > N -> io:format("Player 1 : Your guess is too high!\n"), guess(L,K,N); true -> io:format("Player 1 : Your guess is too low!\n"), guess(K,U,N) end end.
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#C
C
#include <stdio.h>   #define CACHE 256 enum { h_unknown = 0, h_yes, h_no }; unsigned char buf[CACHE] = {0, h_yes, 0};   int happy(int n) { int sum = 0, x, nn; if (n < CACHE) { if (buf[n]) return 2 - buf[n]; buf[n] = h_no; }   for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;   x = happy(sum); if (n < CACHE) buf[n] = 2 - x; return x; }   int main() { int i, cnt = 8; for (i = 1; cnt || !printf("\n"); i++) if (happy(i)) --cnt, printf("%d ", i);   printf("The %dth happy number: ", cnt = 1000000); for (i = 1; cnt; i++) if (happy(i)) --cnt || printf("%d\n", i);   return 0; }
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.
#Groovy
Groovy
def haversine(lat1, lon1, lat2, lon2) { def R = 6372.8 // In kilometers def dLat = Math.toRadians(lat2 - lat1) def dLon = Math.toRadians(lon2 - lon1) lat1 = Math.toRadians(lat1) lat2 = Math.toRadians(lat2)   def a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2) def c = 2 * Math.asin(Math.sqrt(a)) R * c }   haversine(36.12, -86.67, 33.94, -118.40)   > 2887.25995060711
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
#Salmon
Salmon
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
#Scala
Scala
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
#Scheme
Scheme
(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
#Scilab
Scilab
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
#Forth
Forth
." 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
#Raku
Raku
my @keys = <a b c d e>; my @values = ^5;   my %hash = @keys Z=> @values;     #Alternatively, by assigning to a hash slice: %hash{@keys} = @values;     # Or to create an anonymous hash: %( @keys Z=> @values );     # All of these zip forms trim the result to the length of the shorter of their two input lists. # If you wish to enforce equal lengths, you can use a strict hyperoperator instead:   quietly # suppress warnings about unused hash { @keys »=>« @values }; # Will fail if the lists differ in length
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
#Raven
Raven
[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals $keys $vals combine as $hash
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#K
K
  / sum of digits of an integer sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d} / Test if an integer is a Harshad number isHarshad: {:[x!(sumdig x); 0; 1]} / Returns 1 if Harshad / Generate x Harshad numbers starting from y and display the list hSeries: {harshad::();i:y;while[(x-#harshad)>0;:[isHarshad i; harshad::(harshad,i)]; i+:1];harshad}  
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Fortran
Fortran
program hello use windows integer :: res res = MessageBoxA(0, LOC("Hello, World"), LOC("Window Title"), MB_OK) end program
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).
#Fantom
Fantom
  using fwt using gfx   class GuiComponent { public static Void main () { Window { title = "Rosetta Code: Gui component" size = Size(350, 200) textField := Text { onModify.add |Event e| { Text thisText := e.widget if (thisText.text != "") // if nonempty string { try (thisText.text.toInt) // try converting to int catch thisText.text = "" // clear field if does not work } } } GridPane { numCols = 1 textField, Button { text = "increment" onAction.add |Event e| { // make sure there is a number to increment, else set field to 0 if (textField.text == "") { textField.text = "0" } else { try { Int x := textField.text.toInt textField.text = (x+1).toStr } catch { textField.text = "0" } } } }, Button { text = "random" onAction.add |Event e| { if (Dialog.openQuestion(e.window, "Make number random?", null, Dialog.yesNo) == Dialog.yes) { textField.text = Int.random(1..10000).toStr } } }, }, }.open } }  
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).
#FreeBASIC
FreeBASIC
  #Include "windows.bi"   Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Rnd Dim As MSG msg Dim As Integer n Dim As String text   'Create a window with an input field and two buttons: Window_Main = CreateWindow("#32770", "GUI Component Interaction", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 200, 0, 0, 0, 0) Var Static_Number = CreateWindow("STATIC", "Value:", WS_VISIBLE Or WS_CHILD, 10, 10, 100, 20, Window_Main, 0, 0, 0) Edit_Number = CreateWindow("EDIT", "0", WS_BORDER Or WS_VISIBLE Or WS_CHILD Or ES_AUTOHSCROLL Or ES_Number, 110, 10, 100, 20, Window_Main, 0, 0, 0) Button_Inc = CreateWindow("BUTTON", "Increment", WS_VISIBLE Or WS_CHILD, 110, 40, 100, 20, Window_Main, 0, 0, 0) Button_Rnd = CreateWindow("BUTTON", "Random", WS_VISIBLE Or WS_CHILD, 110, 70, 100, 20, Window_Main, 0, 0, 0)   'Windows message loop: While GetMessage(@msg, Window_Main, 0, 0) TranslateMessage(@msg) DispatchMessage(@msg) Select Case msg.hwnd Case Button_Inc If msg.message = WM_LBUTTONDOWN Then 'Increment value: text = Space(GetWindowTextLength(Edit_Number) + 1) 'Buffer for the text GetWindowText(Edit_Number, text, Len(text)) n = Val(text) SetWindowText(Edit_Number, Str(n + 1)) End If Case Button_Rnd If msg.message = WM_LBUTTONDOWN THEN 'Random value (max. 100000): If MessageBox(0, "Set input field to random value?", "Please confirm", MB_ICONQUESTION Or MB_YESNO) = IDYES Then n = 100000 * RND SetWindowText(Edit_Number, Str(n)) End If End If Case Window_Main If msg.message = WM_COMMAND Then End End Select Wend   End  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#360_Assembly
360 Assembly
* Hamming numbers 12/03/2017 HAM CSECT USING HAM,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R6,1 ii=1 DO WHILE=(C,R6,LE,=F'20') do ii=1 to 20 BAL R14,PRTHAM call prtham LA R6,1(R6) ii++ ENDDO , enddo ii LA R6,1691 ii=1691 BAL R14,PRTHAM call prtham L R13,4(0,R13) restore previous savearea pointer LM R14,R12,12(R13) restore previous context XR R15,R15 rc=0 BR R14 exit PRTHAM EQU * ---- prtham ST R14,R14PRT save return addr LR R1,R6 ii XDECO R1,XDEC edit MVC PG+2(4),XDEC+8 output ii LR R1,R6 ii BAL R14,HAMMING call hamming(ii) XDECO R0,XDEC edit MVC PG+8(10),XDEC+2 output hamming(ii) XPRNT PG,L'PG print buffer L R14,R14PRT restore return addr BR R14 ---- return HAMMING EQU * ---- hamming(ll) ST R14,R14HAM save return addr ST R1,LL ll MVC HH,=F'1' h(1)=1 SR R0,R0 0 ST R0,I i=0 ST R0,J j=0 ST R0,K k=0 MVC X2,=F'2' x2=2 MVC X3,=F'3' x3=3 MVC X5,=F'5' x5=5 LA R7,1 n=1 L R2,LL ll BCTR R2,0 -1 ST R2,LLM1 ll-1 DO WHILE=(C,R7,LE,LLM1) do n=1 to ll-1 L R4,X2 m=x2 IF C,R4,GT,X3 THEN if m>x3 then L R4,X3 m=x3 ENDIF , endif IF C,R4,GT,X5 THEN if m>x5 then L R4,X5 m=x5 ENDIF , endif LR R1,R7 n SLA R1,2 *4 ST R4,HH(R1) h(n+1)=m IF C,R4,EQ,X2 THEN if m=x2 then L R1,I i LA R1,1(R1) i+1 ST R1,I i=i+1 SLA R1,2 *4 L R2,HH(R1) h(i+1) MH R2,=H'2' *2 ST R2,X2 x2=2*h(i+1) ENDIF , endif IF C,R4,EQ,X3 THEN if m=x3 then L R1,J j LA R1,1(R1) j+1 ST R1,J j=j+1 SLA R1,2 *4 L R2,HH(R1) h(j+1) MH R2,=H'3' *3 ST R2,X3 x3=3*h(j+1) ENDIF , endif IF C,R4,EQ,X5 THEN if m=x5 then L R1,K k LA R1,1(R1) k+1 ST R1,K k=k+1 SLA R1,2 *4 L R2,HH(R1) h(k+1) MH R2,=H'5' *5 ST R2,X5 x5=5*h(k+1) ENDIF , endif LA R7,1(R7) n++ ENDDO , enddo n L R1,LL ll SLA R1,2 *4 L R0,HH-4(R1) return h(ll) L R14,R14HAM restore return addr BR R14 ---- return R14HAM DS A return addr of hamming R14PRT DS A return addr of print LL DS F ll LLM1 DS F ll-1 I DS F i J DS F j K DS F k X2 DS F x2 X3 DS F x3 X5 DS F x5 PG DC CL80'H(xxxx)=xxxxxxxxxx' XDEC DS CL12 temp LTORG positioning literal pool HH DS 1691F array h(1691) YREGS END HAM
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
#Action.21
Action!
PROC Main() BYTE x,n,min=[1],max=[10]   PrintF("Try to guess a number %B-%B: ",min,max) x=Rand(max-min+1)+min DO n=InputB() IF n=x THEN PrintE("Well guessed!") EXIT ELSE Print("Incorrect. Try again: ") FI OD RETURN
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
#Ada
Ada
with Ada.Numerics.Discrete_Random; with Ada.Text_IO; procedure Guess_Number is subtype Number is Integer range 1 .. 10; package Number_IO is new Ada.Text_IO.Integer_IO (Number); package Number_RNG is new Ada.Numerics.Discrete_Random (Number); Generator  : Number_RNG.Generator; My_Number  : Number; Your_Guess : Number; begin Number_RNG.Reset (Generator); My_Number := Number_RNG.Random (Generator); Ada.Text_IO.Put_Line ("Guess my number!"); loop Ada.Text_IO.Put ("Your guess: "); Number_IO.Get (Your_Guess); exit when Your_Guess = My_Number; Ada.Text_IO.Put_Line ("Wrong, try again!"); end loop; Ada.Text_IO.Put_Line ("Well guessed!"); end Guess_Number;   ------------------------------------------------------------------------------------------------------- -- Another version ------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------------   with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Numerics.Discrete_Random;   -- procedure main - begins program execution procedure main is guess : Integer := 0; counter : Integer := 0; theNumber : Integer := 0;   -- function generate number - creates and returns a random number between the -- ranges of 1 to 100 function generateNumber return Integer is type randNum is new Integer range 1 .. 100; package Rand_Int is new Ada.Numerics.Discrete_Random(randNum); use Rand_Int; gen : Generator; numb : randNum;   begin Reset(gen);   numb := Random(gen);   return Integer(numb); end generateNumber;   -- procedure intro - prints text welcoming the player to the game procedure intro is begin Put_Line("Welcome to Guess the Number"); Put_Line("==========================="); New_Line;   Put_Line("Try to guess the number. It is in the range of 1 to 100."); Put_Line("Can you guess it in the least amount of tries possible?"); New_Line; end intro;   begin New_Line;   intro; theNumber := generateNumber;   -- main game loop while guess /= theNumber loop Put("Enter a guess: "); guess := integer'value(Get_Line);   counter := counter + 1;   if guess > theNumber then Put_Line("Too high!"); elsif guess < theNumber then Put_Line("Too low!"); end if; end loop;   New_Line;   Put_Line("CONGRATULATIONS! You guessed it!"); Put_Line("It took you a total of " & integer'image(counter) & " attempts.");   New_Line; end main;
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT first,last) INT i   Put('[) FOR i=first TO last DO IF i>first THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC Process(INT ARRAY a INT size) INT i,j,beg,end INT sum,best   beg=0 end=-1 best=0 FOR i=0 TO size-1 DO sum=0 FOR j=i TO size-1 DO sum==+a(j) IF sum>best THEN best=sum beg=i end=j FI OD OD   Print("Seq=") PrintArray(a,0,size-1) PrintF("Max sum=%i %ESubseq=",best) PrintArray(a,beg,end) PutE() RETURN   PROC Main() INT ARRAY a(11)=[1 2 3 4 5 65528 65527 65516 40 25 65531], b(11)=[65535 65534 3 5 6 65534 65535 4 65532 2 65535], c(5)=[65535 65534 65533 65532 65531], d(0)=[]   Process(a,11) Process(b,11) Process(c,5) Process(d,0) RETURN
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Max_Subarray is type Int_Array is array (Positive range <>) of Integer; Empty_Error : Exception; function Max(Item : Int_Array) return Int_Array is Start : Positive; Finis : Positive; Max_Sum : Integer := Integer'First; Sum : Integer; begin if Item'Length = 0 then raise Empty_Error; end if;   for I in Item'range loop Sum := 0; for J in I..Item'Last loop Sum := Sum + Item(J); if Sum > Max_Sum then Max_Sum := Sum; Start := I; Finis := J; end if; end loop; end loop; return Item(Start..Finis); end Max; A : Int_Array := (-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); B : Int_Array := Max(A); begin for I in B'range loop Put_Line(Integer'Image(B(I))); end loop; exception when Empty_Error => Put_Line("Array being analyzed has no elements."); end Max_Subarray;
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.
#Phix
Phix
include pGUI.e Ihandle txt, inc, dec, hbx, vbx, dlg function activate(integer v) IupSetInt(txt,"VALUE",v) IupSetAttribute(inc,"ACTIVE",iff(v<10,"YES":"NO")) IupSetAttribute(dec,"ACTIVE",iff(v>0,"YES":"NO")) IupSetAttribute(txt,"ACTIVE",iff(v=0,"YES":"NO")) return IUP_CONTINUE end function function valuechanged_cb(Ihandle /*ih*/) return activate(IupGetInt(txt,"VALUE")) end function function inc_cb(Ihandle /*ih*/) return activate(IupGetInt(txt,"VALUE")+1) end function function dec_cb(Ihandle /*ih*/) return activate(IupGetInt(txt,"VALUE")-1) end function function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function IupOpen() txt = IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"FILTER=NUMBER, EXPAND=YES") inc = IupButton("increment",Icallback("inc_cb")) dec = IupButton("decrement",Icallback("dec_cb"),"ACTIVE=NO") hbx = IupHbox({inc,dec},"MARGIN=0x10, GAP=20") vbx = IupVbox({txt,hbx},"MARGIN=40x20") dlg = IupDialog(vbx) IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if
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)
#Arturo
Arturo
n: random 1 10 while ø [ try? [ num: to :integer input "Guess the number: " n case [num] when? [=n][print "\tWell Guessed! :)", exit] when? [>n][print "\tHigher than the target..."] when? [<n][print "\tLess than the target..."] else [] ] else -> print "\tInvalid input!" ]
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.
#BBC_BASIC
BBC BASIC
MODE 8:REM 640 x 512 pixel display mode: BBC BASIC gives 2 graphics points per pixel REM (0,0) is the bottom left of the display GCOL 1  :REM Select colour one for drawing FOR row%=1 TO 4 n%=2^(row%+2) w%=1280/n% py%=256*(4-row%) FOR b%=0 TO n%-1 g%=255*b%/(n%-1) IF n%=16 OR n%=64 THEN g%=255-g% COLOUR 1,g%,g%,g%  : REM Reprogram colour 1 to the grey we want RECTANGLE FILL w%*b%,py%,w%,256 NEXT b% NEXT row%
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.
#C
C
#include <gtk/gtk.h> /* do some greyscale plotting */ void gsplot (cairo_t *cr,int x,int y,double s) { cairo_set_source_rgb (cr,s,s,s); cairo_move_to (cr,x+0.5,y); cairo_rel_line_to (cr,0,1); cairo_stroke (cr); } /* make a shaded widget */ gboolean expose_event (GtkWidget *widget,GdkEventExpose *event,gpointer data) { int r,c,x=0; cairo_t *cr; cr = gdk_cairo_create (widget->window); cairo_scale (cr,5,50); cairo_set_line_width (cr,1); for (r=0;r<4;r++) { c = (r&1)*64-(r%2); do gsplot (cr,x++%64,r,c/(1<<(3-r))/(8*(1<<r)-1.0)); while ((c+=2*!(r%2)-1)!=(!(r%2))*64-(r%2)); } cairo_destroy (cr); return FALSE; } /* main */ int main (int argc, char *argv[]) { GtkWidget *window; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (window, "expose-event",G_CALLBACK (expose_event), NULL); g_signal_connect (window, "delete-event", G_CALLBACK(gtk_main_quit), NULL); gtk_window_set_default_size (GTK_WINDOW(window), 320, 200); gtk_widget_set_app_paintable (window, TRUE); gtk_widget_show_all (window); gtk_main (); return 0; }
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
#Euphoria
Euphoria
include get.e include wildcard.e   sequence Respons integer min, max, Guess min = 0 max = 100   printf(1,"Think of a number between %d and %d.\n",{min,max}) puts(1,"On every guess of mine you should state whether my guess was\n") puts(1,"too high, too low, or equal to your number by typing 'h', 'l', or '='\n")   while 1 do if max < min then puts(1,"I think something is strange here...\n") exit end if Guess = floor((max-min)/2+min) printf(1,"My guess is %d, is this correct? ", Guess) Respons = upper(prompt_string("")) if Respons[1] = 'H' then max = Guess-1 elsif Respons[1] = 'L' then min = Guess+1 elsif Respons[1] = '=' then puts(1,"I did it!\n") exit else puts(1,"I do not understand that...\n") end if end while
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace HappyNums { class Program { public static bool ishappy(int n) { List<int> cache = new List<int>(); int sum = 0; while (n != 1) { if (cache.Contains(n)) { return false; } cache.Add(n); while (n != 0) { int digit = n % 10; sum += digit * digit; n /= 10; } n = sum; sum = 0; } return true; }   static void Main(string[] args) { int num = 1; List<int> happynums = new List<int>();   while (happynums.Count < 8) { if (ishappy(num)) { happynums.Add(num); } num++; } Console.WriteLine("First 8 happy numbers : " + string.Join(",", 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.
#Haskell
Haskell
import Control.Monad (join) import Data.Bifunctor (bimap) import Text.Printf (printf)   -------------------- HAVERSINE FORMULA -------------------   -- The haversine of an angle. haversine :: Float -> Float haversine = (^ 2) . sin . (/ 2)   -- The approximate distance, in kilometers, -- between two points on Earth. -- The latitude and longtitude are assumed to be in degrees. greatCircleDistance :: (Float, Float) -> (Float, Float) -> Float greatCircleDistance = distDeg 6371 where distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2) distRad radius (lat1, lng1) (lat2, lng2) = (2 * radius) * asin ( min 1.0 ( sqrt $ haversine (lat2 - lat1) + ( (cos lat1 * cos lat2) * haversine (lng2 - lng1) ) ) ) deg2rad = join bimap ((/ 180) . (pi *))   --------------------------- TEST ------------------------- main :: IO () main = printf "The distance between BNA and LAX is about %0.f km.\n" (greatCircleDistance bna lax) where bna = (36.12, -86.67) lax = (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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin write("Goodbye, World!"); end func;
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
#SETL
SETL
nprint( '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
#Sidef
Sidef
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
#Smalltalk
Smalltalk
  Transcript show: '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
#Fortran
Fortran
print *,"Hello world!"
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#REXX
REXX
/*REXX program demonstrates hashing of a stemmed array (from a key or multiple keys)*/ key.= /*names of the nine regular polygons. */ vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon' key.1='thuhree vour phive sicks zeaven ate nein den duzun' key.2='three four five six seven eight nine ten twelve' key.3='3 4 5 6 7 8 9 10 12' key.4='III IV V VI VII VIII IX X XII' key.5='iii iv v vi vii viii ix x xii' hash.='───(not defined)───' /* [↑] blanks added to humorous keys */ /* just because it looks prettier.*/ do k=1 while key.k\=='' call hash vals,key.k /*hash the keys to the values. */ end /*k*/   parse arg query . /*obtain what was specified on the C.L.*/ if query\=='' then say 'key:' left(query,40) "value:" hash.query exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hash: parse arg @val,@key do j=1 for words(@key); map= word(@key, j) hash.map= word(@val, j) end /*j*/ return
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
#Ring
Ring
  # Project : Hash from two arrays   list1="one two three" list2="1 2 3" a = str2list(substr(list1," ",nl)) b = str2list(substr(list2," ",nl)) c = list(len(a)) for i=1 to len(b) temp = number(b[i]) c[temp] = a[i] next for i = 1 to len(c) see c[i] + " " + i + nl next  
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
#Kotlin
Kotlin
// version 1.1   fun sumDigits(n: Int): Int = when { n <= 0 -> 0 else -> { var sum = 0 var nn = n while (nn > 0) { sum += nn % 10 nn /= 10 } sum } }   fun isHarshad(n: Int): Boolean = (n % sumDigits(n) == 0)   fun main(args: Array<String>) { println("The first 20 Harshad numbers are:") var count = 0 var i = 0   while (true) { if (isHarshad(++i)) { print("$i ") if (++count == 20) break } }   println("\n\nThe first Harshad number above 1000 is:") i = 1000   while (true) { if (isHarshad(++i)) { println(i) return } } }
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
#Fennel
Fennel
  (fn love.load [] (love.window.setMode 300 300 {"resizable" false}) (love.window.setTitle "Hello world/Graphical in Fennel!"))   (let [str "Goodbye, World!"] (fn love.draw [] (love.graphics.print str 95 150)))  
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
#FreeBASIC
FreeBASIC
screen 1 'Mode 320x200 locate 12,15 ? "Goodbye, World!" sleep
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).
#Gambas
Gambas
hValueBox As ValueBox 'We need a ValueBox   Public Sub Form_Open() Dim hButton As Button 'We need 2 Buttons   With Me 'Set the Form's Properties.. .height = 95 'Set the Height .Width = 350 'Set the Width .Arrangement = Arrange.Vertical 'Arrange items vertically .Padding = 5 'Border area .Title = "GUI component interaction" 'Title displayed on the Form End With   hValueBox = New ValueBox(Me) 'Add a ValueBox to the Form   With hValueBox 'Set the ValueBox's Properties.. .Expand = True 'Expand the ValueBox .Value = 0 'Set it's value to 0 End With   hButton = New Button(Me) As "ButtonInc" 'Add a Button to the form as Event "ButtonInc"   With hButton 'Set the Button's Properties.. .Height = 28 'Set the Height .Text = "&Increment" 'Add Text (The '&' adds a keyboard shortcut) End With   hButton = New Button(Me) As "ButtonRand" 'Add a Button to the form as Event "ButtonRand"   With hButton 'Set the Button's Properties.. .Height = 28 'Set the Height .Text = "&Random" 'Add Text (The '&' adds a keyboard shortcut) End With   End   Public Sub ButtonInc_Click() 'When the 'Increment' Button is clicked..   hValueBox.Value += 1 'Increase the Value in the ValueBox by 1   End   Public Sub ButtonRand_Click() 'When the 'Random' Button is clicked.. Dim siRand As Short 'To store random number Dim byAnswer As Byte 'To store the answer to the MessageBox question   siRand = Rand(1, 32767) 'Create a 'Random' mnumber   byAnswer = Message.Question("Would you like to set the ValueBox to " & siRand & "?", "Yes", "No") ' Ask if the number is OK If byAnswer = 1 Then 'If the user says 'Yes' then hValueBox.Value = siRand 'Display the 'Random' number in the ValueBox Else 'ELSE hValueBox.Value = 0 'Set the ValueBox Value to 0 End If   End
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Ada
Ada
  with Ada.Numerics.Generic_Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.GMP.Integers; with GNATCOLL.GMP.Lib;   procedure Hamming is   type Log_Type is new Long_Long_Float; package Funcs is new Ada.Numerics.Generic_Elementary_Functions (Log_Type);   type Factors_Array is array (Positive range <>) of Positive;   generic Factors : Factors_Array := (2, 3, 5); -- The factors for smooth numbers. Hamming numbers are 5-smooth. package Smooth_Numbers is type Number is private; function Compute (Nth : Positive) return Number; function Image (N : Number) return String;   private type Exponent_Type is new Natural; type Exponents_Array is array (Factors'Range) of Exponent_Type; -- Numbers are stored as the exponents of the prime factors.   type Number is record Exponents : Exponents_Array; Log  : Log_Type; -- The log of the value, used to ease sorting. end record;   function "=" (N1, N2 : Number) return Boolean is (for all F in Factors'Range => N1.Exponents (F) = N2.Exponents (F)); end Smooth_Numbers;   package body Smooth_Numbers is One : constant Number := (Exponents => (others => 0), Log => 0.0); Factors_Log : array (Factors'Range) of Log_Type;   function Image (N : Number) return String is use GNATCOLL.GMP.Integers, GNATCOLL.GMP.Lib; R, Tmp : Big_Integer; begin Set (R, "1"); for F in Factors'Range loop Set (Tmp, Factors (F)'Image); Raise_To_N (Tmp, GNATCOLL.GMP.Unsigned_Long (N.Exponents (F))); Multiply (R, Tmp); end loop; return Image (R); end Image;   function Compute (Nth : Positive) return Number is Candidates : array (Factors'Range) of Number;   Values  : array (1 .. Nth) of Number; -- Will result in Storage_Error for very large values of Nth   Indices  : array (Factors'Range) of Natural := (others => Values'First); Current  : Number; Tmp  : Number; begin for F in Factors'Range loop Factors_Log (F) := Funcs.Log (Log_Type (Factors (F))); Candidates (F) := One; Candidates (F).Exponents (F) := 1; Candidates (F).Log := Factors_Log (F); end loop;   Values (1) := One;   for Count in 2 .. Nth loop -- Find next value (the lowest of the candidates) Current := Candidates (Factors'First); for F in Factors'First + 1 .. Factors'Last loop if Candidates (F).Log < Current.Log then Current := Candidates (F); end if; end loop;   Values (Count) := Current;   -- Update the candidates. There might be several candidates with -- the same value for F in Factors'Range loop if Candidates (F) = Current then Indices (F) := Indices (F) + 1;   Tmp := Values (Indices (F)); Tmp.Exponents (F) := Tmp.Exponents (F) + 1; Tmp.Log := Tmp.Log + Factors_Log (F);   Candidates (F) := Tmp; end if; end loop; end loop;   return Values (Nth); end Compute; end Smooth_Numbers;   package Hamming is new Smooth_Numbers ((2, 3, 5));   begin for N in 1 .. 20 loop Put (" " & Hamming.Image (Hamming.Compute (N))); end loop; New_Line;   Put_Line (Hamming.Image (Hamming.Compute (1691))); Put_Line (Hamming.Image (Hamming.Compute (1_000_000))); end Hamming;  
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
#Aime
Aime
file f; integer n; text s;   f.stdin;   n = irand(1, 10); o_text("I'm thinking of a number between 1 and 10.\n"); o_text("Try to guess it!\n"); while (1) { f_look(f, "0123456789"); f_near(f, "0123456789", s); if (atoi(s) != n) { o_text("That's not my number.\n"); o_text("Try another guess!\n"); } else { break; } }   o_text("You have won!\n");
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
#ALGOL_68
ALGOL 68
main: ( INT n; INT g; n := ENTIER (random*10+1); PROC puts = (STRING string)VOID: putf(standout, ($gl$,string)); puts("I'm thinking of a number between 1 and 10."); puts("Try to guess it! "); DO readf(($g$, g)); IF g = n THEN break ELSE puts("That's not my number. "); puts("Try another guess!") FI OD; break: puts("You have won! ") )
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Aime
Aime
gsss(list l, integer &start, &end, &maxsum) { integer e, f, i, sum;   end = f = maxsum = start = sum = 0; for (i, e in l) { sum += e; if (sum < 0) { sum = 0; f = i + 1; } elif (maxsum < sum) { maxsum = sum; end = i + 1; start = f; } } }   main(void) { integer start, end, sum; list l;   l = list(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); gsss(l, start, end, sum); o_("Max sum ", sum, "\n"); if (start < end) { l.ocall(o_, 1, start, end - 1, " "); o_newline(); }   0; }
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#ALGOL_68
ALGOL 68
main: ( []INT a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1);   INT begin max, end max, max sum, sum;   sum := 0; begin max := 0; end max := -1; max sum := 0;     FOR begin FROM LWB a TO UPB a DO sum := 0; FOR end FROM begin TO UPB a DO sum +:= a[end]; IF sum > max sum THEN max sum := sum; begin max := begin; end max := end FI OD OD;   FOR i FROM begin max TO end max DO print(a[i]) OD   )
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.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")   (de start () (and (app) (zero *Number)) (action (html 0 "Enable/Disable" "@lib.css" NIL (form NIL (gui '(+Var +Able +NumField) '*Number '(=0 *Number) 20 "Value") (gui '(+Able +JS +Button) '(> 10 *Number) "increment" '(inc '*Number) ) (gui '(+Able +JS +Button) '(gt0 *Number) "decrement" '(dec '*Number) ) ) ) ) )   (server 8080 "!start") (wait)
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)
#AutoHotkey
AutoHotkey
MinNum = 1 MaxNum = 99999999999   Random, RandNum, %MinNum%, %MaxNum% Loop { InputBox, Guess, Number Guessing, Please enter a number between %MinNum% and %MaxNum%:,, 350, 130,,,,, %Guess% If ErrorLevel ExitApp If Guess Is Not Integer { MsgBox, 16, Error, Invalid guess. Continue } If Guess Not Between %MinNum% And %MaxNum% { MsgBox, 16, Error, Guess must be a number between %MinNum% and %MaxNum%. Continue } If A_Index = 1 TotalTime = %A_TickCount% Tries = %A_Index% If Guess = %RandNum% Break If Guess < %RandNum% MsgBox, 64, Incorrect, The number guessed (%Guess%) was too low. If Guess > %RandNum% MsgBox, 64, Incorrect, The number guessed (%Guess%) was too high. } TotalTime := Round((A_TickCount - TotalTime) / 1000,1) MsgBox, 64, Correct, The number %RandNum% was guessed in %Tries% tries, which took %TotalTime% seconds.
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.
#C.23
C#
using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Application.Run(new FullScreen()); } } public sealed class FullScreen : Form { const int ColorCount = 256; public FullScreen() { FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; KeyPress += (s, e) => Application.Exit(); BackgroundImage = ColorBars(Screen.FromControl(this).Bounds); } private static Bitmap ColorBars(Rectangle size) { var colorBars = new Bitmap(size.Width, size.Height); Func<int, int, int> forwardColor = (x, divs) => (int)(x * ((float)divs / size.Width)) * ColorCount / divs; Func<int, int, int> reverseColor = (x, divs) => ColorCount - 1 - forwardColor(x, divs); Action<int, int, int> setGray = (x, y, gray) => colorBars.SetPixel(x, y, Color.FromArgb(gray, gray, gray)); Action<int, int, int> setForward = (x, y, divs) => setGray(x, y, forwardColor(x, divs)); Action<int, int, int> setReverse = (x, y, divs) => setGray(x, y, reverseColor(x, divs)); int verticalStripe = size.Height / 4; for (int x = 0; x < size.Width; x++) { for (int y = 0; y < verticalStripe; y++) setForward(x, y, 8); for (int y = verticalStripe; y < verticalStripe * 2; y++) setReverse(x, y, 16); for (int y = verticalStripe * 2; y < verticalStripe * 3; y++) setForward(x, y, 32); for (int y = verticalStripe * 3; y < verticalStripe * 4; y++) setReverse(x, y, 64); } return colorBars; } }
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
#Factor
Factor
USING: binary-search formatting io kernel math.ranges words ;   : instruct ( -- ) "Think of a number between 1 and 100." print "Score my guess with +lt+ +gt+ or +eq+." print nl ;   : score ( n -- <=> ) "My guess is %d. " printf readln "math.order" lookup-word ;   : play-game ( -- n ) 100 [1,b] [ score ] search nip nl ;   : gloat ( n -- ) "I did it. Your number was %d!\n" printf ;   instruct play-game gloat
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
#Fantom
Fantom
  class Main { public static Void main () { Int lowerLimit := 1 Int higherLimit := 100   echo ("Think of a number between 1 and 100") echo ("Press 'enter' when ready") Env.cur.in.readLine   while (true) { if (higherLimit < lowerLimit) { // check that player is not cheating! echo ("Something has gone wrong ... I give up") break } myGuess := (higherLimit + lowerLimit) / 2 echo ("My guess is $myGuess") echo ("Enter 'H' if your number is higher, 'L' if lower, or 'E' if equal") switch (Env.cur.in.readLine.trim.upper) { case "E": echo ("I got it correct - thankyou!") break // game over case "H": lowerLimit = myGuess + 1 case "L": higherLimit = myGuess - 1 default: echo ("Pardon? Let's try that again") } } } }  
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
#C.2B.2B
C++
#include <map> #include <set>   bool happy(int number) { static std::map<int, bool> cache;   std::set<int> cycle; while (number != 1 && !cycle.count(number)) { if (cache.count(number)) { number = cache[number] ? 1 : 0; break; } cycle.insert(number); int newnumber = 0; while (number > 0) { int digit = number % 10; newnumber += digit * digit; number /= 10; } number = newnumber; } bool happiness = number == 1; for (std::set<int>::const_iterator it = cycle.begin(); it != cycle.end(); it++) cache[*it] = happiness; return happiness; }   #include <iostream>   int main() { for (int i = 1; i < 50; i++) if (happy(i)) std::cout << i << std::endl; return 0; }
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.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() #: Haversine formula printf("BNA to LAX is %d km (%d miles)\n", d := gcdistance([36.12, -86.67],[33.94, -118.40]),d*3280/5280) # with cute km2mi conversion end   procedure gcdistance(a,b) a[2] -:= b[2] every (x := a|b)[i := 1 to 2] := dtor(x[i]) dz := sin(a[1]) - sin(b[1]) dx := cos(a[2]) * cos(a[1]) - cos(b[1]) dy := sin(a[2]) * cos(a[1]) return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * 6371 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
#Standard_ML
Standard ML
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
#Swift
Swift
print("Goodbye, World!", terminator: "")
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
#Tcl
Tcl
puts -nonewline "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
#Transact-SQL
Transact-SQL
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
#Fortress
Fortress
export Executable   run() = println("Hello world!")
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Ruby
Ruby
  keys = ['hal',666,[1,2,3]] vals = ['ibm','devil',123]   hash = Hash[keys.zip(vals)]   p hash # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123}   #retrieve the value linked to the key [1,2,3] puts hash[ [1,2,3] ] # => 123  
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
#Rust
Rust
use std::collections::HashMap;   fn main() { let keys = ["a", "b", "c"]; let values = [1, 2, 3];   let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>(); println!("{:?}", hash); }
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I digsummin YR num I HAS A digsum ITZ 0 IM IN YR LOOP num, O RLY? YA RLY digsum R SUM OF digsum AN MOD OF num AN 10 num R QUOSHUNT OF num AN 10 NO WAI, FOUND YR digsum OIC IM OUTTA YR LOOP IF U SAY SO   I HAS A found ITZ 0   IM IN YR finder UPPIN YR n I HAS A n ITZ SUM OF n AN 1 I HAS A digsum ITZ I IZ digsummin YR n MKAY   NOT MOD OF n AN digsum, O RLY? YA RLY DIFFRINT found AN BIGGR OF found AN 20, O RLY? YA RLY VISIBLE n " "! found R SUM OF found AN 1 OIC   DIFFRINT n AN SMALLR OF n AN 1000, O RLY? YA RLY, VISIBLE ":)" n, GTFO OIC OIC IM OUTTA YR finder   KTHXBYE
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
#Frege
Frege
package HelloWorldGraphical where   import Java.Swing   main _ = do frame <- JFrame.new "Goodbye, world!" frame.setDefaultCloseOperation(JFrame.dispose_on_close) label <- JLabel.new "Goodbye, world!" cp <- frame.getContentPane cp.add label frame.pack frame.setVisible true
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
#Frink
Frink
  g = new graphics g.font["SansSerif", 10] g.text["Goodbye, World!", 0, 0, 10 degrees] g.show[]   g.print[] // Optional: render to printer g.write["GoodbyeWorld.png", 400, 300] // Optional: write to graphics file  
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).
#Go
Go
package main   import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" )   func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true }   func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } }   func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil)   window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() })   box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1)   label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:")   entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") // initialize to zero entry.Connect("activate", func() { // read and validate the entered value str, _ := entry.GetText() validateInput(window, str) })   // button to increment ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { // read and validate the entered value str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } })   // button to put in a random value if confirmed rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } })   box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box)   window.ShowAll() gtk.Main() }
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#ALGOL_68
ALGOL 68
PR precision=100 PR   MODE SERIES = FLEX [1 : 0] UNT, # Initially, no elements # UNT = LONG LONG INT; # A 100-digit unsigned integer #   PROC hamming number = (INT n) UNT: # The n-th Hamming number # CASE n IN 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 # First 10 in a table # OUT # Additional operators # OP MIN = (INT i, j) INT: (i < j | i | j), MIN = (UNT i, j) UNT: (i < j | i | j); PRIO MIN = 9; OP LAST = (SERIES h) UNT: h[UPB h]; # Last element of a series # OP +:= = (REF SERIES s, UNT elem) VOID: # Extend a series by one element, only keep the elements you need # (INT lwb = (i MIN j) MIN k, upb = UPB s; REF SERIES new s = HEAP FLEX [lwb : upb + 1] UNT; (new s[lwb : upb] := s[lwb : upb], new s[upb + 1] := elem); s := new s ); # Determine the n-th hamming number iteratively # SERIES h := 1, # Series, initially one element # UNT m2 := 2, m3 := 3, m5 := 5, # Multipliers # INT i := 1, j := 1, k := 1; # Counters # TO n - 1 DO h +:= (m2 MIN m3) MIN m5; (LAST h = m2 | m2 := 2 * h[i +:= 1]); (LAST h = m3 | m3 := 3 * h[j +:= 1]); (LAST h = m5 | m5 := 5 * h[k +:= 1]) OD; LAST h ESAC;   FOR k TO 20 DO print ((whole (hamming number (k), 0), blank)) OD; print ((newline, whole (hamming number (1 691), 0))); print ((newline, whole (hamming number (1 000 000), 0)))
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#AppleScript
AppleScript
on run -- define the number to be guessed set numberToGuess to (random number from 1 to 10) -- prepare a variable to store the user's answer set guessedNumber to missing value -- start a loop (will be exited by using "exit repeat" after a correct guess) repeat try -- ask the user for his/her guess set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check")) -- try to convert the given answer to an integer set guessedNumber to usersChoice as integer on error -- something gone wrong, overwrite user's answer with a non-matching value set guessedNumber to missing value end try -- decide if the user's answer was the right one if guessedNumber is equal to numberToGuess then -- the user guessed the correct number and gets informed display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK" -- exit the loop (quits this application) exit repeat end if end repeat end run
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#AppleScript
AppleScript
-- maxSubseq :: [Int] -> [Int] -> (Int, [Int]) on maxSubseq(xs) script go on |λ|(ab, x) set a to fst(ab) set {m1, m2} to {fst(a), snd(a)} set high to max(Tuple(0, {}), Tuple(m1 + x, m2 & {x})) Tuple(high, max(snd(ab), high)) end |λ| end script   snd(foldl(go, Tuple(Tuple(0, {}), Tuple(0, {})), xs)) end maxSubseq     -- TEST --------------------------------------------------- on run set mx to maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}) {fst(mx), snd(mx)} end run     -- GENERIC ABSTRACTIONS -----------------------------------   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- gt :: Ord a => a -> a -> Bool on gt(x, y) set c to class of x if record is c or list is c then fst(x) > fst(y) else x > y end if end gt   -- fst :: (a, b) -> a on fst(tpl) if class of tpl is record then |1| of tpl else item 1 of tpl end if end fst   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- max :: Ord a => a -> a -> a on max(x, y) if gt(x, y) then x else y end if end max   -- snd :: (a, b) -> b on snd(tpl) if class of tpl is record then |2| of tpl else item 2 of tpl end if end snd   -- Tuple (,) :: a -> b -> (a, b) on Tuple(a, b) {type:"Tuple", |1|:a, |2|:b, length:2} end Tuple
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.
#Prolog
Prolog
dialog('GUI_Interaction', [ object := GUI_Interaction, parts := [ GUI_Interaction := dialog('Rosetta Code'), Name := label(name, 'Value :'), Input_field := text_item(input_field, '0'), Increment := button(increment), Decrement := button(decrement) ], modifications := [ Input_field := [ label := 'Value :', length := 28, show_label := @off ], Decrement := [active := @off] ], layout := [ area(Name, area(50, 26, 25, 24)), area(Input_field, area(95, 24, 200, 24)), area(Increment, area(50, 90, 80, 24)), area(Decrement, area(230, 90, 80, 24)) ], behaviour :=   [ Increment := [ message := message(@prolog, increment, Increment, Decrement, Input_field ) ], Decrement := [ message := message(@prolog, decrement, Increment, Decrement, Input_field) ], Input_field := [ message := message(@prolog, input, Increment, Decrement, @receiver, @arg1) ] ]   ]).   gui_component :- make_dialog(S, 'GUI_Interaction'), send(S, open).     increment(Incr, Decr, Input) :- get(Input, selection, V), atom_number(V, Val), Val1 is Val + 1, send(Input, selection, Val1), test(Val1, Incr, Decr, Input).   decrement(Incr, Decr, Input) :- get(Input, selection, V), atom_number(V, Val), Val1 is Val - 1, send(Input, selection, Val1), test(Val1, Incr, Decr, Input).       input(Incr, Decr, Input, Selection) :- catch( (term_to_atom(T, Selection), number(T)), _, ( send(@display, inform, 'Please type a number !'), T = 0, send(Input,selection, T))), test(T, Incr, Decr, Input).     test(V, Incr, Decr, Input) :- ( V = 0 -> send(Input, active, @on); send(Input, active, @off)), send(Incr, active, @on), send(Decr, active, @on), ( V < 1 -> send(Decr, active, @off) ; V > 9 -> send(Incr, active, @off)).    
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)
#AWK
AWK
  # syntax: GAWK -f GUESS_THE_NUMBER_WITH_FEEDBACK.AWK BEGIN { L = 1 H = 100 srand() n = int(rand() * (H-L+1)) + 1 printf("I am thinking of a number between %d and %d. Try to guess it.\n",L,H) while (1) { getline ans if (ans !~ /^[0-9]+$/) { print("Your input was not a number. Try again.") continue } if (n == ans) { print("Well done you.") break } if (n > ans) { print("Incorrect, your answer was too low. Try again.") continue } if (n < ans) { print("Incorrect, your answer was too high. Try again.") continue } } exit(0) }  
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.
#C.2B.2B
C++
file greytones.h
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.
#Component_Pascal
Component Pascal
  MODULE RosettaGreys; IMPORT Views, Ports, Properties, Controllers, StdLog;   CONST (* orient values *) left = 1; right = 0;   TYPE View = POINTER TO RECORD (Views.View) END;   PROCEDURE LoadGreyPalette(VAR colors: ARRAY OF Ports.Color); VAR i, step, hue: INTEGER; BEGIN step := 255 DIV LEN(colors); FOR i := 1 TO LEN(colors) DO hue := i * step; colors[i - 1] := Ports.RGBColor(hue,hue,hue) END END LoadGreyPalette;   PROCEDURE (v: View) Restore(f: Views.Frame; l, t, r, b: INTEGER); VAR i, w, h: INTEGER; colors: POINTER TO ARRAY OF Ports.Color;   PROCEDURE Draw(row, cols: INTEGER; orient: INTEGER); VAR w: INTEGER; c: Ports.Color; BEGIN NEW(colors,cols);LoadGreyPalette(colors^); w := (r - l) DIV cols; FOR i := 1 TO cols DO IF orient = left THEN c := colors[cols - i] ELSE c := colors[i - 1] END; f.DrawRect((l + w) * (i - 1), t + (row - 1) * h, (l + w) * i, t + row * h,Ports.fill,c); END END Draw; BEGIN h := (b - t) DIV 4; Draw(1,8,right); Draw(2,16,left); Draw(3,32,right); Draw(4,64,left); END Restore;   PROCEDURE (v: View) HandlePropMsg(VAR msg: Properties.Message); CONST min = 5 * Ports.mm; max = 50 * Ports.mm; VAR stdProp: Properties.StdProp; prop: Properties.Property; BEGIN WITH msg: Properties.SizePref DO IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN msg.w := 100 * Ports.mm; msg.h := 35 * Ports.mm END ELSE (* ignore other messages *) END END HandlePropMsg;   PROCEDURE Deposit*; VAR v: View; BEGIN NEW(v); Views.Deposit(v) END Deposit; END RosettaGreys.   "RosettaGreys.Deposit; StdCmds.Open"  
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
#FOCAL
FOCAL
01.10 A "LOWER LIMIT",L 01.15 A "UPPER LIMIT",H 01.20 S T=0 01.25 I (L-H)1.3;T "INVALID INPUT"!;Q 01.30 S G=FITR((H-L)/2+L) 01.35 T "MY GUESS IS",%4,G,! 01.37 S T=T+1 01.40 A "TOO (L)OW, TOO (H)IGH, OR (C)ORRECT",R 01.45 I (R-0L)1.5,1.65,1.5 01.50 I (R-0H)1.55,1.7,1.55 01.55 I (R-0C)1.6,1.75,1.6 01.60 T "INVALID INPUT"!;G 1.3 01.65 S L=G;G 1.3 01.70 S H=G;G 1.3 01.75 T "ATTEMPTS",T,! 01.80 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
#Fortran
Fortran
program Guess_a_number_Player implicit none   integer, parameter :: limit = 100 integer :: guess, mx = limit, mn = 1 real :: rnum character(1) :: score   write(*, "(a, i0, a)") "Think of a number between 1 and ", limit, & " and I will try to guess it." write(*, "(a)") "You score my guess by entering: h if my guess is higher than that number" write(*, "(a)") " l if my guess is lower than that number" write(*, "(a/)") " c if my guess is the same as that number"   call random_seed call random_number(rnum) guess = rnum * limit + 1 do write(*, "(a, i0, a,)", advance='no') "My quess is: ", guess, " Score(h, l or c)?: " read*, score select case(score) case("l", "L") mn = guess guess = (mx-guess+1) / 2 + mn   case("h", "H") mx = guess guess = mx - (guess-mn+1) / 2   case("c", "C") write(*, "(a)") "I solved it!" exit   case default write(*, "(a)") "I did not understand that" end select end do end program
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
#Clojure
Clojure
(defn happy? [n] (loop [n n, seen #{}] (cond (= n 1) true (seen n) false  :else (recur (->> (str n) (map #(Character/digit % 10)) (map #(* % %)) (reduce +)) (conj seen n)))))   (def happy-numbers (filter happy? (iterate inc 1)))   (println (take 8 happy-numbers))
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.
#Idris
Idris
module Main   -- The haversine of an angle. hsin : Double -> Double hsin t = let u = sin (t/2) in u*u   -- The distance between two points, given by latitude and longtitude, on a -- circle. The points are specified in radians. distRad : Double -> (Double, Double) -> (Double, Double) -> Double distRad radius (lat1, lng1) (lat2, lng2) = let hlat = hsin (lat2 - lat1) hlng = hsin (lng2 - lng1) root = sqrt (hlat + cos lat1 * cos lat2 * hlng) in 2 * radius * asin (min 1.0 root)   -- The distance between two points, given by latitude and longtitude, on a -- circle. The points are specified in degrees. distDeg : Double -> (Double, Double) -> (Double, Double) -> Double distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2) where d2r : Double -> Double d2r t = t * pi / 180 deg2rad (t, u) = (d2r t, d2r u)   -- The approximate distance, in kilometers, between two points on Earth. -- The latitude and longtitude are assumed to be in degrees. earthDist : (Double, Double) -> (Double, Double) -> Double earthDist = distDeg 6372.8   main : IO () main = putStrLn $ "The distance between BNA and LAX is about " ++ show (floor dst) ++ " km." where bna : (Double, Double) bna = (36.12, -86.67)   lax : (Double, Double) lax = (33.94, -118.40)   dst : Double dst = earthDist bna lax  
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.
#IS-BASIC
IS-BASIC
100 PROGRAM "Haversine.bas" 110 PRINT "Haversine distance:";HAVERSINE(36.12,-86.67,33.94,-118.4);"km" 120 DEF HAVERSINE(LAT1,LON1,LAT2,LON2) 130 OPTION ANGLE RADIANS 140 LET R=6372.8 150 LET DLAT=RAD(LAT2-LAT1):LET DLON=RAD(LON2-LON1) 160 LET LAT1=RAD(LAT1):LET LAT2=RAD(LAT2) 170 LET HAVERSINE=R*2*ASIN(SQR(SIN(DLAT/2)^2+SIN(DLON/2)^2*COS(LAT1)*COS(LAT2))) 190 END DEF
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
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT 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
#TXR
TXR
$ txr -e '(put-string "Goodbye, world!")' 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
#UNIX_Shell
UNIX Shell
printf "Goodbye, World!" # This works. There is no newline. printf %s "-hyphens and % signs" # Use %s with arbitrary strings.
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
#Ursa
Ursa
out "goodbye world!" console
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
#FreeBASIC
FreeBASIC
? "Hello world!" sleep
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
#Sather
Sather
class ZIPPER{K,E} is zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E} pre k.size = e.size is m :MAP{K, E} := #; loop m[k.elt!] := e.elt!; end; return m; end; end;   class MAIN is   main is keys:ARRAY{STR} := |"one", "three", "four"|; values:ARRAY{INT} := |1, 3, 4|; m ::= ZIPPER{STR,INT}::zip(keys, values); loop #OUT + m.pair! + " "; end; #OUT + "\n"; end;   end;
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Scala
Scala
val keys = List(1, 2, 3) val values = Array("A", "B", "C") // Array mixed with List val map = keys.zip(values).toMap // and other Seq are possible.   // Testing assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C")) println("Successfully completed without errors.")
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
#Lua
Lua
function isHarshad(n) local s=0 local n_str=tostring(n) for i=1,#n_str do s=s+tonumber(n_str:sub(i,i)) end return n%s==0 end   local count=0 local harshads={} local n=1   while count<20 do if isHarshad(n) then count=count+1 table.insert(harshads, n) end n=n+1 end   print(table.concat(harshads, " "))   local h=1001 while not isHarshad(h) do h=h+1 end print(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
#FunL
FunL
native javax.swing.{SwingUtilities, JPanel, JLabel, JFrame} native java.awt.Font   def createAndShowGUI( msg ) = f = JFrame() f.setTitle( msg ) f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) p = JPanel() l = JLabel( msg ) l.setFont( Font.decode(Font.SERIF + ' 150') ) p.add( l ) f.add( p ) f.pack() f.setResizable( false ) f.setVisible( true )   SwingUtilities.invokeLater( createAndShowGUI.runnable('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
#FutureBasic
FutureBasic
  alert 1, NSWarningAlertStyle, @"Goodbye, World!", @"It's been real.", @"See ya!", YES   HandleEvents  
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).
#Haskell
Haskell
import Graphics.UI.WX import System.Random   main :: IO () main = start $ do frm <- frame [text := "Interact"] fld <- textEntry frm [text := "0", on keyboard := checkKeys] inc <- button frm [text := "increment", on command := increment fld] ran <- button frm [text := "random", on command := (randReplace fld frm)] set frm [layout := margin 5 $ floatCentre $ column 2 [centre $ widget fld, row 2 [widget inc, widget ran]]]   increment :: Textual w => w -> IO () increment field = do val <- get field text when ((not . null) val) $ set field [text := show $ 1 + read val]   checkKeys :: EventKey -> IO () checkKeys (EventKey key _ _) = when (elem (show key) $ "Backspace" : map show [0..9]) propagateEvent   randReplace :: Textual w => w -> Window a -> IO () randReplace field frame = do answer <- confirmDialog frame "Random" "Generate a random number?" True when answer $ getStdRandom (randomR (1,100)) >>= \num -> set field [text := show (num :: Int)]
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#ALGOL_W
ALGOL W
begin  % returns the minimum of a and b  % integer procedure min ( integer value a, b ) ; if a < b then a else b;  % find and print Hamming Numbers  %  % Algol W only supports 32-bit integers so we just find %  % the 1691 32-bit Hamming Numbers  % integer MAX_HAMMING; MAX_HAMMING := 1691; begin integer array H( 1 :: MAX_HAMMING ); integer p2, p3, p5, last2, last3, last5; H( 1 ) := 1; last2  := last3 := last5 := 1; p2  := 2; p3  := 3; p5  := 5; for hPos := 2 until MAX_HAMMING do begin integer m;  % the next Hamming number is the lowest of the next multiple of 2, 3, and 5 % m := min( min( p2, p3 ), p5 ); H( hPos ) := m; if m = p2 then begin last2 := last2 + 1; p2  := 2 * H( last2 ) end if_used_power_of_2 ; if m = p3 then begin last3 := last3 + 1; p3  := 3 * H( last3 ) end if_used_power_of_3 ; if m = p5 then begin last5 := last5 + 1; p5  := 5 * H( last5 ) end if_used_power_of_5 ; end for_hPos ; i_w := 1; s_w := 1; write( H( 1 ) ); for i := 2 until 20 do writeon( H( i ) ); write( H( MAX_HAMMING ) ) end end.