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] ...
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/...
#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("...
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 dial...
#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...
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 ...
#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...
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,   a...
#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 "../includeConstantesAR...
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,   a...
#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...
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 th...
#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...
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 progr...
#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 = butt...
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 progr...
#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, ...
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...
#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 fe...
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 ha...
#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 / (nrcolo...
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 ha...
#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 score...
#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}? To...
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 score...
#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)...
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 inclu...
#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 < CACH...
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, g...
#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.c...
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 wi...
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/...
#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::(hars...
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 dial...
#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 no...
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 dial...
#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,...
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 ...
#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...
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,   a...
#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,   a...
#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; You...
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 th...
#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 ...
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 th...
#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; be...
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 progr...
#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 func...
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...
#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 -...
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 ha...
#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% COL...
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 ha...
#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,g...
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 score...
#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 ...
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 inclu...
#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 (c...
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, g...
#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. -- ...
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 ...
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/...
#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...
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 dial...
#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 ...
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 ...
#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 (Positi...
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,   a...
#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...
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,   a...
#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 n...
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 th...
#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; star...
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 th...
#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 ...
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 progr...
#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 '...
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...
#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 %MinNu...
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 ha...
#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 = F...
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 score...
#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 ]...
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 score...
#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! ...
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 inclu...
#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...
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, g...
#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...
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/...
#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 IT...
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 dial...
#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.D...
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 ...
#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 # ...
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,   a...
#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 ...
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 th...
#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   ...
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 progr...
#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), Decremen...
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...
#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...
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 ha...
#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 ha...
#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...
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 score...
#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"...
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 score...
#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...
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 inclu...
#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? (...
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, g...
#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, lng...
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, g...
#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(SI...
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}::...
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/...
#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 ...
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()...
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 dial...
#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 := (ran...
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 ...
#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 ...