task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Arturo
Arturo
n: random 1 10   while [notEqual? to :integer input "Guess the number: " n] [ print "Wrong!" ]   print "Well guessed!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#AutoHotkey
AutoHotkey
Random, rand, 1, 10 ; This stores a number between 1 and 10 in the var rand using the Mersenne Twister msgbox I am thinking of a number between 1 and 10.   loop { InputBox, guess, Guess the number, Type in a number from 1 to 10 If (guess = rand) { msgbox Well Guessed! Break ; exits loop } Else Msgbox...
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...
#Arturo
Arturo
subarraySum: function [arr][ curr: 0 mx: 0 fst: size arr lst: 0 currFst: 0   loop.with: 'i arr [e][ curr: curr + e if e > curr [ curr: e currFst: i ] if curr > mx [ mx: curr fst: currFst lst: i ] ...
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...
#PureBasic
PureBasic
Enumeration #TextGadget #AddButton #SubButton EndEnumeration   Procedure UpdateGadgets(Value,UpdateValue=0) Overmax=0: UnderMin=0 If Value>=10 Overmax=1 ElseIf Value<=0 UnderMin=1 EndIf DisableGadget(#AddButton,Overmax) DisableGadget(#SubButton,UnderMin) If UpdateValue SetGadgetText(#Te...
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...
#BASIC
BASIC
100 L% = 1 110 U% = 10 120 N% = RND(1) * (U% - L% + 1) + L% 130 PRINT "A NUMBER FROM " L%; 140 PRINT " TO " U%; 150 PRINT ", CALLED A TARGET, HAS BEEN RANDOMLY CHOSEN." 160 FOR Q = 0 TO 1 STEP 0 170 INPUT "GUESS THE TARGET NUMBER: "; G% 180 IF G% < L% OR G% > U% THEN PRINT "THE INPUT WAS INAPPROPRIATE." 190 ...
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...
#EasyLang
EasyLang
n = 8 for row range 4 sz = 100 / n for i range n c = i / (n - 1) if row mod 2 = 1 c = 1 - c . color3 c c c move sz * i row * 25 rect sz + 1 25 . n *= 2 .
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function grayscale(y1,y2,n,direction=1) ... $ loop 0 to n-1; $ s=#/(n-1); barcolor(rgb(s,s,s)); $ if direction==1 then plotbar(#/n,y1,1/n,y2-y1); $ else plotbar(1-(#+1)/n,y1,1/n,y2-y1); $ endif; $ end; $endfunction >function grayscales () ... $ aspect(2); barstyle("#"); $ window(0,0,1023,1023); margin(0); s...
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...
#FreeBASIC
FreeBASIC
' version 01-09-2017 ' compile with: fbc -s console ' or compile with: fbc -s gui ' hit any key to stop   Dim As UInteger d, blocks, blocksize, ps, col, h, w, x, y1, y2   ScreenInfo w, h ' create display size window, 8bit color (palette), no frame ScreenRes w, h, 8,, 8   For x = 0 To 255 ' create grayscale pa...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim hle As String Dim lowest As Integer = 1 Dim highest As Integer = 20 Dim guess As Integer = 10 Print "Please choose a number between 1 and 20 but don't tell me what it is yet" Print Do Print "My guess is"; guess Do Input "Is this higher/lower or equal to your chosen number h/l/e : "; hle ...
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...
#CLU
CLU
sum_dig_sq = proc (n: int) returns (int) sum_sq: int := 0 while n > 0 do sum_sq := sum_sq + (n // 10) ** 2 n := n / 10 end return (sum_sq) end sum_dig_sq   is_happy = proc (n: int) returns (bool) nn: int := sum_dig_sq(n) while nn ~= n cand nn ~= 1 do n := sum_dig_sq(n) ...
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...
#J
J
require 'trig' haversin=: 0.5 * 1 - cos Rearth=: 6372.8 haversineDist=: Rearth * haversin^:_1@((1 , *&(cos@{.)) +/ .* [: haversin -)&rfd  
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Verbexx
Verbexx
@STDOUT "Goodbye, World!";
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Verilog
Verilog
module main; initial begin $write("Goodbye, World!"); $finish ; end endmodule
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Vim_Script
Vim Script
echon "Goodbye, World!"
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Console.Write("Goodbye, World!") End Sub   End Module
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Frege
Frege
module HelloWorld where main _ = println "Hello world!"
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Scheme
Scheme
(define (lists->hash-table keys values . rest) (apply alist->hash-table (map cons keys values) rest))
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: numericHash is hash [string] integer; var numericHash: myHash is numericHash.value;   const proc: main is func local var array string: keyList is [] ("one", "two", "three"); var array integer: valueList is [] (1, 2, 3); var integer: number is 0; begin for numb...
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/...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
nextHarshad = NestWhile[# + 1 &, # + 1, ! Divisible[#, Total@IntegerDigits@#] &] &; Print@Rest@NestList[nextHarshad, 0, 20]; Print@nextHarshad@1000;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Gambas
Gambas
Message.Info("Goodbye, World!") ' Display a simple message box
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Genie
Genie
[indent=4] /* Genie GTK+ hello valac --pkg gtk+-3.0 hello-gtk.gs ./hello-gtk */ uses Gtk   init Gtk.init (ref args) var window = new Window (WindowType.TOPLEVEL) var label = new Label("Goodbye, World!") window.add(label) window.set_default_size(160, 100) window.show_all() window.destro...
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...
#Icon_and_Unicon
Icon and Unicon
  import gui $include "guih.icn"   # Provides a basic message dialog class MessageDialog : Dialog (message) method component_setup () label := Label ("label="||message, "pos=20,20") add (label) button := TextButton("label=OK", "pos=100,60") button.connect (self, "dispose", ACTION_EVENT) add (butto...
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 ...
#Arturo
Arturo
hamming: function [limit][ if limit=1 -> return 1 h: map 0..limit-1 'z -> 1 x2: 2, x3: 3, x5: 5 i: 0, j: 0, k: 0   loop 1..limit-1 'n [ set h n min @[x2 x3 x5] if x2 = h\[n] [ i: i + 1 x2: 2 * h\[i] ] if x3 = h\[n] [ j: j + 1 ...
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...
#AutoIt
AutoIt
  $irnd = Random(1, 10, 1) $iinput = -1 While $input <> $irnd $iinput = InputBox("Choose a number", "Please chosse a Number between 1 and 10") WEnd MsgBox(0, "Success", "Well guessed!")  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#AWK
AWK
  # syntax: GAWK -f GUESS_THE_NUMBER.AWK BEGIN { srand() n = int(rand() * 10) + 1 print("I am thinking of a number between 1 and 10. Try to guess it.") while (1) { getline ans if (ans !~ /^[0-9]+$/) { print("Your input was not a number. Try again.") continue } if ...
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...
#ATS
ATS
  (* ** This one is ** translated into ATS from the Ocaml entry *)   (* ****** ****** *) // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o maxsubseq maxsubseq.dats // (* ****** ****** *) // #include "share/atspre_staload.hats" // (* ****** ****** *)   typedef ints = List0(int)   (* ****** ****** *)   fun maxsubseq...
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...
#AutoHotkey
AutoHotkey
seq = -1,-2,3,5,6,-2,-1,4,-4,2,-1 max := sum := start := 0 Loop Parse, seq, `, If (max < sum+=A_LoopField) max := sum, a := start, b := A_Index Else If sum <= 0 sum := 0, start := A_Index ; read out the best subsequence Loop Parse, seq, `, s .= A_Index > a && A_Index <= b ? A_LoopField "," : "" Msg...
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...
#Python
Python
  #!/usr/bin/env python3   import tkinter as tk   class MyForm(tk.Frame):   def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack(expand=True, fill="both", padx=10, pady=10) self.master.title("Controls") self.setupUI()   def setupUI(self): self.value_...
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...
#Batch_File
Batch File
@echo off   :A set /a number=%random% %% 10 + 1 :B set /p guess=Choose a number between 1 and 10: if %guess equ %number% goto win if %guess% gtr 10 msg * "Number must be between 1 and 10." if %guess% leq 0 msg * "Number must be between 1 and 10." if %guess% gtr %number% echo Higher! if %guess% lss %number% echo Lower!...
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...
#Frink
Frink
  fakewidth =!= dummy   g = new graphics g.antialiased[false] drawBars[g, 0, 1, 0, 1/4, 8] drawBars[g, 1, 0, 1/4, 1/2, 16] drawBars[g, 0, 1, 1/2, 3/4, 32] drawBars[g, 1, 0, 3/4, 1, 64] g.show[640,480,1] // No portable fullscreen mode; user must maximize window.   drawBars[g is graphics, leftColor, rightColor, top, bot...
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...
#Gambas
Gambas
Public Sub Form_Open() Dim iRow, iCol, iClr As Integer 'For Row, Column and Colour Dim iInc As Integer = 4 'To calculate RGB colour Dim h1Panel As Panel 'Panels to display colours   With Me ...
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...
#Go
Go
package main   import ( "fmt" "sort" )   func main() { lower, upper := 0, 100 fmt.Printf(`Instructions: Think of integer number from %d (inclusive) to %d (exclusive) and I will guess it. After each guess, I will ask you if it is less than or equal to some number, and you will respond with "yes" or "no"....
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...
#CoffeeScript
CoffeeScript
happy = (n) -> seen = {} while true n = sum_digit_squares(n) return true if n == 1 return false if seen[n] seen[n] = true   sum_digit_squares = (n) -> sum = 0 for c in n.toString() d = parseInt(c) sum += d*d sum   i = 1 cnt = 0 while cnt < 8 if happy(i) console.log i cnt += 1...
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...
#Java
Java
public class Haversine { public static final double R = 6372.8; // In kilometers public static double haversine(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); lat1 = Math.toRadians(lat1); ...
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Vlang
Vlang
fn main() { print("Goodbye, World!") }
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Web_68
Web 68
@ @a@=#!/usr/bin/a68g -nowarn@>@\BEGIN print("Hello World") END
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Wren
Wren
System.write("Goodbye, World!")
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#XLISP
XLISP
(display "Goodbye, World!")
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#friendly_interactive_shell
friendly interactive shell
echo Hello world!
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#SenseTalk
SenseTalk
  set keyList to ["red", "green", "blue"] set valueList to [150,0,128]   repeat with n=1 to the number of items in keyList set map.(item n of keyList) to item n of valueList end repeat   put map --> (blue:"128", green:"0", red:"150")    
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Sidef
Sidef
var keys = %w(a b c) var vals = [1, 2, 3]   var hash = Hash() hash{keys...} = vals... say hash
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(A,B) ENTRY TO REM. FUNCTION RETURN A-A/B*B END OF FUNCTION   INTERNAL FUNCTION(I) ENTRY TO DSUM. SUM = 0 REST = I DIGIT WHENEVER REST.NE.0 SUM = S...
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#GlovePIE
GlovePIE
debug="⡧⢼⣟⣋⣇⣀⣇⣀⣏⣹⠀⠀⣇⣼⣏⣹⡯⡽⣇⣀⣏⡱⢘⠀"
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#GML
GML
draw_text(0,0,"Goodbye World!");
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#J
J
INTERACT=: noun define pc interact; cc Value edit center; cc increment button;cn "Increment"; cc random button;cn "Random"; pas 6 6;pcenter; )   interact_run=: verb define wd INTERACT wd 'set Value text 0;' wd 'pshow;' )   interact_cancel=: interact_close=: verb define wd'pclose' )   interact_Value_button=: verb de...
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...
#Java
Java
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;   import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField;   pub...
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 ...
#ATS
ATS
  // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o hamming hamming.dats // #include "share/atspre_staload.hats"   fun min3 ( A: arrayref(int, 3) ) : natLt(3) = i where { var x: int = A[0] var i: natLt(3) = 0 val () = if A[1] < x then (x := A[1]; i := 1) val () = if A[2] < x then (x := A[2]; i := 2) } (*...
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...
#BASIC
BASIC
10 N% = RND(1) * 10 + 1 20 PRINT "A NUMBER FROM 1 "; 30 PRINT "TO 10 HAS BEEN "; 40 PRINT "RANDOMLY CHOSEN." 50 FOR Q = 0 TO 1 STEP 0 60 INPUT "ENTER A GUESS. "; G% 70 Q = G% = N% 80 NEXT 90 PRINT "WELL GUESSED!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#BASIC256
BASIC256
n = int(rand * 10) + 1 print "I am thinking of a number from 1 to 10" do input "Guess it > ",g if g <> n then print "No luck, Try again." endif until g = n print "Yea! You guessed my number."
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#AutoIt
AutoIt
  Local $iArray[11] = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] GREAT_SUB($iArray) Local $iArray[5] = [-1, -2, -3, -4, -5] GREAT_SUB($iArray) Local $iArray[15] = [7, -6, -8, 5, -2, -6, 7, 4, 8, -9, -3, 2, 6, -4, -6] GREAT_SUB($iArray)   Func GREAT_SUB($iArray) Local $iSUM = 0, $iBEGIN_MAX = 0, $iEND_MAX = -1, $iMAX_SUM ...
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...
#R
R
  library(gWidgets) options(guiToolkit="RGtk2") ## using gWidgtsRGtk2   w <- gwindow("Disable components")   g <- ggroup(cont=w, horizontal=FALSE) e <- gedit("0", cont=g, coerce.with=as.numeric) bg <- ggroup(cont=g)   down_btn <- gbutton("-", cont=bg) up_btn <- gbutton("+", cont=bg)   update_ctrls <- function(h,...) { ...
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...
#BBC_BASIC
BBC BASIC
Min% = 1 Max% = 10 chosen% = RND(Max%-Min%+1) + Min% - 1 REPEAT PRINT "Guess a number between "; Min% " and " ;Max% ; INPUT ": " guess% CASE TRUE OF WHEN guess% < Min% OR guess% > Max%: PRINT "That was an invalid number" WHEN guess% < chose...
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...
#Go
Go
package main   import ( "github.com/fogleman/gg" "math" )   func greyBars(dc *gg.Context) { run := 0 colorComp := 0.0 // component of the color for colCount := 8; colCount < 128; colCount *= 2 { // by this gap we change the background color colorGap := 255.0 / float64(colCount-1) ...
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...
#Haskell
Haskell
import Graphics.UI.Gtk import Graphics.UI.Gtk.Gdk.GC import Control.Monad.Trans (liftIO)   -- click on the window to exit.   main = do initGUI   window <- windowNew   buf <- pixbufNewFromXPMData bars   widgetAddEvents window [ButtonPressMask] on window objectDestroy mainQuit on window exposeEven...
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...
#Haskell
Haskell
  main :: IO () main = do putStrLn "Please enter the range:" putStr "From: " from <- getLine putStr "To: " to <- getLine case (from, to) of (_) | [(from', "")] <- reads from , [(to' , "")] <- reads to , from' < to' -> loop from' to' (_)...
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...
#Common_Lisp
Common Lisp
(defun sqr (n) (* n n))   (defun sum-of-sqr-dgts (n) (loop for i = n then (floor i 10) while (plusp i) sum (sqr (mod i 10))))   (defun happy-p (n &optional cache) (or (= n 1) (unless (find n cache) (happy-p (sum-of-sqr-dgts n) (cons n cache)))))   (defun happys (&au...
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...
#JavaScript
JavaScript
function haversine() { var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; }); var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3]; var R = 6372.8; // km var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a =...
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#XPath
XPath
'Goodbye, World!'
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#XPL0
XPL0
code Text=12; Text(0, "Goodbye, World!")
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#XSLT
XSLT
<xsl:text>Goodbye, World!</xsl:text>
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#zkl
zkl
print("Goodbye, World!"); Console.write("Goodbye, World!");
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Zig
Zig
const std = @import("std");   pub fn main() !void { try std.io.getStdOut().writer().writeAll("Hello world!"); }
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Frink
Frink
  println["Hello world!"]  
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Smalltalk
Smalltalk
Array extend [ dictionaryWithValues: array [ |d| d := Dictionary new. 1 to: ((self size) min: (array size)) do: [:i| d at: (self at: i) put: (array at: i). ]. ^ d ] ].     ({ 'red' . 'one' . 'two' } dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#SNOBOL4
SNOBOL4
* # Fill arrays keys = array(5); vals = array(5) ks = 'ABCDE'; vs = '12345' kloop i = i + 1; ks len(1) . keys<i> = :s(kloop) vloop j = j + 1; vs len(1) . vals<j> = :s(vloop)   * # Create hash hash = table(5) hloop k = k + 1; hash<keys<k>> = vals<k> :s(hloop)   * # Test an...
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/...
#MATLAB_.2F_Octave
MATLAB / Octave
function v = isharshad(n) v = isinteger(n) && ~mod(n,sum(num2str(n)-'0')); end;
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Go
Go
package main   import "github.com/mattn/go-gtk/gtk"   func main() { gtk.Init(nil) win := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) win.SetTitle("Goodbye, World!") win.SetSizeRequest(300, 200) win.Connect("destroy", gtk.MainQuit) button := gtk.NewButtonWithLabel("Goodbye, World!") win.Add(button) button...
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...
#Julia
Julia
#= The task: For a minimal "application", write a program that presents a form with three components to the user: A numeric input field ("Value") and two buttons ("increment" and "random"). =#   using Tk   w = Toplevel("Component Interaction Example") fr = Frame(w) pack(fr, expand=true, fill="both")   value = Entry(fr,...
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...
#Kotlin
Kotlin
import java.awt.GridLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.KeyListener import javax.swing.*   class Interact : JFrame() { val numberField = JTextField() val incButton = JButton("Increment") val randButton = JButton("...
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 ...
#AutoHotkey
AutoHotkey
SetBatchLines, -1 Msgbox % hamming(1,20) Msgbox % hamming(1690) return   hamming(first,last=0) { if (first < 1) ans=ERROR   if (last = 0) last := first   i:=0, j:=0, k:=0   num1 := ceil((last * 20)**(1/3)) num2 := ceil(num1 * ln(2)/ln(3)) num3 := ceil(num1 * ln(2)/ln(5))   loop { H := (2**i) * (3**j) * (5...
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...
#Batch_File
Batch File
@echo off set /a answer=%random%%%(10-1+1)+1 set /p guess=Pick a number between 1 and 10: :loop if %guess%==%answer% (echo Well guessed! pause) else (set /p guess=Nope, guess again: goto loop)
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#BBC_BASIC
BBC BASIC
choose% = RND(10) REPEAT INPUT "Guess a number between 1 and 10: " guess% IF guess% = choose% THEN PRINT "Well guessed!" END ELSE PRINT "Sorry, try again" ENDIF UNTIL FALSE
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#AWK
AWK
# Finds the subsequence of ary[1] to ary[len] with the greatest sum. # Sets subseq[1] to subseq[n] and returns n. Also sets subseq["sum"]. # An empty subsequence has sum 0. function maxsubseq(subseq, ary, len, b, bp, bs, c, cp, i) { b = 0 # best sum c = 0 # current sum bp = 0 # position of best subsequence bn...
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...
#Racket
Racket
  #lang racket/gui   (define frame (new frame% [label "Interaction Demo"]))   (define (changed . _) (define s (send inp get-value)) (define v (string->number s)) (unless v (set! v (or (string->number (regexp-replace* #rx"[^0-9]+" s "")) 0)) (send inp set-value (~a v))) (send inc-b enable (< v 10)) ...
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...
#Raku
Raku
use GTK::Simple; use GTK::Simple::App;   my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );   $app.set-content( my $box = GTK::Simple::HBox.new( my $inc = GTK::Simple::Button.new( label => ' + ' ), my $value = GTK::Simple::Entry.new, my $dec = GTK::Simple::Button.ne...
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...
#BCPL
BCPL
get "libhdr" static $( randstate = ? $)   let rand(min,max) = valof $( let x = ? let range = max-min let mask = 1 while mask < range do mask := (mask << 1) | 1 $( randstate := random(randstate) x := (randstate >> 6) & mask $) repeatuntil 0 <= x < range resultis x + min $)   let readgue...
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...
#Icon_and_Unicon
Icon and Unicon
link graphics,printf,numbers   procedure main() DrawTestCard(GreyScale_TestCard()) WDone() end   procedure greyscale(l,h,s) #: generate s greys over range l:h every i := round(l to h+1 by ((h-l)/(s-1.))) do suspend sprintf("%d,%d,%d",i,i,i) # return rgb black-grey-white end   procedure 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...
#Icon_and_Unicon
Icon and Unicon
  procedure main () lower_limit := 1 higher_limit := 100   write ("Think of a number between 1 and 100") write ("Press 'enter' when ready") read ()   repeat { if (higher_limit < lower_limit) then { # check that player is not cheating! write ("Something has gone wrong ... I give up") ...
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...
#Cowgol
Cowgol
include "cowgol.coh";   sub sumDigitSquare(n: uint8): (s: uint8) is s := 0; while n != 0 loop var d := n % 10; s := s + d * d; n := n / 10; end loop; end sub;   sub isHappy(n: uint8): (h: uint8) is var seen: uint8[256]; MemZero(&seen[0], @bytesof seen);   while seen[n] ==...
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...
#jq
jq
def haversine(lat1;lon1; lat2;lon2): def radians: . * (1|atan)/45; def sind: radians|sin; def cosd: radians|cos; def sq: . * .;   (((lat2 - lat1)/2) | sind | sq) as $dlat | (((lon2 - lon1)/2) | sind | sq) as $dlon | 2 * 6372.8 * (( $dlat + (lat1|cosd) * (lat2|cosd) * $dlon ) | sqrt | asin) ;
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Jsish
Jsish
/* Haversine formula, in Jsish */ function haversine() { var radians = arguments.map(function(deg) { return deg/180.0 * Math.PI; }); var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3]; var R = 6372.8; // km var dLat = lat2 - lat1; var dLon = lon2 - lon1; ...
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM The trailing semicolon prevents a newline 20 PRINT "Goodbye, World!";
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#FunL
FunL
println( 'Hello world!' )
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Sparkling
Sparkling
let keys = { "foo", "bar", "baz" }; let vals = { 13, 37, 42 }; var hash = {}; for var i = 0; i < sizeof keys; i++ { hash[keys[i]] = vals[i]; }
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Standard_ML
Standard ML
structure StringMap = BinaryMapFn (struct type ord_key = string val compare = String.compare end);   val keys = [ "foo", "bar", "baz" ] and vals = [ 16384, 32768, 65536 ] and myMap = StringMap.empty;   val myMap...
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/...
#Modula-2
Modula-2
MODULE Harshad; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   VAR n, i: CARDINAL;   PROCEDURE DigitSum(n: CARDINAL): CARDINAL; VAR sum: CARDINAL; BEGIN sum := 0; WHILE n > 0 DO; sum := sum + n MOD 10; n := n DIV 10; END; RETURN sum; END DigitSum;   PROCEDURE NextHarshad(n: CARDINA...
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Groovy
Groovy
import groovy.swing.SwingBuilder import javax.swing.JFrame   new SwingBuilder().edt { optionPane().showMessageDialog(null, "Goodbye, World!") frame(title:'Goodbye, World!', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show: true) { flowLayout() button(text:'Goodbye, World!') textArea(text:'Goo...
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...
#Lambdatalk
Lambdatalk
  {input {@ id="input" type="text" value="0"}} {input {@ type="button" value="increment" onclick="document.getElementById('input').value = parseInt( document.getElementById('input').value ) + 1;"}} {input {@ type="button" value="random" onclick="if (confirm( 'yes?' )) ...
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...
#Liberty_BASIC
Liberty BASIC
nomainwin textbox #demo.val, 20, 50, 90, 24 button #demo.inc, "Increment", [btnIncrement], UL, 20, 90, 90, 24 button #demo.rnd, "Random", [btnRandom], UL, 20, 120, 90, 24 open "Rosetta Task: GUI component interaction" for window as #demo #demo "trapclose [quit]" validNum$ = "0123456789." #de...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#11l
11l
T Colour Byte r, g, b   F (r, g, b) .r = r .g = g .b = b   F ==(other) R .r == other.r & .g == other.g & .b == other.b   V black = Colour(0, 0, 0) V white = Colour(255, 255, 255)   T Bitmap Int width, height Colour background [[Colour]] map   F (width = 40, height = 40, back...
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 ...
#AWK
AWK
  # syntax: gawk -M -f hamming_numbers.awk BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (...
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...
#Befunge
Befunge
v RNG anthouse > v ,,,,,,< v?v , vvvvv , v?????v , vvvvvvvvv , >?????????v , >vvvvvvvvvv< , >??????????< , >vvvvvvvvvv< , >??????????< , >vvvvvvvvvv< ^"Well guessed!"< >??????????< >"oN",,91v actua...
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...
#Bracmat
Bracmat
( ( GuessTheNumber = mynumber . clk$:?mynumber & mod$(!mynumber*den$!mynumber.10)+1:?mynumber & whl ' ( put'"Guess my number:" & get':~!mynumber:?K ) & out'"Well guessed!" ) & GuessTheNumber$ );
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#BBC_BASIC
BBC BASIC
DIM A%(11) : A%() = 0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2 PRINT FNshowarray(A%()) " -> " FNmaxsubsequence(A%()) DIM B%(10) : B%() = -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 PRINT FNshowarray(B%()) " -> " FNmaxsubsequence(B%()) DIM C%(4) : C%() = -1, -2, -3, -4, -5 PRINT FNshowarray(C%...
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...
#Bracmat
Bracmat
  ( 0:?max & :?seq & -1 -2 3 5 6 -2 -1 4 -4 2 -1  :  ? [%( ( = s sum . ( sum = A .  !arg:%?A ?arg&!A+sum$!arg | 0 ) & ( sum$!sjt:>!max:?max ...
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...
#Red
Red
Red[]   enable: does [ f/enabled?: 0 = n i/enabled?: 10 > n d/enabled?: 0 < n ]   view [ f: field "0" [either error? try [n: to-integer f/text] [f/text: "0"] [enable]] i: button "increment" [f/text: mold n: add to-integer f/text 1 enable] d: button "decrement" disabled [f/text: mold n: subtract ...
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...
#Befunge
Befunge
1:"d">>048*"neewteb rebmun a sseuG">:#,_$\:.\"d na",,\,,:.55+,\-88+0v <*2\_$\1+%+48*">",,#v>#+:&#>#5-:!_0`00p0"hgih"00g>_0"wol"00g!>_48vv1? \1-:^v"d correctly!"<^,,\,+55,". >"$_,#!>#:<"Your guess was too"*<>+> :#,_@>"ess" >"eug uoY">
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#J
J
load 'viewmat' size=. 2{.".wd'qm' NB. J6 size=. getscreenwh_jgtk_ '' NB. J7 rows=. (2^3+i.4),._1^i.4 bars=. ((64%{.)#[:(<:@|%~i.)*/)"1 rows togreyscale=. (256#. [:<.255 255 255&*)"0 'rgb' viewmat (4<.@%~{:size)# (64<.@%~{.size)#"1 togreyscale bars
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Java
Java
import javax.swing.* ; import java.awt.* ;   public class Greybars extends JFrame { private int width ; private int height ;   public Greybars( ) { super( "grey bars example!" ) ; width = 640 ; height = 320 ; setSize( width , height ) ; setDefaultCloseOperation( JFrame.EXIT_ON_CL...
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...
#IS-BASIC
IS-BASIC
100 PROGRAM "GuessIt.bas" 110 LET N=100 120 TEXT 80 130 PRINT "Choose a number between 1 and;" N:PRINT "I will start guess the number." 140 LET BL=1:LET UL=100:LET NR=0 150 DO 160 LET GUESS=INT((BL+UL)/2):LET NR=NR+1 170 SET #102:INK 3:PRINT :PRINT "My";NR;". guess: ";GUESS:SET #102:INK 1 180 LET ANSWER=QUESTION ...