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/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#J
J
require 'misc' guess=:3 :0 'lo hi'=.y while.lo < hi do. smoutput 'guessing a number between ',(":lo),' and ',":hi guess=.lo+?hi-lo select.{.deb tolower prompt 'is it ',(":guess),'? ' case.'y'do. smoutput 'Win!' return. case.'l'do. lo=.guess+1 case.'h'do. hi=.guess-1 case.'q'do. smoutput 'giving up' return. case. do. smouput 'options: yes, low, high, quit' end. end. )
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Crystal
Crystal
def happy?(n) past = [] of Int32 | Int64 until n == 1 sum = 0; while n > 0; sum += (n % 10) ** 2; n //= 10 end return false if past.includes? (n = sum) past << n end true end   i = count = 0 until count == 8; (puts i; count += 1) if happy?(i += 1) end puts (99999999999900..99999999999999).each { |i| puts i if happy?(i) }
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Julia
Julia
haversine(lat1, lon1, lat2, lon2) = 2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 + cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2))   @show haversine(36.12, -86.67, 33.94, -118.4)
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Kotlin
Kotlin
import java.lang.Math.*   const val R = 6372.8 // in kilometers   fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val λ1 = toRadians(lat1) val λ2 = toRadians(lat2) val Δλ = toRadians(lat2 - lat1) val Δφ = toRadians(lon2 - lon1) return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2))) }   fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))
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
#Furor
Furor
."Hello, World!\n"
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Swift
Swift
let keys = ["a","b","c"] let vals = [1,2,3] var hash = [String: Int]() for (key, val) in zip(keys, vals) { hash[key] = val }
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
#Tcl
Tcl
set keys [list fred bob joe] set values [list barber plumber tailor] array set arr {} foreach a $keys b $values { set arr($a) $b }   parray arr
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#min
min
(  :n () =list (n 0 >) ( n 10 mod list prepend #list n 10 div @n ) while list ) :digits   (dup digits sum mod 0 ==) :harshad?   ( succ :n (n harshad? not) ( n succ @n ) while n ) :next-harshad   0 (next-harshad print " " print!) 20 times newline 1000 next-harshad print!
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
#GUISS
GUISS
Start,Programs,Accessories,Notepad,Type:Goodbye[comma][space]World[pling]
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
#Harbour
Harbour
PROCEDURE Main() RETURN wapi_MessageBox(,"Goodbye, World!","")  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Declare form1 form Declare textbox1 textbox form form1 Declare buttonInc Button form form1 Declare buttonRND Button form form1 Method textbox1, "move", 2000,2000,4000,600 Method buttonInc, "move", 2000,3000,2000,600 Method buttonRND, "move", 4000,3000,2000,600 With form1, "Title", "Rosetta Code: GUI component interaction" With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:", "ShowAlways", true With buttonInc,"Caption","Increment" With buttonRND,"Caption","Random" textbox1.value$="0" Function Local1(new Feed$) { \\ this Function can be used from other Integer \\ this$ and thispos, exist just before the call of this Function local sgn$ if feed$="" and this$="-" then thispos-- : exit if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2) if this$<>Trim$(this$) then this$=Feed$ : thispos-- : exit If Trim$(this$)="" then this$="0" : thispos=2 : exit if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$="" if instr(this$,"-")>0 and sgn$="" then this$=filter$(this$, "-") : sgn$="-" if filter$(this$,"0123456789")<>"" then this$=Feed$ : thispos-- : exit if len(this$)>1 then While left$(this$,1)="0" {this$=mid$(this$, 2)} this$=sgn$+this$ if this$="-0" then this$="-" : thispos=2 } Function TextBox1.ValidString { \\ this Function called direct from textbox Read New &this$, &thispos Call Local local1(textbox1.value$) } Function buttonInc.Click { textbox1.value$=str$(val(textbox1.value$)+1, "") } Function buttonRND.Click { If AsK$("Change Value with random number", "Question", "Yes", "No")="Yes" Then { textbox1.value$=str$(Random(0, 10000), "") After 100 {Try {Method textbox1,"GetFocus"}} } } \\ open modal Method form1, "show", 1 Declare form1 nothing } Checkit  
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Maple
Maple
  Increase();  
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Action.21
Action!
INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image   PROC PrintB3(BYTE x) IF x<10 THEN Print(" ") ELSEIF x<100 THEN Print(" ") FI PrintB(x) RETURN   PROC PrintRgbImage(RgbImage POINTER img) BYTE x,y RGB c   FOR y=0 TO img.h-1 DO FOR x=0 TO img.w-1 DO GetRgbPixel(img,x,y,c) Put(32) PrintB3(c.r) Put(32) PrintB3(c.g) Put(32) PrintB3(c.b) Put(32) OD PutE() OD RETURN   PROC PrintGrayImage(GrayImage POINTER img) BYTE x,y,c   FOR y=0 TO img.h-1 DO FOR x=0 TO img.w-1 DO c=GetGrayPixel(img,x,y) Put(32) PrintB3(c) OD PutE() OD RETURN   PROC Main() BYTE ARRAY rgbdata=[ 0 0 0 0 0 255 0 255 0 255 0 0 0 255 255 255 0 255 255 255 0 255 255 255 31 63 127 63 31 127 127 31 63 127 63 31] BYTE ARRAY graydata(12) BYTE width=[3],height=[4],LMARGIN=$52,oldLMARGIN RgbImage rgbimg GrayImage grayimg   oldLMARGIN=LMARGIN LMARGIN=0 ;remove left margin on the screen Put(125) PutE() ;clear the screen InitRgbToGray() InitRgbImage(rgbimg,width,height,rgbdata) InitGrayImage(grayimg,width,height,graydata)   PrintE("Original RGB image:") PrintRgbImage(rgbimg) PutE()   RgbToGray(rgbimg,grayimg) PrintE("RGB to grayscale image:") PrintGrayImage(grayimg) PutE()   GrayToRgb(grayimg,rgbimg) PrintE("Grayscale to RGB image:") PrintRgbImage(rgbimg)   LMARGIN=oldLMARGIN ;restore left margin on the screen RETURN
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Ada
Ada
type Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance;
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#BASIC256
BASIC256
w = 143 h = 188 name$ = "Mona_Lisa.jpg" graphsize w,h imgload w/2, h/2, name$ fastgraphics   for x = 0 to w-1 for y = 0 to h-1 p = pixel(x,y) b = p % 256 p = p \256 g = p % 256 p = p \ 256 r = p % 256 l = 0.2126*r + 0.7152*g + 0.0722*b color rgb(l,l,l) plot x,y next y refresh next x   imgsave "Grey_"+name$,"jpg"
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#Aime
Aime
  ' Go Fish ~ ¡Pesca!   Const cartas = "A234567890JQK"   Declare Sub Reparto_Cartas Declare Sub Pescar_Carta_Jug Declare Sub Pescar_Carta_CPU Declare Sub Comprobar_Libro_Jug Declare Sub Comprobar_Libro_CPU Declare Sub Comprobar_Fin_Partida Declare Sub Intro   Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13) Dim Shared As String nombre, Snombre, CartaPedida Dim Shared puntos(2) As Byte = {0,0} Dim Shared As Integer remca = 4*Len(cartas) Dim Shared As Integer i, k, j, cn For i = 1 To 13 deck(i) = 4 Next i For i = 1 To 9 Reparto_Cartas deck(k) -= 1 compu(k) += 1 Reparto_Cartas deck(k) -= 1 play(k) += 1 Next i Dim As Integer v, po   Sub Reparto_Cartas remca -= 1 Dim As Integer sc = remca * Rnd + 1 For k = 1 To 13 sc -= deck(k) If sc <= 0 Then Return Next k End Sub   Sub Pescar_Carta_Jug Reparto_Cartas Print " " &Mid(cartas,k,1) &"." deck(k) -= 1 play(k) += 1 End Sub   Sub Pescar_Carta_CPU Reparto_Cartas Print "a carta." deck(k) -= 1 compu(k) += 1 End Sub   Sub Comprobar_Libro_Jug For i = 1 To 13 If play(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 play(i) = 0 puntos(0) += 1 End If Next i End Sub   Sub Comprobar_Libro_CPU For i = 1 To 13 If compu(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 compu(i) = 0 puntos(1) += 1 End If Next i End Sub   Sub Comprobar_Fin_Partida Dim As Integer np = 0, nc = 0 For i = 1 To 13 np += play(i) nc += compu(i) Next i If remca = 0 Or np = 0 Or nc = 0 Then Color 15: Print Print "*** ­FIN de la partida! ***" Print If puntos(0) < puntos(1) Then Print "La CPU ha ganado." Elseif puntos(0) > puntos(1) Then Print nombre &" ha ganado." Else Print "­Es un empate!" End If Sleep: End End If End Sub   Sub Intro Color 15 Print " __ _ _ " Print " __ _ ___ / _(_)___| |__ " Print " / ` |/ _ \ | |_| / __| '_ \ " Print "| (_) | (_) | | _| \__ \ | | | " Print " \__, |\___/ |_| |_|___/_| |_| " Print " |___/ " Print " " Color 14: Locate 10, 2: Input "Como te llamas: ", nombre End Sub   '--- Programa Principal --- Cls Randomize Timer Intro Do Dim As boolean MuestraMano = false While MuestraMano = false Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1) Color 13: Print Chr(10) &space(10) &remca &" cartas restantes" Color 14: Print Chr(10) &"Tu mano: "; For i = 1 To 13 If Not play(i) Then For j = 1 To play(i) Print Mid(cartas,i,1); " "; Next j End If Next i Print   Dim As boolean PideCarta = false While PideCarta = false Comprobar_Fin_Partida Snombre = nombre Color 7: Print Input "¨Que carta pides... "; CartaPedida Print If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true If cn = 0 Then Print "Lo siento, no es una opción valida.": PideCarta = false Elseif play(cn) = 0 Then Color 12: Print "­No tienes esa carta!": Color 7: PideCarta = false End If Wend   guess(cn) = 1 If compu(cn) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug Comprobar_Libro_Jug MuestraMano = true Else v = compu(cn) compu(cn) = 0 play(cn) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_Jug MuestraMano = false End If Wend   Snombre = "CPU" For i = 1 To 13 asked(i) = 0 Next i Dim As boolean Turno_CPU_2 = false While Turno_CPU_2 = false Comprobar_Fin_Partida po = 0 For i = 1 To 13 If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1 Next i If po = 0 Then Do k = (Rnd*12)+1 Loop While compu(k) = 0 Or asked(k) Else Do k = (Rnd*12)+1 Loop While poss(k) = 0 guess(k) = 0 asked(k) = 1 End If   Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s." asked(k) = 1 If play(k) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU Comprobar_Libro_CPU Turno_CPU_2 = true Else v = play(k) play(k) = 0 compu(k) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_CPU Turno_CPU_2 = false End If Wend Loop End  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#BASIC256
BASIC256
print "The first 20 Hamming numbers are :" for i = 1 to 20 print Hamming(i);" "; next i   print print "H( 1691) = "; Hamming(1691) end   function min(a, b) if a < b then return a else return b end function   function Hamming(limit) dim h(1000000)   h[0] = 1 x2 = 2 : x3 = 3 : x5 = 5 i = 0 : j = 0 : k = 0 for n = 1 to limit h[n] = min(x2, min(x3, x5)) if x2 = h[n] then i += 1: x2 = 2 *h[i] if x3 = h[n] then j += 1: x3 = 3 *h[j] if x5 = h[n] then k += 1: x5 = 5 *h[k] next n return h[limit -1] end function
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Brat
Brat
number = random 10   p "Guess a number between 1 and 10."   until { true? ask("Guess: ").to_i == number { p "Well guessed!"; true } { p "Guess again!" } }
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#C
C
#include <stdlib.h> #include <stdio.h> #include <time.h>   int main(void) { int n; int g; char c;   srand(time(NULL)); n = 1 + (rand() % 10);   puts("I'm thinking of a number between 1 and 10."); puts("Try to guess it:");   while (1) { if (scanf("%d", &g) != 1) { /* ignore one char, in case user gave a non-number */ scanf("%c", &c); continue; }   if (g == n) { puts("Correct!"); return 0; } puts("That's not my number. Try another guess:"); } }
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#C
C
#include "stdio.h"   typedef struct Range { int start, end, sum; } Range;   Range maxSubseq(const int sequence[], const int len) { int maxSum = 0, thisSum = 0, i = 0; int start = 0, end = -1, j;   for (j = 0; j < len; j++) { thisSum += sequence[j]; if (thisSum < 0) { i = j + 1; thisSum = 0; } else if (thisSum > maxSum) { maxSum = thisSum; start = i; end = j; } }   Range r; if (start <= end && start >= 0 && end >= 0) { r.start = start; r.end = end + 1; r.sum = maxSum; } else { r.start = 0; r.end = 0; r.sum = 0; } return r; }   int main(int argc, char **argv) { int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1}; int alength = sizeof(a)/sizeof(a[0]);   Range r = maxSubseq(a, alength); printf("Max sum = %d\n", r.sum); int i; for (i = r.start; i < r.end; i++) printf("%d ", a[i]); printf("\n");   return 0; }
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#Ring
Ring
  Load "guilib.ring"   MyApp = New qApp { num = 0 win1 = new qWidget() { setwindowtitle("Hello World") setGeometry(100,100,370,250)   btn1 = new qpushbutton(win1) { setGeometry(50,200,100,30) settext("Increment") setclickevent("Increment()")}   btn2 = new qpushbutton(win1) { setGeometry(200,200,100,30) settext("Decrement") setclickevent("Decrement()")}   lineedit1 = new qlineedit(win1) { setGeometry(10,100,350,30) settext("0")} show()} exec()}   func Increment lineedit1{ num = text()} num = string(number(num)+1) lineedit1.settext(num) if number(num)>9 btn1.setDisabled(True) ok   func Decrement lineedit1{ num = text()} num = string(number(num)-1) lineedit1.settext(num) if number(num)<0 btn2.setDisabled(True) ok  
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#Brat
Brat
number = random 10   p "Guess a number between 1 and 10."   until { guess = ask("Guess: ").to_i   true? (guess.null? || { guess > 10 || guess < 1 }) { p "Please guess a number between 1 and 10."} { true? guess == number { p "Correct!"; true } { true? guess < number { p "Too low!" } { p "Too high!" } } } }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#JavaScript
JavaScript
<html><body> <script type="text/javascript"> var width = 640; var height = 400; var c = document.createElement("canvas"); c.setAttribute('id', 'myCanvas'); c.setAttribute('style', 'border:1px solid black;'); c.setAttribute('width', width); c.setAttribute('height', height); document.body.appendChild(c); var ctx = document.getElementById('myCanvas').getContext("2d");   var columnCount = 8; // number of columns var rowCount = 4; // number of rows var direction = 1; // 1 = from left to right, 0 = from right to left var blackLeft = 1; // black is left: 1 = true, 0 = false for(var j = 0; j < rowCount; j++){ for(var i = 0; i < columnCount; i++){ ctx.fillStyle = 'rgba(0,0,0,'+ (blackLeft-(1/(columnCount-1)*i))*direction +')'; ctx.fillRect( (width/columnCount)*i,(height/rowCount)*j, (width/columnCount),(height/rowCount) ); } columnCount *= 2; direction *= -1; blackLeft = blackLeft ? 0 : 1; } </script> </body></html>  
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Java
Java
import java.util.AbstractList; import java.util.Collections; import java.util.Scanner;   public class GuessNumber { public static final int LOWER = 0, UPPER = 100; public static void main(String[] args) { System.out.printf("Instructions:\n" + "Think of integer number from %d (inclusive) to %d (exclusive) and\n" + "I will guess it. After each guess, you respond with L, H, or C depending\n" + "on if my guess was too low, too high, or correct.\n", LOWER, UPPER); int result = Collections.binarySearch(new AbstractList<Integer>() { private final Scanner in = new Scanner(System.in); public int size() { return UPPER - LOWER; } public Integer get(int i) { System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i); String s = in.nextLine(); assert s.length() > 0; switch (Character.toLowerCase(s.charAt(0))) { case 'l': return -1; case 'h': return 1; case 'c': return 0; } return -1; } }, 0); if (result < 0) System.out.println("That is impossible."); else System.out.printf("Your number is %d.\n", result); } }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#D
D
bool isHappy(int n) pure nothrow { int[int] past;   while (true) { int total = 0; while (n > 0) { total += (n % 10) ^^ 2; n /= 10; } if (total == 1) return true; if (total in past) return false; n = total; past[total] = 0; } }   void main() { import std.stdio, std.algorithm, std.range;   int.max.iota.filter!isHappy.take(8).writeln; }
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Liberty_BASIC
Liberty BASIC
print "Haversine distance: "; using( "####.###########", havDist( 36.12, -86.67, 33.94, -118.4)); " km." end function havDist( th1, ph1, th2, ph2) degtorad = acs(-1)/180 diameter = 2 * 6372.8 LgD = degtorad * (ph1 - ph2) th1 = degtorad * th1 th2 = degtorad * th2 dz = sin( th1) - sin( th2) dx = cos( LgD) * cos( th1) - cos( th2) dy = sin( LgD) * cos( th1) havDist = asn( ( dx^2 +dy^2 +dz^2)^0.5 /2) *diameter end function
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
#FutureBasic
FutureBasic
window 1 print @"Hello world!"   HandleEvents
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
#TXR
TXR
$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))' #H(() (c 3) (b 2) (a 1))
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
#UNIX_Shell
UNIX Shell
keys=( foo bar baz ) values=( 123 456 789 ) declare -A hash   for (( i = 0; i < ${#keys[@]}; i++ )); do hash["${keys[i]}"]=${values[i]} done   for key in "${!hash[@]}"; do printf "%s => %s\n" "$key" "${hash[$key]}" done
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#MLite
MLite
fun sumdigits (0, n) = n | (m, n) = sumdigits (m div 10, m rem 10) + n | n = sumdigits (n div 10, n rem 10)   fun is_harshad n = (n rem (sumdigits n) = 0)   fun next_harshad_after (n, ~1) = if is_harshad n then n else next_harshad_after (n + 1, ~1) | n = next_harshad_after (n + 1, ~1)   fun harshad (max, _, count > max, accum) = rev accum | (max, here, count, accum) = if is_harshad here then harshad (max, here + 1, count + 1, here :: accum) else harshad (max, here + 1, count, accum) | max = harshad (max, 1, 1, [])   ;   print "first twenty harshad numbers = "; println ` harshad 20; print "first harshad number after 1000 = "; println ` next_harshad_after 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
#Haskell
Haskell
import Graphics.UI.Gtk import Control.Monad   messDialog = do initGUI dialog <- messageDialogNew Nothing [] MessageInfo ButtonsOk "Goodbye, World!"   rs <- dialogRun dialog when (rs == ResponseOk || rs == ResponseDeleteEvent) $ widgetDestroy dialog   dialog `onDestroy` mainQuit   mainGUI
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &}, Row@{Button["increment", value++], Button["random", If[DialogInput[ Column@{"Are you sure?", Row@{Button["Yes", DialogReturn[True]], Button["No", DialogReturn[False]]}}], value = RandomInteger@10000], Method -> "Queued"]}]
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Nim
Nim
import gtk2, glib2, strutils, random   var valu: int = 0   proc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} = main_quit()   randomize() nim_init() var win = window_new(gtk2.WINDOW_TOPLEVEL) var content = vbox_new(true,10) var hbox1 = hbox_new(true,10) var hbox2 = hbox_new(false,1) var lbl = label_new("Value:") var entry_fld = entry_new() entry_fld.set_text("0") var btn_quit = button_new("Quit") var btn_inc = button_new("Increment") var btn_rnd = button_new("Random") add(hbox2,lbl) add(hbox2,entry_fld) add(hbox1,btn_inc) add(hbox1,btn_rnd) pack_start(content, hbox2, true, true, 0) pack_start(content, hbox1, true, true, 0) pack_start(content, btn_quit, true, true, 0) set_border_width(win, 5) add(win, content)   proc on_question_clicked: bool = var dialog = win.message_dialog_new(0, MESSAGE_QUESTION, BUTTONS_YES_NO, "Use a Random number?") var response = dialog.run() result = response == RESPONSE_YES dialog.destroy()   proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} = inc(valu) entry_fld.set_text($valu)   proc thisRnd(widget: PWidget, data: Pgpointer){.cdecl.} = if on_question_clicked(): valu = rand(20) entry_fld.set_text($valu)   proc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} = try: valu = parseInt($entry_fld.get_text()) except ValueError: entry_fld.set_text($valu)   discard signal_connect(win, "destroy", SIGNAL_FUNC(thisDestroy), nil) discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil) discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil) discard signal_connect(btn_rnd, "clicked", SIGNAL_FUNC(thisRnd), nil) discard signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil)   win.show_all() main()
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#11l
11l
max(values)
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected. Only unconnected nodes need a separate description. For example, 0-1 1-2 2-0 3 Describes the following graph. Note that node 3 has no neighbours Example graph +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ A useful internal datastructure for a graph and for later graph algorithms is as a mapping between each node and the set/list of its neighbours. In the above example: 0 maps-to 1 and 2 1 maps to 2 and 0 2 maps-to 1 and 0 3 maps-to <nothing> Graph colouring task Colour the vertices of a given graph so that no edge is between verticies of the same colour. Integers may be used to denote different colours. Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement). Show for each edge, the colours assigned on each vertex. Show the total number of nodes, edges, and colours used for each graph. Use the following graphs Ex1 0-1 1-2 2-0 3 +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ Ex2 The wp articles left-side graph 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7 +----------------------------------+ | | | +---+ | | +-----------------| 3 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 6 | --- | 4 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 7 | --- | 2 | --- | 5 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex3 The wp articles right-side graph which is the same graph as Ex2, but with different node orderings and namings. 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6 +----------------------------------+ | | | +---+ | | +-----------------| 5 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 4 | --- | 7 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 6 | --- | 3 | --- | 2 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex4 This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x. This might alter the node order used in the greedy algorithm leading to differing numbers of colours. 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7 +-------------------------------------------------+ | | | | +-------------------+---------+ | | | | | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | | | | | | +---------+-----------------------------+---------+ | | | | | | | | | | +-----------------------------+-------------------+ | | | | | +-----------------------------+ References Greedy coloring Wikipedia. Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
#11l
11l
F first_avail_int(data) ‘return lowest int 0... not in data’ V d = Set(data) L(i) 0.. I i !C d R i   F greedy_colour(name, connections) DefaultDict[Int, [Int]] graph   L(connection) connections.split(‘ ’) I ‘-’ C connection V (n1, n2) = connection.split(‘-’).map(Int) graph[n1].append(n2) graph[n2].append(n1) E graph[Int(connection)] = [Int]()   // Greedy colourisation algo V order = sorted(graph.keys()) [Int = Int] colour V neighbours = graph L(node) order V used_neighbour_colours = neighbours[node].filter(nbr -> nbr C @colour).map(nbr -> @colour[nbr]) colour[node] = first_avail_int(used_neighbour_colours)   print("\n"name) V canonical_edges = Set[(Int, Int)]() L(n1, neighbours) sorted(graph.items()) I !neighbours.empty L(n2) neighbours V edge = tuple_sorted((n1, n2)) I edge !C canonical_edges print(‘ #.-#.: Colour: #., #.’.format(n1, n2, colour[n1], colour[n2])) canonical_edges.add(edge) E print(‘ #.: Colour: #.’.format(n1, colour[n1])) V lc = Set(colour.values()).len print(" #Nodes: #.\n #Edges: #.\n #Colours: #.".format(colour.len, canonical_edges.len, lc))   L(name, connections) [ (‘Ex1’, ‘0-1 1-2 2-0 3’), (‘Ex2’, ‘1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7’), (‘Ex3’, ‘1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6’), (‘Ex4’, ‘1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7’)] greedy_colour(name, connections)
http://rosettacode.org/wiki/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function. The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes. Examples G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2) G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19) Task Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4) Find and display the value of G(1000000) Stretch Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet See also Wikipedia: Goldbach's conjecture OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
#ALGOL_68
ALGOL 68
BEGIN # calculate values of the Goldbach function G where G(n) is the number # # of prime pairs that sum to n, n even and > 2 # # generates an ASCII scatter plot of G(n) up to G(2000) # # (Goldbach's Comet) # PR read "primes.incl.a68" PR # include prime utilities # INT max prime = 1 000 000; # maximum number we will consider # INT max plot = 2 000; # maximum G value for the comet # []BOOL prime = PRIMESIEVE max prime; # sieve of primes to max prime # [ 0 : max plot ]INT g2; # table of G values: g2[n] = G(2n) # # construct the table of G values # FOR n FROM LWB g2 TO UPB g2 DO g2[ n ] := 0 OD; g2[ 4 ] := 1; # 4 is the only sum of two even primes # FOR p FROM 3 BY 2 TO max plot OVER 2 DO IF prime[ p ] THEN g2[ p + p ] +:= 1; FOR q FROM p + 2 BY 2 TO max plot - p DO IF prime[ q ] THEN g2[ p + q ] +:= 1 FI OD FI OD; # show the first hundred G values # INT c := 0; FOR n FROM 4 BY 2 TO 202 DO print( ( whole( g2[ n ], -4 ) ) ); IF ( c +:= 1 ) = 10 THEN print( ( newline ) ); c := 0 FI OD; # show G( 1 000 000 ) # INT gm := 0; FOR p FROM 3 TO max prime OVER 2 DO IF prime[ p ] THEN IF prime[ max prime - p ] THEN gm +:= 1 FI FI OD; print( ( "G(", whole( max prime, 0 ), "): ", whole( gm, 0 ), newline ) ); # find the maximum value of G up to the maximum plot size # INT max g := 0; FOR n FROM 2 BY 2 TO max plot DO IF g2[ n ] > max g THEN max g := g2[ n ] FI OD; # draw an ASCII scatter plot of G, each position represents 5 G values # # the vertical axis is n/10, the horizontal axis is G(n) # INT plot step = 10; STRING plot value = " .-+=*%$&#@"; FOR g FROM 0 BY plot step TO max plot - plot step DO [ 0 : max g ]INT values; FOR v pos FROM LWB values TO UPB values DO values[ v pos ] := 0 OD; INT max v := 0; FOR g element FROM g BY 2 TO g + ( plot step - 1 ) DO INT g2 value = g2[ g element ]; values[ g2 value ] +:= 1; IF g2 value > max v THEN max v := g2 value FI OD; print( ( IF g MOD 100 = 90 THEN "+" ELSE "|" FI ) ); FOR v pos FROM 1 TO max v DO # exclude 0 values from the plot # print( ( plot value[ values[ v pos ] + 1 ] ) ) OD; print( ( newline ) ) OD END
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#BBC_BASIC
BBC BASIC
Width% = 200 Height% = 200   VDU 23,22,Width%;Height%;8,16,16,128 *display c:\lena   FOR y% = 0 TO Height%-1 FOR x% = 0 TO Width%-1 rgb% = FNgetpixel(x%,y%) r% = rgb% >> 16 g% = (rgb% >> 8) AND &FF b% = rgb% AND &FF l% = INT(0.3*r% + 0.59*g% + 0.11*b% + 0.5) PROCsetpixel(x%,y%,l%,l%,l%) NEXT NEXT y% END   DEF PROCsetpixel(x%,y%,r%,g%,b%) COLOUR 1,r%,g%,b% GCOL 1 LINE x%*2,y%*2,x%*2,y%*2 ENDPROC   DEF FNgetpixel(x%,y%) LOCAL col% col% = TINT(x%*2,y%*2) SWAP ?^col%,?(^col%+2) = col%
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#C
C
typedef unsigned char luminance; typedef luminance pixel1[1]; typedef struct { unsigned int width; unsigned int height; luminance *buf; } grayimage_t; typedef grayimage_t *grayimage;   grayimage alloc_grayimg(unsigned int, unsigned int); grayimage tograyscale(image); image tocolor(grayimage);
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#AutoHotkey
AutoHotkey
  ' Go Fish ~ ¡Pesca!   Const cartas = "A234567890JQK"   Declare Sub Reparto_Cartas Declare Sub Pescar_Carta_Jug Declare Sub Pescar_Carta_CPU Declare Sub Comprobar_Libro_Jug Declare Sub Comprobar_Libro_CPU Declare Sub Comprobar_Fin_Partida Declare Sub Intro   Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13) Dim Shared As String nombre, Snombre, CartaPedida Dim Shared puntos(2) As Byte = {0,0} Dim Shared As Integer remca = 4*Len(cartas) Dim Shared As Integer i, k, j, cn For i = 1 To 13 deck(i) = 4 Next i For i = 1 To 9 Reparto_Cartas deck(k) -= 1 compu(k) += 1 Reparto_Cartas deck(k) -= 1 play(k) += 1 Next i Dim As Integer v, po   Sub Reparto_Cartas remca -= 1 Dim As Integer sc = remca * Rnd + 1 For k = 1 To 13 sc -= deck(k) If sc <= 0 Then Return Next k End Sub   Sub Pescar_Carta_Jug Reparto_Cartas Print " " &Mid(cartas,k,1) &"." deck(k) -= 1 play(k) += 1 End Sub   Sub Pescar_Carta_CPU Reparto_Cartas Print "a carta." deck(k) -= 1 compu(k) += 1 End Sub   Sub Comprobar_Libro_Jug For i = 1 To 13 If play(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 play(i) = 0 puntos(0) += 1 End If Next i End Sub   Sub Comprobar_Libro_CPU For i = 1 To 13 If compu(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 compu(i) = 0 puntos(1) += 1 End If Next i End Sub   Sub Comprobar_Fin_Partida Dim As Integer np = 0, nc = 0 For i = 1 To 13 np += play(i) nc += compu(i) Next i If remca = 0 Or np = 0 Or nc = 0 Then Color 15: Print Print "*** ­FIN de la partida! ***" Print If puntos(0) < puntos(1) Then Print "La CPU ha ganado." Elseif puntos(0) > puntos(1) Then Print nombre &" ha ganado." Else Print "­Es un empate!" End If Sleep: End End If End Sub   Sub Intro Color 15 Print " __ _ _ " Print " __ _ ___ / _(_)___| |__ " Print " / ` |/ _ \ | |_| / __| '_ \ " Print "| (_) | (_) | | _| \__ \ | | | " Print " \__, |\___/ |_| |_|___/_| |_| " Print " |___/ " Print " " Color 14: Locate 10, 2: Input "Como te llamas: ", nombre End Sub   '--- Programa Principal --- Cls Randomize Timer Intro Do Dim As boolean MuestraMano = false While MuestraMano = false Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1) Color 13: Print Chr(10) &space(10) &remca &" cartas restantes" Color 14: Print Chr(10) &"Tu mano: "; For i = 1 To 13 If Not play(i) Then For j = 1 To play(i) Print Mid(cartas,i,1); " "; Next j End If Next i Print   Dim As boolean PideCarta = false While PideCarta = false Comprobar_Fin_Partida Snombre = nombre Color 7: Print Input "¨Que carta pides... "; CartaPedida Print If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true If cn = 0 Then Print "Lo siento, no es una opción valida.": PideCarta = false Elseif play(cn) = 0 Then Color 12: Print "­No tienes esa carta!": Color 7: PideCarta = false End If Wend   guess(cn) = 1 If compu(cn) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug Comprobar_Libro_Jug MuestraMano = true Else v = compu(cn) compu(cn) = 0 play(cn) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_Jug MuestraMano = false End If Wend   Snombre = "CPU" For i = 1 To 13 asked(i) = 0 Next i Dim As boolean Turno_CPU_2 = false While Turno_CPU_2 = false Comprobar_Fin_Partida po = 0 For i = 1 To 13 If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1 Next i If po = 0 Then Do k = (Rnd*12)+1 Loop While compu(k) = 0 Or asked(k) Else Do k = (Rnd*12)+1 Loop While poss(k) = 0 guess(k) = 0 asked(k) = 1 End If   Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s." asked(k) = 1 If play(k) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU Comprobar_Libro_CPU Turno_CPU_2 = true Else v = play(k) play(k) = 0 compu(k) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_CPU Turno_CPU_2 = false End If Wend Loop End  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#BBC_BASIC
BBC BASIC
@% = &1010 FOR h% = 1 TO 20 PRINT "H("; h% ") = "; FNhamming(h%) NEXT PRINT "H(1691) = "; FNhamming(1691) END   DEF FNhamming(l%) LOCAL i%, j%, k%, n%, m, x2, x3, x5, h%() DIM h%(l%) : h%(0) = 1 x2 = 2 : x3 = 3 : x5 = 5 FOR n% = 1 TO l%-1 m = x2 IF m > x3 m = x3 IF m > x5 m = x5 h%(n%) = m IF m = x2 i% += 1 : x2 = 2 * h%(i%) IF m = x3 j% += 1 : x3 = 3 * h%(j%) IF m = x5 k% += 1 : x5 = 5 * h%(k%) NEXT = h%(l%-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,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#C.23
C#
using System;   class GuessTheNumberGame { static void Main() { int randomNumber = new Random().Next(1, 11);   Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?"); while(true) { Console.Write("Guess: "); if (int.Parse(Console.ReadLine()) == randomNumber) break; Console.WriteLine("That's not it. Guess again."); } Console.WriteLine("Congrats!! You guessed right!"); } };
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#C.2B.2B
C++
#include <iostream> #include <cstdlib> #include <ctime>   int main() { srand(time(0)); int n = 1 + (rand() % 10); int g; std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! "; while(true) { std::cin >> g; if (g == n) break; else std::cout << "That's not my number.\nTry another guess! "; } std::cout << "You've guessed my number!"; return 0; }    
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#C.23
C#
using System;   namespace Tests_With_Framework_4 { class Program { static void Main(string[] args) { int[] integers = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; int length = integers.Length; int maxsum, beginmax, endmax, sum; maxsum = beginmax = sum = 0; endmax = -1;   for (int i = 0; i < length; i++) { sum = 0; for (int k = i; k < length; k++) { sum += integers[k]; if (sum > maxsum) { maxsum = sum; beginmax = i; endmax = k; } } }   for (int i = beginmax; i <= endmax; i++) Console.WriteLine(integers[i]);   Console.ReadKey(); } } }
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#Ruby
Ruby
Shoes.app do @number = edit_line @number.change {update_controls}   @incr = button('Increment') {update_controls(@number.text.to_i + 1)} @decr = button('Decrement') {update_controls(@number.text.to_i - 1)}   def update_controls(value = @number.text.to_i) @number.text = value @incr.state = value.to_i >= 10 ? "disabled" : nil @decr.state = value.to_i <= 0 ? "disabled" : nil end   update_controls 0 end
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#C
C
#include <stdlib.h> #include <stdio.h> #include <time.h>   #define lower_limit 0 #define upper_limit 100   int main(){ int number, guess;   srand( time( 0 ) ); number = lower_limit + rand() % (upper_limit - lower_limit + 1);   printf( "Guess the number between %d and %d: ", lower_limit, upper_limit );   while( scanf( "%d", &guess ) == 1 ){ if( number == guess ){ printf( "You guessed correctly!\n" ); break; } printf( "Your guess was too %s.\nTry again: ", number < guess ? "high" : "low" ); }   return 0; }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Julia
Julia
using Gtk, Cairo, ColorTypes   function generategrays(n, screenwidth) verts = Vector{RGB}() hwidth = Int(ceil(screenwidth/n)) for x in 00:Int(floor(0xff/(n-1))):0xff rgbgray = RGB(x/255, x/255, x/255) for i in 1:hwidth push!(verts, rgbgray) end end verts end   function drawline(ctx, p1, p2, color, width) move_to(ctx, p1.x, p1.y) set_source(ctx, color) line_to(ctx, p2.x, p2.y) set_line_width(ctx, width) stroke(ctx) end   const can = @GtkCanvas() const win = GtkWindow(can, "Grayscale bars/Display", 400, 400) fullscreen(win) # start full screen, then reduce to regular window in 5 seconds.   draw(can) do widget ctx = getgc(can) h = height(can) w = width(can) gpoints = generategrays(8, w) for (i, x) in enumerate(0:w-1) drawline(ctx, Point(x, 0.25*h), Point(x, 0), gpoints[i], 1) end gpoints = reverse(generategrays(16, w)) for (i, x) in enumerate(0:w-1) drawline(ctx, Point(x, 0.5*h), Point(x, 0.25*h), gpoints[i], 1) end gpoints = generategrays(32, w) for (i, x) in enumerate(0:w-1) drawline(ctx, Point(x, 0.75*h), Point(x, 0.5*h), gpoints[i], 1) end gpoints = reverse(generategrays(64, w)) for (i, x) in enumerate(0:w-1) drawline(ctx, Point(x, h), Point(x, 0.75*h), gpoints[i], 1) end end   show(can) sleep(5) unfullscreen(win) const cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) wait(cond)
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Kotlin
Kotlin
// version 1.1   import java.awt.Color import java.awt.Graphics import javax.swing.JFrame   class GreyBars : JFrame("grey bars example!") { private val w: Int private val h: Int   init { w = 640 h = 320 setSize(w, h) defaultCloseOperation = JFrame.EXIT_ON_CLOSE isVisible = true }   override fun paint(g: Graphics) { var run = 0 var colorComp: Double // component of the color var columnCount = 8 while (columnCount < 128) { var colorGap = 255.0 / (columnCount - 1) // by this gap we change the background color val columnWidth = w / columnCount val columnHeight = h / 4 if (run % 2 == 0) // switches color directions with each iteration of while loop colorComp = 0.0 else { colorComp = 255.0 colorGap *= -1.0 } val ystart = columnHeight * run var xstart = 0 for (i in 0 until columnCount) { val iColor = Math.round(colorComp).toInt() val nextColor = Color(iColor, iColor, iColor) g.color = nextColor g.fillRect(xstart, ystart, columnWidth, columnHeight) xstart += columnWidth colorComp += colorGap } run++ columnCount *= 2 } } }   fun main(args: Array<String>) { GreyBars() }
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#JavaScript
JavaScript
#!/usr/bin/env js   var DONE = RIGHT = 0, HIGH = 1, LOW = -1;   function main() { showInstructions(); while (guess(1, 100) !== DONE); }   function guess(low, high) { if (low > high) { print("I can't guess it. Perhaps you changed your number."); return DONE; }   var g = Math.floor((low + high) / 2); var result = getResult(g); switch (result) { case RIGHT: return DONE; case LOW: return guess(g + 1, high); case HIGH: return guess(low, g - 1); } }   function getResult(g) { while(true) { putstr('Is it ' + g + '? '); var ans = readline().toUpperCase().replace(/^\s+/, '') + ' '; switch (ans[0]) { case 'R': print('I got it! Thanks for the game.'); return RIGHT; case 'L': return LOW; case 'H': return HIGH; default: print('Please tell me if I am "high", "low" or "right".'); } } }   function showInstructions() { print('Think of a number between 1 and 100 and I will try to guess it.'); print('After I guess, type "low", "high" or "right", and then press enter.'); putstr("When you've thought of a number press enter."); readline(); }   main();  
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Dart
Dart
main() { HashMap<int,bool> happy=new HashMap<int,bool>(); happy[1]=true;   int count=0; int i=0;   while(count<8) { if(happy[i]==null) { int j=i; Set<int> sequence=new Set<int>(); while(happy[j]==null && !sequence.contains(j)) { sequence.add(j); int sum=0; int val=j; while(val>0) { int digit=val%10; sum+=digit*digit; val=(val/10).toInt(); } j=sum; } bool sequenceHappy=happy[j]; Iterator<int> it=sequence.iterator(); while(it.hasNext()) { happy[it.next()]=sequenceHappy; } } if(happy[i]) { print(i); count++; } i++; } }
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#LiveCode
LiveCode
function radians n return n * (3.1415926 / 180) end radians   function haversine lat1, lng1, lat2, lng2 local radiusEarth local lat3, lng3 local lat1Rad, lat2Rad, lat3Rad local lngRad1, lngRad2, lngRad3 local haver put 6372.8 into radiusEarth put (lat2 - lat1) into lat3 put (lng2 - lng1) into lng3 put radians(lat1) into lat1Rad put radians(lat2) into lat2Rad put radians(lat3) into lat3Rad put radians(lng1) into lngRad1 put radians(lng2) into lngRad2 put radians(lng3) into lngRad3   put (sin(lat3Rad/2.0)^2) + (cos(lat1Rad)) \ * (cos(lat2Rad)) \ * (sin(lngRad3/2.0)^2) \ into haver  return (radiusEarth * (2.0 * asin(sqrt(haver))))   end haversine
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Lua
Lua
local function haversine(x1, y1, x2, y2) r=0.017453292519943295769236907684886127; x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1; a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c; return d; end
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
#FUZE_BASIC
FUZE BASIC
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
#UnixPipes
UnixPipes
cat <<VAL >p.values apple boy cow dog elephant VAL   cat <<KEYS >p.keys a b c d e KEYS   paste -d\ <(cat p.values | sort) <(cat p.keys | sort)
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
#Ursala
Ursala
keys = <'foo','bar','baz'> values = <12354,145430,76748>   hash_function = keys-$values
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#NetRexx
NetRexx
/* NetRexx ------------------------------------------------------------ * 21.01.2014 Walter Pachl translated from ooRexx (from REXX version 1) *--------------------------------------------------------------------*/   options replace format comments java crossref symbols nobinary   Parse Arg x y . /* get optional arguments: X Y */ If x='' Then x=20 /* Not specified? Use default */ If y='' Then y=1000 /* " " " " */ n=0 /* Niven count */ nl='' /* Niven list. */   Loop j=1 By 1 Until n=x /* let's go Niven number hunting.*/ If j//sumdigs(j)=0 Then Do /* j is a Niven number */ n=n+1 /* bump Niven count */ nl=nl j /* add to list. */ End End   Say 'first' n 'Niven numbers:'nl   Loop j=y+1 By 1 /* start with first candidate */ If j//sumdigs(j)=0 Then /* j is a Niven number */ Leave End   Say 'first Niven number >' y 'is:' j Exit   method sumdigs(n) public static returns Rexx sum=n.left(1) Loop k=2 To n.length() sum=sum+n.substr(k,1) End Return sum
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
#HicEst
HicEst
WRITE(Messagebox='!') '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
#HolyC
HolyC
PopUpOk("Goodbye, World!");
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#Oz
Oz
declare [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}   proc {Main} MaxValue = 1000 NumberWidget GUI = lr( numberentry(init:1 min:0 max:MaxValue handle:NumberWidget) button(text:"Increase" action:proc {$} OldVal = {NumberWidget get($)} in {NumberWidget set(OldVal+1)} end) button(text:"Random" action:proc {$} if {Ask "Reset to random?"} then Rnd = {OS.rand} * MaxValue div {OS.randLimits _} in {NumberWidget set(Rnd)} end end) ) Window = {QTk.build GUI} in {Window show} end   fun {Ask Msg} Result Box = {QTk.build td(message(init:Msg) lr(button(text:"Yes" action:proc {$} Result=true {Box close} end) button(text:"No" action:proc {$} Result=false {Box close} end) ))} in {Box show} {Box wait} Result end in {Main}
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#8th
8th
  [ 1.0, 2.3, 1.1, 5.0, 3, 2.8, 2.01, 3.14159 ] ' n:max 0 a:reduce . cr  
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected. Only unconnected nodes need a separate description. For example, 0-1 1-2 2-0 3 Describes the following graph. Note that node 3 has no neighbours Example graph +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ A useful internal datastructure for a graph and for later graph algorithms is as a mapping between each node and the set/list of its neighbours. In the above example: 0 maps-to 1 and 2 1 maps to 2 and 0 2 maps-to 1 and 0 3 maps-to <nothing> Graph colouring task Colour the vertices of a given graph so that no edge is between verticies of the same colour. Integers may be used to denote different colours. Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement). Show for each edge, the colours assigned on each vertex. Show the total number of nodes, edges, and colours used for each graph. Use the following graphs Ex1 0-1 1-2 2-0 3 +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ Ex2 The wp articles left-side graph 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7 +----------------------------------+ | | | +---+ | | +-----------------| 3 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 6 | --- | 4 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 7 | --- | 2 | --- | 5 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex3 The wp articles right-side graph which is the same graph as Ex2, but with different node orderings and namings. 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6 +----------------------------------+ | | | +---+ | | +-----------------| 5 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 4 | --- | 7 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 6 | --- | 3 | --- | 2 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex4 This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x. This might alter the node order used in the greedy algorithm leading to differing numbers of colours. 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7 +-------------------------------------------------+ | | | | +-------------------+---------+ | | | | | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | | | | | | +---------+-----------------------------+---------+ | | | | | | | | | | +-----------------------------+-------------------+ | | | | | +-----------------------------+ References Greedy coloring Wikipedia. Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
#Go
Go
package main   import ( "fmt" "sort" )   type graph struct { nn int // number of nodes st int // node numbering starts from nbr [][]int // neighbor list for each node }   type nodeval struct { n int // number of node v int // valence of node i.e. number of neighbors }   func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false }   func newGraph(nn, st int) graph { nbr := make([][]int, nn) return graph{nn, st, nbr} }   // Note that this creates a single 'virtual' edge for an isolated node. func (g graph) addEdge(n1, n2 int) { n1, n2 = n1-g.st, n2-g.st // adjust to starting node number g.nbr[n1] = append(g.nbr[n1], n2) if n1 != n2 { g.nbr[n2] = append(g.nbr[n2], n1) } }   // Uses 'greedy' algorithm. func (g graph) greedyColoring() []int { // create a slice with a color for each node, starting with color 0 cols := make([]int, g.nn) // all zero by default including the first node for i := 1; i < g.nn; i++ { cols[i] = -1 // mark all nodes after the first as having no color assigned (-1) } // create a bool slice to keep track of which colors are available available := make([]bool, g.nn) // all false by default // assign colors to all nodes after the first for i := 1; i < g.nn; i++ { // iterate through neighbors and mark their colors as available for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = true } } // find the first available color c := 0 for ; c < g.nn; c++ { if !available[c] { break } } cols[i] = c // assign it to the current node // reset the neighbors' colors to unavailable // before the next iteration for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = false } } } return cols }   // Uses Welsh-Powell algorithm. func (g graph) wpColoring() []int { // create nodeval for each node nvs := make([]nodeval, g.nn) for i := 0; i < g.nn; i++ { v := len(g.nbr[i]) if v == 1 && g.nbr[i][0] == i { // isolated node v = 0 } nvs[i] = nodeval{i, v} } // sort the nodevals in descending order by valence sort.Slice(nvs, func(i, j int) bool { return nvs[i].v > nvs[j].v }) // create colors slice with entries for each node cols := make([]int, g.nn) for i := range cols { cols[i] = -1 // set all nodes to no color (-1) initially } currCol := 0 // start with color 0 for f := 0; f < g.nn-1; f++ { h := nvs[f].n if cols[h] != -1 { // already assigned a color continue } cols[h] = currCol // assign same color to all subsequent uncolored nodes which are // not connected to a previous colored one outer: for i := f + 1; i < g.nn; i++ { j := nvs[i].n if cols[j] != -1 { // already colored continue } for k := f; k < i; k++ { l := nvs[k].n if cols[l] == -1 { // not yet colored continue } if contains(g.nbr[j], l) { continue outer // node j is connected to an earlier colored node } } cols[j] = currCol } currCol++ } return cols }   func main() { fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring} titles := []string{"'Greedy'", "Welsh-Powell"} nns := []int{4, 8, 8, 8} starts := []int{0, 1, 1, 1} edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}} edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8}, {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8}, {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}} edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8}, {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} for j, fn := range fns { fmt.Println("Using the", titles[j], "algorithm:\n") for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} { fmt.Println(" Example", i+1) g := newGraph(nns[i], starts[i]) for _, e := range edges { g.addEdge(e[0], e[1]) } cols := fn(g) ecount := 0 // counts edges for _, e := range edges { if e[0] != e[1] { fmt.Printf(" Edge  %d-%d -> Color %d, %d\n", e[0], e[1], cols[e[0]-g.st], cols[e[1]-g.st]) ecount++ } else { fmt.Printf(" Node  %d -> Color %d\n", e[0], cols[e[0]-g.st]) } } maxCol := 0 // maximum color number used for _, col := range cols { if col > maxCol { maxCol = col } } fmt.Println(" Number of nodes  :", nns[i]) fmt.Println(" Number of edges  :", ecount) fmt.Println(" Number of colors :", maxCol+1) fmt.Println() } } }
http://rosettacode.org/wiki/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function. The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes. Examples G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2) G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19) Task Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4) Find and display the value of G(1000000) Stretch Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet See also Wikipedia: Goldbach's conjecture OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
#Arturo
Arturo
G: function [n][ size select 2..n/2 'x -> and? [prime? x][prime? n-x] ]   print "The first 100 G values:" loop split.every: 10 map select 4..202 => even? => G 'row [ print map to [:string] row 'item -> pad item 3 ]   print ["\nG(1000000) =" G 1000000]   csv: join.with:",\n" map select 4..2000 => even? 'x -> ~"|x|, |G x|"   ; write the CSV data to a file which we can then visualize ; via our preferred spreadsheet app write "comet.csv" csv
http://rosettacode.org/wiki/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function. The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes. Examples G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2) G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19) Task Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4) Find and display the value of G(1000000) Stretch Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet See also Wikipedia: Goldbach's conjecture OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
#AWK
AWK
  # syntax: GAWK -f GOLDBACHS_COMET.AWK BEGIN { print("The first 100 G numbers:") for (n=4; n<=202; n+=2) { printf("%4d%1s",g(n),++count%10?"":"\n") } n = 1000000 printf("\nG(%d): %d\n",n,g(n)) n = 4 printf("G(%d): %d\n",n,g(n)) n = 22 printf("G(%d): %d\n",n,g(n)) exit(0) } function g(n, count,i) { if (n % 2 == 0) { # n must be even for (i=2; i<=(1/2)*n; i++) { if (is_prime(i) && is_prime(n-i)) { count++ } } } return(count) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (n % 2 == 0) { return(n == 2) } if (n % 3 == 0) { return(n == 3) } while (d*d <= n) { if (n % d == 0) { return(0) } d += 2 if (n % d == 0) { return(0) } d += 4 } return(1) }  
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#C.23
C#
  Bitmap tImage = new Bitmap("spectrum.bmp");   for (int x = 0; x < tImage.Width; x++) { for (int y = 0; y < tImage.Height; y++) { Color tCol = tImage.GetPixel(x, y);   // L = 0.2126·R + 0.7152·G + 0.0722·B double L = 0.2126 * tCol.R + 0.7152 * tCol.G + 0.0722 * tCol.B; tImage.SetPixel(x, y, Color.FromArgb(Convert.ToInt32(L), Convert.ToInt32(L), Convert.ToInt32(L))); } }   // Save tImage.Save("spectrum2.bmp");  
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Clojure
Clojure
  (import '[java.io File] '[javax.imageio ImageIO] '[java.awt Color] '[java.awt.image BufferedImage]))   (defn rgb-to-gray [color-image] (let [width (.getWidth color-image)] (partition width (for [x (range width) y (range (.getHeight color-image))] (let [rgb (.getRGB color-image x y) rgb-object (new Color rgb) r (.getRed rgb-object) g (.getGreen rgb-object) b (.getBlue rgb-object) a (.getAlpha rgb-object)] ;Compute the grayscale value an return it: L = 0.2126·R + 0.7152·G + 0.0722·B (+ (* r 0.2126) (* g 0.7152) (* b 0.0722)))))))     (defn write-matrix-to-image [matrix filename] (ImageIO/write (let [height (count matrix) width (count (first matrix)) output-image (new BufferedImage width height BufferedImage/TYPE_BYTE_GRAY)] (doseq [row-index (range height) column-index (range width)] (.setRGB output-image column-index row-index (.intValue (nth (nth matrix row-index) column-index)))) output-image) "png" (new File filename)))   (println (write-matrix-to-image (rgb-to-gray (ImageIO/read (new File "test.jpg"))) "test-gray-cloj.png"))    
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#C
C
  ' Go Fish ~ ¡Pesca!   Const cartas = "A234567890JQK"   Declare Sub Reparto_Cartas Declare Sub Pescar_Carta_Jug Declare Sub Pescar_Carta_CPU Declare Sub Comprobar_Libro_Jug Declare Sub Comprobar_Libro_CPU Declare Sub Comprobar_Fin_Partida Declare Sub Intro   Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13) Dim Shared As String nombre, Snombre, CartaPedida Dim Shared puntos(2) As Byte = {0,0} Dim Shared As Integer remca = 4*Len(cartas) Dim Shared As Integer i, k, j, cn For i = 1 To 13 deck(i) = 4 Next i For i = 1 To 9 Reparto_Cartas deck(k) -= 1 compu(k) += 1 Reparto_Cartas deck(k) -= 1 play(k) += 1 Next i Dim As Integer v, po   Sub Reparto_Cartas remca -= 1 Dim As Integer sc = remca * Rnd + 1 For k = 1 To 13 sc -= deck(k) If sc <= 0 Then Return Next k End Sub   Sub Pescar_Carta_Jug Reparto_Cartas Print " " &Mid(cartas,k,1) &"." deck(k) -= 1 play(k) += 1 End Sub   Sub Pescar_Carta_CPU Reparto_Cartas Print "a carta." deck(k) -= 1 compu(k) += 1 End Sub   Sub Comprobar_Libro_Jug For i = 1 To 13 If play(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 play(i) = 0 puntos(0) += 1 End If Next i End Sub   Sub Comprobar_Libro_CPU For i = 1 To 13 If compu(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 compu(i) = 0 puntos(1) += 1 End If Next i End Sub   Sub Comprobar_Fin_Partida Dim As Integer np = 0, nc = 0 For i = 1 To 13 np += play(i) nc += compu(i) Next i If remca = 0 Or np = 0 Or nc = 0 Then Color 15: Print Print "*** ­FIN de la partida! ***" Print If puntos(0) < puntos(1) Then Print "La CPU ha ganado." Elseif puntos(0) > puntos(1) Then Print nombre &" ha ganado." Else Print "­Es un empate!" End If Sleep: End End If End Sub   Sub Intro Color 15 Print " __ _ _ " Print " __ _ ___ / _(_)___| |__ " Print " / ` |/ _ \ | |_| / __| '_ \ " Print "| (_) | (_) | | _| \__ \ | | | " Print " \__, |\___/ |_| |_|___/_| |_| " Print " |___/ " Print " " Color 14: Locate 10, 2: Input "Como te llamas: ", nombre End Sub   '--- Programa Principal --- Cls Randomize Timer Intro Do Dim As boolean MuestraMano = false While MuestraMano = false Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1) Color 13: Print Chr(10) &space(10) &remca &" cartas restantes" Color 14: Print Chr(10) &"Tu mano: "; For i = 1 To 13 If Not play(i) Then For j = 1 To play(i) Print Mid(cartas,i,1); " "; Next j End If Next i Print   Dim As boolean PideCarta = false While PideCarta = false Comprobar_Fin_Partida Snombre = nombre Color 7: Print Input "¨Que carta pides... "; CartaPedida Print If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true If cn = 0 Then Print "Lo siento, no es una opción valida.": PideCarta = false Elseif play(cn) = 0 Then Color 12: Print "­No tienes esa carta!": Color 7: PideCarta = false End If Wend   guess(cn) = 1 If compu(cn) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug Comprobar_Libro_Jug MuestraMano = true Else v = compu(cn) compu(cn) = 0 play(cn) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_Jug MuestraMano = false End If Wend   Snombre = "CPU" For i = 1 To 13 asked(i) = 0 Next i Dim As boolean Turno_CPU_2 = false While Turno_CPU_2 = false Comprobar_Fin_Partida po = 0 For i = 1 To 13 If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1 Next i If po = 0 Then Do k = (Rnd*12)+1 Loop While compu(k) = 0 Or asked(k) Else Do k = (Rnd*12)+1 Loop While poss(k) = 0 guess(k) = 0 asked(k) = 1 End If   Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s." asked(k) = 1 If play(k) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU Comprobar_Libro_CPU Turno_CPU_2 = true Else v = play(k) play(k) = 0 compu(k) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_CPU Turno_CPU_2 = false End If Wend Loop End  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Bc
Bc
cat hamming_numbers.bc define min(x,y) { if (x < y) { return x } else { return y } } define hamming(limit) { i = 0 j = 0 k = 0 h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (n=1; n<=limit; n++) { h[n] = min(x2,min(x3,x5)) if (h[n] == x2) { x2 = 2 * h[++i] } if (h[n] == x3) { x3 = 3 * h[++j] } if (h[n] == x5) { x5 = 5 * h[++k] } } return (h[limit-1]) } for (lab=1; lab<=20; lab++) { hamming(lab) } hamming(1691) hamming(1000000) quit  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Clojure
Clojure
  (def target (inc (rand-int 10))   (loop [n 0] (println "Guess a number between 1 and 10 until you get it right:") (let [guess (read)] (if (= guess target) (printf "Correct on the %d guess.\n" n) (do (println "Try again") (recur (inc n))))))  
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Guess-The-Number.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Random-Num PIC 99. 01 Guess PIC 99.   PROCEDURE DIVISION. COMPUTE Random-Num = 1 + (FUNCTION RANDOM * 10) DISPLAY "Guess a number between 1 and 10:"   PERFORM FOREVER ACCEPT Guess   IF Guess = Random-Num DISPLAY "Well guessed!" EXIT PERFORM ELSE DISPLAY "That isn't it. Try again." END-IF END-PERFORM   GOBACK .
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#C.2B.2B
C++
#include <utility> // for std::pair #include <iterator> // for std::iterator_traits #include <iostream> // for std::cout #include <ostream> // for output operator and std::endl #include <algorithm> // for std::copy #include <iterator> // for std::output_iterator   // Function template max_subseq // // Given a sequence of integers, find a 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. // // Requirements: // * ForwardIterator is a forward iterator // * ForwardIterator's value_type is less-than comparable and addable // * default-construction of value_type gives the neutral element // (zero) // * operator+ and operator< are compatible (i.e. if a>zero and // b>zero, then a+b>zero, and if a<zero and b<zero, then a+b<zero) // * [begin,end) is a valid range // // Returns: // a pair of iterators describing the begin and end of the // subsequence template<typename ForwardIterator> std::pair<ForwardIterator, ForwardIterator> max_subseq(ForwardIterator begin, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type value_type;   ForwardIterator seq_begin = begin, seq_end = seq_begin; value_type seq_sum = value_type(); ForwardIterator current_begin = begin; value_type current_sum = value_type();   value_type zero = value_type();   for (ForwardIterator iter = begin; iter != end; ++iter) { value_type value = *iter; if (zero < value) { if (current_sum < zero) { current_sum = zero; current_begin = iter; } } else { if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = iter; seq_sum = current_sum; } } current_sum += value; }   if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = end; seq_sum = current_sum; }   return std::make_pair(seq_begin, seq_end); }   // the test array int array[] = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 };   // function template to find the one-past-end pointer to the array template<typename T, int N> int* end(T (&arr)[N]) { return arr+N; }   int main() { // find the subsequence std::pair<int*, int*> seq = max_subseq(array, end(array));   // output it std::copy(seq.first, seq.second, std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl;   return 0; }
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#Scala
Scala
import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField } import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }   object Enabling extends swing.SimpleSwingApplication { def top = new swing.MainFrame { title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala"   val numberField = new TextField { text = "0" // start at 0 horizontalAlignment = swing.Alignment.Right }   val (incButton, decButton) = (new Button("Increment"), // Two variables initialized new Button("Decrement") { enabled = false })   // arrange buttons in a grid with 1 row, 2 columns val buttonPanel = new GridPanel(1, 2) { contents ++= List(incButton, decButton) }   // arrange text field and button panel in a grid with 2 row, 1 column contents = new BoxPanel(Orientation.Vertical) { contents ++= List(numberField, buttonPanel) }   val specialKeys = List(Key.BackSpace, Key.Delete)   // listen for keys pressed in numberField and button clicks listenTo(numberField.keys, incButton, decButton) reactions += { case kt: KeyTyped => if (kt.char.isDigit) // if the entered char is a digit ... Swing.onEDT(switching) // ensure GUI-updating else kt.consume // ... eat the event (i.e. stop it from being processed) case KeyPressed(_, kp, _, _) if (!specialKeys.contains(kp)) => Swing.onEDT(switching) // ensure GUI-updating case ButtonClicked(`incButton`) => numberField.text = (numberField.text.toLong + 1).toString switching case ButtonClicked(`decButton`) => numberField.text = (numberField.text.toLong - 1).toString switching }   def switching = { val n = (if (numberField.text.isEmpty()) "0" else numberField.text).toLong numberField.text = n.toString numberField.enabled = n == 0 incButton.enabled = n < 10 decButton.enabled = n > 0 } centerOnScreen() } // def top( }
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#C.23
C#
using System;   class Program { static void Main(string[] args) { const int from = 1; const int to = 10;   int randomNumber = new Random().Next(from, to); int guessedNumber;   Console.Write("The number is between {0} and {1}. ", from, to); while (true) { Console.Write("Make a guess: "); if (int.TryParse(Console.ReadLine(), out guessedNumber)) { if (guessedNumber == randomNumber) { Console.WriteLine("You guessed the right number!"); break; } else { Console.WriteLine("Your guess was too {0}.", (guessedNumber > randomNumber) ? "high" : "low"); } } else { Console.WriteLine("Input was not an integer."); } }   Console.WriteLine(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }  
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Liberty_BASIC
Liberty BASIC
  nomainwin   WindowWidth =DisplayWidth WindowHeight =DisplayHeight   open "Grey bars" for graphics_fs_nsb as #w   #w "trapclose [quit]" #w "down"   bars =4 ' alter for more, finer bars.   for group =0 to bars -1 for i = 0 to 2^( 3 +group) -1 #w "place "; WindowWidth *i /( 2^( 3 +group)); " "; WindowHeight *group /bars if ( group =0) or ( group =2) then g$ =str$( int( 255 *i /(2^( 3 +group)-1))) else g$ =str$( 255 -int( 255 *i /(2^( 3 +group)-1))) end if grey$ =g$ +" " +g$ +" " +g$ #w "backcolor "; grey$ '#w "color "; grey$ 'rem out for outlined areas.. #w "boxfilled "; WindowWidth *( i +1) /8 ; " "; WindowHeight *( group +1) /bars next i next group   wait [quit] close #w end    
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Julia
Julia
print("Enter an upper bound: ") lower = 0 input = readline() upper = parse(Int, input)   if upper < 1 throw(DomainError) end   attempts = 1 print("Think of a number, ", lower, "--", upper, ", then press ENTER.") readline() const maxattempts = round(Int, ceil(-log(1 / (upper - lower)) / log(2))) println("I will need at most ", maxattempts, " attempts ", "(⌈-log(1 / (", upper, " - ", lower, ")) / log(2)⌉ = ", maxattempts, ").\n") previous = -1 guess = -1   while true previous = guess guess = lower + round(Int, (upper - lower) / 2, RoundNearestTiesUp)   if guess == previous || attempts > maxattempts println("\nThis is impossible; did you forget your number?") exit() end   print("I guess ", guess, ".\n[l]ower, [h]igher, or [c]orrect? ") input = chomp(readline())   while input ∉ ["c", "l", "h"] print("Please enter one of \"c\", \"l\", or \"h\". ") input = chomp(readline()) end   if input == "l" upper = guess elseif input == "h" lower = guess else break end   attempts += 1 end   println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { var hle: Char var lowest = 1 var highest = 20 var guess = 10 println("Please choose a number between 1 and 20 but don't tell me what it is yet\n")   while (true) { println("My guess is $guess")   do { print("Is this higher/lower than or equal to your chosen number h/l/e : ") hle = readLine()!!.first().toLowerCase() if (hle == 'l' && guess == highest) { println("It can't be more than $highest, try again") hle = 'i' // signifies invalid } else if (hle == 'h' && guess == lowest) { println("It can't be less than $lowest, try again") hle = 'i' } } while (hle !in "hle")   when (hle) { 'e' -> { println("Good, thanks for playing the game with me!") ; return } 'h' -> if (highest > guess - 1) highest = guess - 1 'l' -> if (lowest < guess + 1) lowest = guess + 1 }   guess = (lowest + highest) / 2 } }
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#dc
dc
[lcI~rscd*+lc0<H]sH [0rsclHxd4<h]sh [lIp]s_ 0sI[lI1+dsIlhx2>_z8>s]dssx
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Maple
Maple
distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) );
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles". Task Implement a great-circle distance function, or use a library function, to show the great-circle distance between: Nashville International Airport (BNA)   in Nashville, TN, USA,   which is: N 36°7.2', W 86°40.2' (36.12, -86.67) -and- Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is: N 33°56.4', W 118°24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km, practical precision required is certainly no greater than about .0000001——i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  distance[{theta1_, phi1_}, {theta2_, phi2_}] := 2*6378.14 ArcSin@ Sqrt[Haversine[(theta2 - theta1) Degree] + Cos[theta1*Degree] Cos[theta2*Degree] Haversine[(phi2 - phi1) Degree]]  
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
#Gambas
Gambas
Public Sub Main()   PRINT "Hello world!"   End
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Vala
Vala
  using Gee;   void main(){ // mostly copied from C# example var hashmap = new HashMap<string, string>();   string[] arg_keys = {"foo", "bar", "val"}; string[] arg_values = {"little", "miss", "muffet"};   if (arg_keys.length == arg_values.length ){ for (int i = 0; i < arg_keys.length; i++){ hashmap[arg_keys[i]] = arg_values[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
#VBScript
VBScript
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:   list the first 20 members of the sequence,   and   list the first Harshad number greater than 1000. Show your output here. Related task   Increasing gaps between consecutive Niven numbers See also   OEIS: A005349
#Nim
Nim
proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] = var i = 0 for n in iter(): if i > sl.b: break if i >= sl.a: result.add(n) inc i   iterator harshad(): int {.closure.} = for n in 1 ..< int.high: var sum = 0 for ch in $n: sum += ord(ch) - ord('0') if n mod sum == 0: yield n   echo harshad.slice 0 ..< 20   for n in harshad(): if n > 1000: echo n break
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Icon_and_Unicon
Icon and Unicon
link graphics procedure main() WOpen("size=100,20") | stop("No window") WWrites("Goodbye, World!") WDone() 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
#HPPPL
HPPPL
MSGBOX("Goodbye, World!");
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dialogs to query the user for further information Task For a minimal "application", write a program that presents a form with three components to the user: a numeric input field ("Value") a button ("increment") a button ("random") The field is initialized to zero. The user may manually enter a new value into the field, or increment its value with the "increment" button. Entering a non-numeric value should be either impossible, or issue an error message. Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task Simple windowed application).
#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 interaction' ); my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1); $lf->Entry( -width => 10, -textvariable => \$value, -validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ }, )->pack(-fill => 'x', -expand => 1); $mw->Button( -text => 'increment', -command => sub { $value++ }, )->pack( -side => 'left' ); $mw->Button( -text => 'random', -command => sub { $mw->Dialog( -text => 'Change to a random value?', -title => 'Confirm', -buttons => [ qw(Yes No) ] )->Show eq 'Yes' and $value = int rand 1e9; } )->pack( -side => 'right' );   MainLoop;
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] Reference Converting Between Gray and Binary Codes. It includes step-by-step animations.
#11l
11l
F gray_encode(n) R n (+) n >> 1   F gray_decode(=n) V m = n >> 1 L m != 0 n (+)= m m >>= 1 R n   print(‘DEC, BIN => GRAY => DEC’) L(i) 32 V gray = gray_encode(i) V dec = gray_decode(gray) print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec))
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program rechMax64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .ascii "Max number is = @ rank = @ address (hexa) = @ \n" // message result   tTableNumbers: .quad 50 .quad 12 .quad -1000 .quad 40 .quad 255 .quad 60 .quad 254 .equ NBRANKTABLE, (. - tTableNumbers) / 8 // number table posts   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x1,qAdrtTableNumbers mov x2,0 ldr x4,[x1,x2,lsl #3] // load first number mov x3,x2 // save first indice add x2,x2,1 // increment indice 1: cmp x2,#NBRANKTABLE // indice ? maxi bge 2f // yes -> end search ldr x0,[x1,x2,lsl #3] // load other number cmp x0,x4 // > old number max csel x4,x0,x4,gt // if > x4 = x0 else x4=x4 csel x3,x2,x3,gt // if > x3 = x2 else x3=x3 add x2,x2,1 // increment indice b 1b // and loop   2: mov x0,x4 ldr x1,qAdrsZoneConv bl conversion10S // decimal conversion ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at first @ character mov x5,x0 // save address message mov x0,x3 ldr x1,qAdrsZoneConv // conversion rank maxi bl conversion10S // decimal conversion mov x0,x5 // message address ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at Second @ character mov x5,x0 // save message address ldr x0,qAdrtTableNumbers lsl x3,x3,3 add x0,x0,x3 ldr x1,qAdrsZoneConv // conversion address maxi bl conversion16 // hexa conversion mov x0,x5 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at third @ character bl affichageMess // display message final     100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrtTableNumbers: .quad tTableNumbers qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv   /******************************************************************/ /* conversion hexadecimal register */ /******************************************************************/ /* x0 contains value and x1 address zone receptrice */ conversion16: stp x0,lr,[sp,-48]! // save registres stp x1,x2,[sp,32] // save registres stp x3,x4,[sp,16] // save registres mov x2,#60 // start bit position mov x4,#0xF000000000000000 // mask mov x3,x0 // save entry value 1: // start loop and x0,x3,x4 // value register and mask lsr x0,x0,x2 // right shift cmp x0,#10 // >= 10 ? bge 2f // yes add x0,x0,#48 // no is digit b 3f 2: add x0,x0,#55 // else is a letter A-F 3: strb w0,[x1],#1 // load result and + 1 in address lsr x4,x4,#4 // shift mask 4 bits left subs x2,x2,#4 // decrement counter 4 bits <= zero  ? bge 1b // no -> loop   100: // fin standard de la fonction ldp x3,x4,[sp,16] // restaur des 2 registres ldp x1,x2,[sp,32] // restaur des 2 registres ldp x0,lr,[sp],48 // restaur des 2 registres ret /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected. Only unconnected nodes need a separate description. For example, 0-1 1-2 2-0 3 Describes the following graph. Note that node 3 has no neighbours Example graph +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ A useful internal datastructure for a graph and for later graph algorithms is as a mapping between each node and the set/list of its neighbours. In the above example: 0 maps-to 1 and 2 1 maps to 2 and 0 2 maps-to 1 and 0 3 maps-to <nothing> Graph colouring task Colour the vertices of a given graph so that no edge is between verticies of the same colour. Integers may be used to denote different colours. Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is not a requirement). Show for each edge, the colours assigned on each vertex. Show the total number of nodes, edges, and colours used for each graph. Use the following graphs Ex1 0-1 1-2 2-0 3 +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ Ex2 The wp articles left-side graph 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7 +----------------------------------+ | | | +---+ | | +-----------------| 3 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 6 | --- | 4 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 7 | --- | 2 | --- | 5 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex3 The wp articles right-side graph which is the same graph as Ex2, but with different node orderings and namings. 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6 +----------------------------------+ | | | +---+ | | +-----------------| 5 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 4 | --- | 7 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 6 | --- | 3 | --- | 2 | -+ | +---+ +---+ +---+ | | +-------------------+ Ex4 This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x. This might alter the node order used in the greedy algorithm leading to differing numbers of colours. 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7 +-------------------------------------------------+ | | | | +-------------------+---------+ | | | | | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | | | | | | +---------+-----------------------------+---------+ | | | | | | | | | | +-----------------------------+-------------------+ | | | | | +-----------------------------+ References Greedy coloring Wikipedia. Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
#Haskell
Haskell
import Data.Maybe import Data.List import Control.Monad.State import qualified Data.Map as M import Text.Printf   ------------------------------------------------------------ -- Primitive graph representation   type Node = Int type Color = Int type Graph = M.Map Node [Node]   nodes :: Graph -> [Node] nodes = M.keys   adjacentNodes :: Graph -> Node -> [Node] adjacentNodes g n = fromMaybe [] $ M.lookup n g   degree :: Graph -> Node -> Int degree g = length . adjacentNodes g   fromList :: [(Node, [Node])] -> Graph fromList = foldr add M.empty where add (a, bs) g = foldr (join [a]) (join bs a g) bs join = flip (M.insertWith (++))   readGraph :: String -> Graph readGraph = fromList . map interprete . words where interprete s = case span (/= '-') s of (a, "") -> (read a, []) (a, '-':b) -> (read a, [read b])   ------------------------------------------------------------ -- Graph coloring functions   uncolored :: Node -> State [(Node, Color)] Bool uncolored n = isNothing <$> colorOf n   colorOf :: Node -> State [(Node, Color)] (Maybe Color) colorOf n = gets (lookup n)   greedyColoring :: Graph -> [(Node, Color)] greedyColoring g = mapM_ go (nodes g) `execState` [] where go n = do c <- colorOf n when (isNothing c) $ do adjacentColors <- nub . catMaybes <$> mapM colorOf (adjacentNodes g n) let newColor = head $ filter (`notElem` adjacentColors) [1..] modify ((n, newColor) :) filterM uncolored (adjacentNodes g n) >>= mapM_ go   wpColoring :: Graph -> [(Node, Color)] wpColoring g = go [1..] nodesList `execState` [] where nodesList = sortOn (negate . degree g) (nodes g)   go _ [] = pure () go (c:cs) ns = do mark c ns filterM uncolored ns >>= go cs   mark c [] = pure () :: State [(Node, Color)] () mark c (n:ns) = do modify ((n, c) :) mark c (filter (`notElem` adjacentNodes g n) ns)
http://rosettacode.org/wiki/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function. The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes. Examples G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2) G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19) Task Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4) Find and display the value of G(1000000) Stretch Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet See also Wikipedia: Goldbach's conjecture OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
#FreeBASIC
FreeBASIC
Function isPrime(Byval ValorEval As Uinteger) As Boolean If ValorEval <= 1 Then Return False For i As Integer = 2 To Int(Sqr(ValorEval)) If ValorEval Mod i = 0 Then Return False Next i Return True End Function   Function g(n As Uinteger) As Uinteger Dim As Uinteger i, count = 0 If (n Mod 2 = 0) Then 'n in goldbach function g(n) must be even For i = 2 To (1/2) * n If isPrime(i) And isPrime(n - i) Then count += 1 Next i End If Return count End Function   Print "The first 100 G numbers are:"   Dim As Uinteger col = 1 For n As Uinteger = 4 To 202 Step 2 Print Using "####"; g(n); If (col Mod 10 = 0) Then Print col += 1 Next n   Print !"\nThe value of G(1000000) is "; g(1000000) Sleep
http://rosettacode.org/wiki/Goldbach%27s_comet
Goldbach's comet
This page uses content from Wikipedia. The original article was at Goldbach's comet. 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) Goldbach's comet is the name given to a plot of the function g(E), the so-called Goldbach function. The Goldbach function is studied in relation to Goldbach's conjecture. The function g(E) is defined for all even integers E>2 to be the number of different ways in which E can be expressed as the sum of two primes. Examples G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2) G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19) Task Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4) Find and display the value of G(1000000) Stretch Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet See also Wikipedia: Goldbach's conjecture OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes
#J
J
10 10$#/.~4,/:~ 0-.~,(<:/~ * +/~) p:1+i.p:inv 202 1 1 1 2 1 2 2 2 2 3 3 3 2 3 2 4 4 2 3 4 3 4 5 4 3 5 3 4 6 3 5 6 2 5 6 5 5 7 4 5 8 5 4 9 4 5 7 3 6 8 5 6 8 6 7 10 6 6 12 4 5 10 3 7 9 6 5 8 7 8 11 6 5 12 4 8 11 5 8 10 5 6 13 9 6 11 7 7 14 6 8 13 5 8 11 7 9 13 8 9
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color use the formula recommended by CIE: L = 0.2126 × R + 0.7152 × G + 0.0722 × B When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.
#Common_Lisp
Common Lisp
  (in-package #:rgb-pixel-buffer)   (defun rgb-to-gray-image (rgb-image) (flet ((rgb-to-gray (rgb-value) (round (+ (* 0.2126 (rgb-pixel-red rgb-value)) (* 0.7152 (rgb-pixel-green rgb-value)) (* 0.0722 (rgb-pixel-blue rgb-value)))))) (let ((gray-image (make-array (array-dimensions rgb-image) :element-type '(unsigned-byte 8)))) (dotimes (i (array-total-size rgb-image)) (setf (row-major-aref gray-image i) (rgb-to-gray (row-major-aref rgb-image i)))) gray-image)))   (export 'rgb-to-gray-image)     (defun grayscale-image-to-pgm-file (image file-name &optional (max-value 255)) (with-open-file (p file-name :direction :output :if-exists :supersede) (format p "P2 ~&~A ~A ~&~A" (array-dimension image 1) (array-dimension image 0) max-value) (dotimes (i (array-total-size image)) (print (row-major-aref image i) p))))   (export 'grayscale-image-to-pgm-file)    
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again. If the opponent has no cards of the named rank, the requester draws a card and ends their turn. A book is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand. If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck. The game ends when every book is complete. The player with the most books wins. The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random. You may want to use code from Playing Cards. Related tasks: Playing cards Card shuffles Deal cards_for_FreeCell War Card_Game Poker hand_analyser
#C.2B.2B
C++
  ' Go Fish ~ ¡Pesca!   Const cartas = "A234567890JQK"   Declare Sub Reparto_Cartas Declare Sub Pescar_Carta_Jug Declare Sub Pescar_Carta_CPU Declare Sub Comprobar_Libro_Jug Declare Sub Comprobar_Libro_CPU Declare Sub Comprobar_Fin_Partida Declare Sub Intro   Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13) Dim Shared As String nombre, Snombre, CartaPedida Dim Shared puntos(2) As Byte = {0,0} Dim Shared As Integer remca = 4*Len(cartas) Dim Shared As Integer i, k, j, cn For i = 1 To 13 deck(i) = 4 Next i For i = 1 To 9 Reparto_Cartas deck(k) -= 1 compu(k) += 1 Reparto_Cartas deck(k) -= 1 play(k) += 1 Next i Dim As Integer v, po   Sub Reparto_Cartas remca -= 1 Dim As Integer sc = remca * Rnd + 1 For k = 1 To 13 sc -= deck(k) If sc <= 0 Then Return Next k End Sub   Sub Pescar_Carta_Jug Reparto_Cartas Print " " &Mid(cartas,k,1) &"." deck(k) -= 1 play(k) += 1 End Sub   Sub Pescar_Carta_CPU Reparto_Cartas Print "a carta." deck(k) -= 1 compu(k) += 1 End Sub   Sub Comprobar_Libro_Jug For i = 1 To 13 If play(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 play(i) = 0 puntos(0) += 1 End If Next i End Sub   Sub Comprobar_Libro_CPU For i = 1 To 13 If compu(i) <> 4 Then Else Color 11: Print Snombre &" completa el libro de " &Mid(cartas,i,1) &"'s.": Color 7 compu(i) = 0 puntos(1) += 1 End If Next i End Sub   Sub Comprobar_Fin_Partida Dim As Integer np = 0, nc = 0 For i = 1 To 13 np += play(i) nc += compu(i) Next i If remca = 0 Or np = 0 Or nc = 0 Then Color 15: Print Print "*** ­FIN de la partida! ***" Print If puntos(0) < puntos(1) Then Print "La CPU ha ganado." Elseif puntos(0) > puntos(1) Then Print nombre &" ha ganado." Else Print "­Es un empate!" End If Sleep: End End If End Sub   Sub Intro Color 15 Print " __ _ _ " Print " __ _ ___ / _(_)___| |__ " Print " / ` |/ _ \ | |_| / __| '_ \ " Print "| (_) | (_) | | _| \__ \ | | | " Print " \__, |\___/ |_| |_|___/_| |_| " Print " |___/ " Print " " Color 14: Locate 10, 2: Input "Como te llamas: ", nombre End Sub   '--- Programa Principal --- Cls Randomize Timer Intro Do Dim As boolean MuestraMano = false While MuestraMano = false Color 15: Print Chr(10) &"Puntos >> " &nombre &": "; puntos(0); " CPU: "; puntos(1) Color 13: Print Chr(10) &space(10) &remca &" cartas restantes" Color 14: Print Chr(10) &"Tu mano: "; For i = 1 To 13 If Not play(i) Then For j = 1 To play(i) Print Mid(cartas,i,1); " "; Next j End If Next i Print   Dim As boolean PideCarta = false While PideCarta = false Comprobar_Fin_Partida Snombre = nombre Color 7: Print Input "¨Que carta pides... "; CartaPedida Print If CartaPedida <> "" Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true If cn = 0 Then Print "Lo siento, no es una opción valida.": PideCarta = false Elseif play(cn) = 0 Then Color 12: Print "­No tienes esa carta!": Color 7: PideCarta = false End If Wend   guess(cn) = 1 If compu(cn) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7: Print Snombre &" pesca un";: Pescar_Carta_Jug Comprobar_Libro_Jug MuestraMano = true Else v = compu(cn) compu(cn) = 0 play(cn) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_Jug MuestraMano = false End If Wend   Snombre = "CPU" For i = 1 To 13 asked(i) = 0 Next i Dim As boolean Turno_CPU_2 = false While Turno_CPU_2 = false Comprobar_Fin_Partida po = 0 For i = 1 To 13 If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1 Next i If po = 0 Then Do k = (Rnd*12)+1 Loop While compu(k) = 0 Or asked(k) Else Do k = (Rnd*12)+1 Loop While poss(k) = 0 guess(k) = 0 asked(k) = 1 End If   Print: Print Snombre &" quiere tus " &Mid(cartas,k,1) &"'s." asked(k) = 1 If play(k) = 0 Then Print Snombre &", "; Color 15: Print "­ve a pescar!" Color 7:Print Snombre &" pesca un";: Pescar_Carta_CPU Comprobar_Libro_CPU Turno_CPU_2 = true Else v = play(k) play(k) = 0 compu(k) += v Print Snombre &" consigue " &v &" carta(s) mas." Comprobar_Libro_CPU Turno_CPU_2 = false End If Wend Loop End  
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In particular: Show the   first twenty   Hamming numbers. Show the   1691st   Hamming number (the last one below   231). Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers). Related tasks Humble numbers N-smooth numbers References Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number). Wikipedia entry:   Smooth number OEIS entry:   A051037   5-smooth   or   Hamming numbers Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
#Bracmat
Bracmat
( ( hamming = x2 x3 x5 n i j k min . tbl$(h,!arg) { This creates an array. Arrays are always global in Bracmat. } & 1:?(0$h) & 2:?x2 & 3:?x3 & 5:?x5 & 0:?n:?i:?j:?k & whl ' ( !n+1:<!arg:?n & !x2:?min & (!x3:<!min:?min|) & (!x5:<!min:?min|) & !min:?(!n$h) { !n is index into array h } & (  !x2:!min & 2*!((1+!i:?i)$h):?x2 | ) & (  !x3:!min & 3*!((1+!j:?j)$h):?x3 | ) & (  !x5:!min & 5*!((1+!k:?k)$h):?x5 | ) ) & !((!arg+-1)$h) (tbl$(h,0)&) { We delete the array by setting its size to 0 } ) & 0:?I & whl'(!I+1:~>20:?I&put$(hamming$!I " ")) & out$ & out$(hamming$1691) & out$(hamming$1000000) );
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#CoffeeScript
CoffeeScript
num = Math.ceil(Math.random() * 10) guess = prompt "Guess the number. (1-10)" while parseInt(guess) isnt num guess = prompt "YOU LOSE! Guess again. (1-10)" alert "Well guessed!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits. A   conditional loop   may be used to repeat the guessing until the user is correct. Related tasks   Bulls and cows   Bulls and cows/Player   Guess the number/With Feedback   Mastermind
#Common_Lisp
Common Lisp
(defun guess-the-number (max) (format t "Try to guess a number from 1 to ~a!~%Guess? " max) (loop with num = (1+ (random max)) for guess = (read) as num-guesses from 1 until (and (numberp guess) (= guess num)) do (format t "Your guess was wrong. Try again.~%Guess? ") (force-output) finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses)))  
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence.
#Clojure
Clojure
(defn max-subseq-sum [coll] (->> (take-while seq (iterate rest coll)) ; tails (mapcat #(reductions conj [] %)) ; inits (apply max-key #(reduce + %)))) ; max 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 program that presents a form with three components to the user:   a numeric input field ("Value")   a button   ("increment")   a button   ("decrement") The field is initialized to zero. The user may manually enter a new value into the field, increment its value with the "increment" button, or decrement the value with the "decrement" button. The input field should be enabled only when its value is zero. The "increment" button only as long as the field's value is less then 10: When the value 10 is reached, the button should go into a disabled state. Analogously, the "decrement" button should be enabled only as long as the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. Manually entering values outside that range is still legal, but the buttons should reflect that and enable/disable accordingly.
#Smalltalk
Smalltalk
|top input vh incButton decButton|   vh := ValueHolder with:0.   top := StandardSystemView label:'Rosetta GUI interaction'. top extent:300@100. top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40). top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40). input model:(TypeConverter onNumberValue:vh). input enableChannel:(BlockValue with:[:v | v = 0] argument:vh).   top add:((incButton := Button label:'Inc') origin: 10 @ 50 corner: 100 @ 80). top add:((decButton := Button label:'Dec') origin: 110 @ 50 corner: 210 @ 80).   incButton action:[ vh value: (vh value + 1) ]. incButton enableChannel:(BlockValue with:[:v | v < 10] argument:vh). decButton action:[ vh value: (vh value - 1) ]. decButton enableChannel:(BlockValue with:[:v | v > 0] argument:vh).   top open
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to the target, less than the target,   or the input was inappropriate. Related task   Guess the number/With Feedback (Player)
#C.2B.2B
C++
#include <iostream> #include <cstdlib> #include <ctime>   int main() { std::srand(std::time(0)); int lower, upper, guess; std::cout << "Enter lower limit: "; std::cin >> lower; std::cout << "Enter upper limit: "; std::cin >> upper; int random_number = lower + std::rand() % ((upper + 1) - lower);   do { std::cout << "Guess what number I have: "; std::cin >> guess; if (guess > random_number) std::cout << "Your guess is too high\n"; else if (guess < random_number) std::cout << "Your guess is too low\n"; else std::cout << "You got it!\n"; } while (guess != random_number);   return 0; }
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CreateDocument[ Graphics[ Flatten@Table[ { If[EvenQ[#3], GrayLevel[ 1. - j/#1 ], GrayLevel[ j/#1 ]], Rectangle[{j #2, 7*#3}, {#2 (j + 1), (#3 + 1) 7}]}, {j, 0, #1}] & @@@ {{7, 8, 3}, {15, 4, 2}, {31, 2, 1}, {63, 1, 0} } ,ImageSize -> Full], WindowFrame -> "Frameless", WindowSize -> Full]
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#MAXScript
MAXScript
  fn drawBarRow _bmp _row _width _number _inverse= ( local dir = if _inverse then 1 else -1 if not _inverse then ( setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (black)) for i = (_width/_number) to _width by (_width/_number) do ( local loopPosition = i/(_width-(_width/_number)) as float local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition) setpixels _bmp [i,_row] colorsArr ) return _bmp ) else ( setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (white)) for i = _width to (_width/_number) by ((_width/_number)*-1) do ( local loopPosition = 1.0-(i/(_width-(_width/_number))) as float local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition) setpixels _bmp [i,_row] colorsArr ) return _bmp )   )   fn bitmap_verticalBars = ( local width = (sysinfo.desktopsize).x local height = (sysinfo.desktopsize).y local theBitmap = bitmap width height color:white   local row = 0 while row <= (height-1) do ( local barNumber = 0 case of ( (row < (height/4)): (barNumber = 1) (row >= (height/4) and row < (height/2)): (barNumber = 2) (row >= (height/2) and row < (height-(height/4))): (barNumber = 3) (row >= (height-(height/4))): (barNumber = 4) default: return theBitmap ) case barNumber of ( 1: ( theBitmap = drawBarRow theBitmap row width 8 false ) 2: ( theBitmap = drawBarRow theBitmap row width 16 true ) 3: ( theBitmap = drawBarRow theBitmap row width 32 false ) 4: ( theBitmap = drawBarRow theBitmap row width 64 true ) ) row += 1 -- ) return theBitmap )   b = bitmap_verticalBars() display b  
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm. Related tasks   Guess the number/With Feedback   Bulls and cows/Player
#Liberty_BASIC
Liberty BASIC
mini=0 maxi=100   print "Think of a number between ";mini;" and ";maxi print "Each time I guess a number you must state whether my" print "guess was too high, too low, or equal to your number." print   while response$<>"=" if not(mini<=maxi) then print "Error" exit while end if guess=int((maxi-mini)/2)+mini print "My guess is ";guess;". Type L for low, H for high, = for correct." input response$ response$=upper$(response$) select case response$ case "L" mini=guess+1 case "H" maxi=guess-1 case "=" print guess;" is correct." exit while case else print "Your response was not helpful." end select wend print "Thanks for playing."