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/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Euler_Math_Toolbox
Euler Math Toolbox
  >A=loadrgb("mona.jpg"); >insrgb(A); >function grayscale (A) ... ${r,g,b}=getrgb(A); $c=0.2126*r+0.7152*g+0.0722*b; $return rgb(c,c,c); $endfunction >insrgb(grayscale(A)); >insrgb(A|grayscale(A));  
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Euphoria
Euphoria
function to_gray(sequence image) sequence color for i = 1 to length(image) do for j = 1 to length(image[i]) do color = and_bits(image[i][j], {#FF0000,#FF00,#FF}) / {#010000,#0100,#01} -- unpack color triple image[i][j] = floor(0.2126*colo...
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 t...
#Go
Go
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
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 ...
#Chapel
Chapel
use BigInteger; use Time;   // Chapel doesn't have closure functions that can capture variables from // outside scope, so we use a class to emulate them for this special case; // the member fields mult, mrglst, and mltlst, emulate "captured" variables // that would normally be captured by the `next` continuation closur...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#EasyLang
EasyLang
n = random 10 + 1 write "Guess a number between 1 and 10: " repeat g = number input write g until g = n print " is wrong" write "try again: " . print " is correct. Well guessed!"
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make local number_to_guess: INTEGER do number_to_guess := (create {RANDOMIZER}).random_integer_in_range (1 |..| 10) from print ("Please guess the number!%N") io.read_integer until io.last_integer = number_to_guess l...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Crystal
Crystal
def subarray_sum(arr) max, slice = 0, [] of Int32 arr.each_index do |i| (i...arr.size).each do |j| sum = arr[i..j].sum max, slice = sum, arr[i..j] if sum > max end end [max, slice] end
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#D
D
import std.stdio;   inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc { int maxSum, thisSum, i, start, end = -1;   foreach (immutable j, immutable x; sequence) { thisSum += x; if (thisSum < 0) { i = j + 1; thisSum = 0; } else if (thisSum > maxSum) { ...
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#Wren
Wren
import "graphics" for Canvas, Color import "input" for Mouse, Keyboard import "dome" for Window import "./polygon" for Polygon   class Button { construct new(x, y, w, h, legend, c, oc, lc) { var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]] _rect = Polygon.quick(vertices) _x = x ...
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...
#CLU
CLU
read_number = proc (prompt: string) returns (int) po: stream := stream$primary_output() pi: stream := stream$primary_input() while true do stream$puts(po, prompt) return(int$parse(stream$getl(pi))) except when bad_format: stream$putl(po, "Invalid number.") end ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#PicoLisp
PicoLisp
(let Pgm # Create PGM of 384 x 288 pixels (make (for N 4 (let L (make (for I (* N 8) (let C (*/ (dec I) 255 (dec (* N 8))) (unless (bit? 1 N) (setq C (- 255 C)) ) (do (/ 48 N) (link C)) ) ) ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Plain_English
Plain English
To run: Start up. Clear the screen. Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4. Make a gradient with the box and 8 and "left-to-right". Draw the gradient. Draw the next gradient given the gradient. Draw the next gradient given the gradient. Draw...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#PureBasic
PureBasic
EnableExplicit   Macro Check(Function) If Not Function : End : EndIf EndMacro   Check(InitKeyboard()) ; Cannot initialize keyboard Check(InitSprite()) ; Cannot initialize sprite/screen library Check(ExamineDesktops()) ; Cannot retrieve informations about desktops   Define.i iHeight, iWidth, iDepth iHeight = D...
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Nim
Nim
import strutils   let oRange = 1..10 var iRange = oRange   echo """Think of a number between $# and $# and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by typing h, l, or =""".format(iRange.a, iRange.b)   var i = 0 while true: inc i ...
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#NS-HUBASIC
NS-HUBASIC
10 PRINT "THINK OF A NUMBER BETWEEN 1 AND";" 9, AND I'LL TRY TO GUESS IT." 20 ISVALID=0 30 GUESS=5 40 PRINT "I GUESS"GUESS"." 50 INPUT "IS THAT HIGHER THAN, LOWER THAN OR EQUAL TO YOUR NUMBER? ",ANSWER$ 60 IF ANSWER$="LOWER THAN" THEN ISVALID=1:IF GUESS<9 THEN GUESS=GUESS+1 70 IF ANSWER$="HIGHER THAN" THEN ISVALID=1:IF...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Dyalect
Dyalect
func happy(n) { var m = [] while n > 1 { m.Add(n) var x = n n = 0 while x > 0 { var d = x % 10 n += d * d x /= 10 } if m.IndexOf(n) != -1 { return false } } return true }   var (n, found) = (1, 0) whi...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Objeck
Objeck
  bundle Default { class Haversine { function : Dist(th1 : Float, ph1 : Float, th2 : Float, ph2 : Float) ~ Float { ph1 -= ph2; ph1 := ph1->ToRadians(); th1 := th1->ToRadians(); th2 := th2->ToRadians();   dz := th1->Sin()- th2->Sin(); dx := ph1->Cos() * th1->Cos() - th2->Cos(); ...
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
#Genie
Genie
  init print "Hello world!"  
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/...
#Pascal
Pascal
program Niven;   {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   const base = 10;   type tNum = longword; {Uint64} {$IFDEF FPC}   const cntbasedigits = trunc(ln(High(tNum)) / ln(base)) + 1; {$ELSE}   var cntbasedigits: Integer = 0; {$ENDIF}   type tSumDigit = record sdNumber: tNum; {$IFDEF FPC} sdDigits: arr...
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
#JavaScript
JavaScript
alert("Goodbye, World!");
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Python
Python
  import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)...
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 follow...
#APL
APL
N←5 ({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)
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 follow...
#Arturo
Arturo
toGray: function [n]-> xor n shr n 1 fromGray: function [n][ p: n while [n > 0][ n: shr n 1 p: xor p n ] return p ]   loop 0..31 'num [ encoded: toGray num decoded: fromGray encoded   print [ pad to :string num 2 ":" pad as.binary num 5 "=>" pad as....
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#6502_Assembly
6502 Assembly
JSR $FFED ;returns screen width in X and screen height in Y dex  ;subtract 1. This is more useful for comparisons. dey  ;subtract 1. This is more useful for comparisons. stx $20 ;store in zero page ram sty $21 ;store in zero page ram
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.
#Aime
Aime
integer lmax(list l) { integer max, x;   max = l[0];   for (, x in l) { if (max < x) { max = x; } }   max; }
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#360_Assembly
360 Assembly
* Greatest common divisor 04/05/2016 GCD CSECT USING GCD,R15 use calling register L R6,A u=a L R7,B v=b LOOPW LTR R7,R7 while v<>0 BZ ELOOPW leave while LR R8,R6 ...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Ada
Ada
with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;   procedure Global_Replace is   subtype U_String is Ada.Strings.Unbounded.Unbounded_String; function "+"(S: String) return U_String renames Ada.Strings.Unbounded.To_Unbounded_String; function "-"(U: U_String) return String renames...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure hailstone is type int_arr is array(Positive range <>) of Integer; type int_arr_pt is access all int_arr;   function hailstones(num:Integer; pt:int_arr_pt) return Integer is stones : Integer := 1; n : Integer := num; begin if pt /= null then pt(1) := num; end if; ...
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...
#Raku
Raku
sub GraphNodeColor(@RAW) { my %OneMany = my %NodeColor; for @RAW { %OneMany{$_[0]}.push: $_[1] ; %OneMany{$_[1]}.push: $_[0] } my @ColorPool = "0", "1" … ^+%OneMany.elems; # as string my %NodePool = %OneMany.BagHash; # this DWIM is nice if %OneMany<NaN>:exists { %NodePool{$_}:delete for %OneMany<NaN>, N...
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),...
#Wren
Wren
import "./math" for Int import "./trait" for Stepped import "./fmt" for Fmt import "io" for File   var limit = 2000 var primes = Int.primeSieve(limit-1).skip(1).toList var goldbach = {4: 1} for (i in Stepped.new(6..limit, 2)) goldbach[i] = 0 for (i in 0...primes.count) { for (j in i...primes.count) { var s ...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Factor
Factor
USING: arrays kernel math math.matrices math.vectors ;   : rgb>gray ( matrix -- new-matrix ) [ { 0.2126 0.7152 0.0722 } vdot >integer ] matrix-map ;   : gray>rgb ( matrix -- new-matrix ) [ dup dup 3array ] matrix-map ;
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#FBSL
FBSL
DIM colored = ".\LenaClr.bmp", grayscale = ".\LenaGry.bmp" DIM head, tail, r, g, b, l, ptr, blobsize = 54 ' sizeof BMP file headers   FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' load buffer head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' set loop bounds   FOR ptr = head TO tail S...
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 t...
#Haskell
Haskell
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
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 ...
#Clojure
Clojure
(defn smerge [xs ys] (lazy-seq (let [x (first xs), y (first ys), [z xs* ys*] (cond (< x y) [x (rest xs) ys] (> x y) [y xs (rest ys)]  :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*)))))   (def hamming (lazy-seq (->> (map #(*' ...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Elena
Elena
import extensions;   public program() { int randomNumber := randomGenerator.eval(1,10); console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?"); bool numberCorrect := false; until(numberCorrect) { console.print("Guess: "); int userGuess := console.readLine(...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Elixir
Elixir
defmodule GuessingGame do def play do play(Enum.random(1..10)) end   defp play(number) do guess = Integer.parse(IO.gets "Guess a number (1-10): ") case guess do {^number, _} -> IO.puts "Well guessed!" {n, _} when n in 1..10 -> IO.puts "That's not it." play(number) ...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Delphi
Delphi
pragma.enable("accumulator")   def maxSubseq(seq) { def size := seq.size()   # Collect all intervals of indexes whose values are positive def intervals := { var intervals := [] var first := 0 while (first < size) { var next := first def seeing := seq[first] > 0 while (next < size && ...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Guess-With-Feedback.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 Seed PIC 9(8). 01 Random-Num PIC 99. 01 Guess PIC 99.   PROCEDURE DIVISION. ACCEPT Seed FROM TIME COMPUTE Random-Num = ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Python
Python
#!/usr/bin/env python #four gray scaled stripes 8:16:32:64 in Python 2.7.1   from livewires import *   horiz=640; vert=480; pruh=vert/4; dpp=255.0 begin_graphics(width=horiz,height=vert,title="Gray stripes",background=Colour.black)   def ty_pruhy(each): hiy=each[0]*pruh; loy=hiy-pruh krok=horiz/each[1]; piecol=255.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 ha...
#R
R
  mat <- matrix(c(rep(1:8, each = 8) / 8, rep(16:1, each = 4) / 16, rep(1:32, each = 2) / 32, rep(64:1, each = 1) / 64), nrow = 4, byrow = TRUE) par(mar = rep(0, 4)) image(t(mat[4:1, ]), col = gray(1:64/64), axes = FALSE)  
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface GuessNumberFakeArray : NSArray { int lower, upper; } - (instancetype)initWithLower:(int)l andUpper:(int)u; @end   @implementation GuessNumberFakeArray - (instancetype)initWithLower:(int)l andUpper:(int)u { if ((self = [super init])) { lower = l; upper = u; } ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
next-num: 0 while over: over * dup % swap 10 + swap floor / swap 10 swap drop swap   is-happy happies n: if has happies n: return happies! n local :seq set{ n } n while /= 1 dup: next-num if has seq dup: drop set-to happies n false return false if has happies dup: set-to happies n dup...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Objective-C
Objective-C
+ (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1 lat2:(double)lat2 lon2:(double)lon2 { //degrees to radians double lat1rad = lat1 * M_PI/180; double lon1rad = lon1 * M_PI/180; double lat2rad = lat2 * M_PI/180; double lon2rad = lon2 * M_PI/180;   //deltas ...
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
#Gentee
Gentee
func hello <main> { print("Hello world!") }
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/...
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use List::Util qw ( sum ) ;   sub createHarshads { my @harshads ; my $number = 1 ; do { if ( $number % sum ( split ( // , $number ) ) == 0 ) { push @harshads , $number ; } $number++ ; } until ( $harshads[ -1 ] > 1000 ) ; return @harshads ; ...
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
#jq
jq
# Convert a JSON object to a string suitable for use as a CSS style value # e.g: "font-size: 40px; text-align: center;" (without the quotation marks) def to_s: reduce to_entries[] as $pair (""; . + "\($pair.key): \($pair.value); ");   # Defaults: 100%, 100% def svg(width; height): "<svg width='\(width // "100%")' ...
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
#JSE
JSE
Text 25,10,"Goodbye, World!"
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#R
R
  library(gWidgets) options(guiToolkit="RGtk2") ## using gWidgtsRGtk2   w <- gwindow("Interaction")   g <- ggroup(cont=w, horizontal=FALSE) e <- gedit(0, cont=g, coerce.with=as.numeric) bg <- ggroup(cont=g)   inc_btn <- gbutton("increment", cont=bg) rdm_btn <- gbutton("random", cont=bg)   addHandlerChanged(e, handler=f...
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Racket
Racket
  #lang racket/gui   (define frame (new frame% [label "Interaction Demo"]))   (define inp (new text-field% [label "Value"] [parent frame] [init-value "0"] [callback (λ(f ev) (define v (send f get-value)) (unless (string->number v) (send f set-value (regexp-replace* #rx"[...
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 follow...
#AutoHotkey
AutoHotkey
gray_encode(n){ return n ^ (n >> 1) }   gray_decode(n){ p := n while (n >>= 1) p ^= n return p }   BinString(n){ Loop 5 If ( n & ( 1 << (A_Index-1) ) ) o := "1" . o else o := "0" . o return o }   Loop 32 n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n)) . " => " BinString(...
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#68000_Assembly
68000 Assembly
doRNG: ;run this during vblank for best results. JSR SYS_READ_CALENDAR ;gets the calendar. ;MAME uses your computer's time for this. MOVE.L BIOS_HOUR,D0 ;D0 = HHMMSS00 LSR.L #8,D0 ;shift out the zeroes. MOVE.L frame_timer,D1 ;this value is incremented by 1 every vBlank (i.e. just ...
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with GNAT.Expect; use GNAT.Expect; with GNAT.OS_Lib; use GNAT.OS_Lib; with GNAT.String_Split; use GNAT.String_Split;   procedure System_Command is Command  : String  := "ls -l";...
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.
#ALGOL_68
ALGOL 68
# substitute any array type with a scalar element # MODE FLT = REAL;   # create an exception for the case of an empty array # PROC raise empty array = VOID:( GO TO except empty array );   PROC max = ([]FLT item)FLT: BEGIN IF LWB item > UPB item THEN raise empty array; SKIP ELSE FLT max element := ite...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#8th
8th
: gcd \ a b -- gcd dup 0 n:= if drop ;; then tuck \ b a b n:mod \ b a-mod-b recurse ;   : demo \ a b -- 2dup "GCD of " . . " and " . . " = " . gcd . ;   100 5 demo cr 5 100 demo cr 7 23 demo cr   bye  
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#AutoHotkey
AutoHotkey
SetWorkingDir %A_ScriptDir% ; Change the working directory to the script's location listFiles := "a.txt|b.txt|c.txt" ; Define a list of files in the current working directory loop, Parse, listFiles, | { ; The above parses the list based on the | character fileread, contents, %A_LoopField% ; Read the file fileDe...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#AWK
AWK
  # syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s) BEGIN { old_text = "Goodbye London!" new_text = "Hello New York!" } BEGINFILE { nfiles_in++ text_found = 0 delete arr } { if (gsub(old_text,new_text,$0) > 0) { text_found++ } arr[FNR] = $0 } ENDFILE { if (...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Aime
Aime
void print_hailstone(integer h) { list l;   while (h ^ 1) { lb_p_integer(l, h); h = h & 1 ? 3 * h + 1 : h / 2; }   o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n", l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, ~l + 1); }   void max_hailstone(integer ...
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...
#Wren
Wren
import "/dynamic" for Struct import "/sort" for Sort import "/fmt" for Fmt   // (n)umber of node and its (v)alence i.e. number of neighbors var NodeVal = Struct.create("NodeVal", ["n", "v"])   class Graph { construct new(nn, st) { _nn = nn // number of nodes _st = st ...
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),...
#XPL0
XPL0
  func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int PT(1_000_000);   func G(E); \Ways E can be expressed as sum of two primes int...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Forth
Forth
\ grayscale bitmap (without word-alignment for scan lines)   \ bdim, bwidth, bdata all work with graymaps   : graymap ( w h -- gmp ) 2dup * bdata allocate throw dup >r 2! r> ;   : gxy ( x y gmp -- addr ) dup bwidth rot * rot + swap bdata + ;   : g@ ( x y gmp -- c ) gxy c@ ; : g! ( c x y bmp -- ) gxy c! ;   : gfil...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Fortran
Fortran
type scimage integer, dimension(:,:), pointer :: channel integer :: width, height end type scimage
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 t...
#Icon_and_Unicon
Icon and Unicon
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
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 ...
#CoffeeScript
CoffeeScript
# Generate hamming numbers in order. Hamming numbers have the # property that they don't evenly divide any prime numbers outside # a given set, such as [2, 3, 5].   generate_hamming_sequence = (primes, max_n) -> # We use a lazy algorithm, only ever keeping N candidates # in play, one for each of our seed primes. ...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Emacs_Lisp
Emacs Lisp
(let ((number (1+ (random 10)))) (while (not (= (read-number "Guess the number ") number)) (message "Wrong, try again.")) (message "Well guessed! %d" number))
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Erlang
Erlang
% Implemented by Arjun Sunel -module(guess_the_number). -export([main/0]).   main() -> io:format("Guess my number between 1 and 10 until you get it right:\n"), N = random:uniform(10), guess(N).   guess(N) -> {ok, [K]} = io:fread("Guess number : ","~d"),   if K=:=N -> io:format("Well guessed!!\n"); true ->...
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#E
E
pragma.enable("accumulator")   def maxSubseq(seq) { def size := seq.size()   # Collect all intervals of indexes whose values are positive def intervals := { var intervals := [] var first := 0 while (first < size) { var next := first def seeing := seq[first] > 0 while (next < size && ...
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...
#Common_Lisp
Common Lisp
(defun guess-the-number-feedback (&optional (min 1) (max 100)) (let ((num-guesses 0) (num (+ (random (1+ (- max min))) min)) (guess nil)) (format t "Try to guess a number from ~:d to ~:d!~%" min max) (loop do (format t "Guess? ") (incf num-guesses) (setf guess (read)) (format t "Your guess is ~[not...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Racket
Racket
  #lang racket/gui (require slideshow/pict)   (define-values (*width* *height*) (values 400 40))   (define (shades inc) (for/list ([scale (in-range 0 (+ 1 inc) inc)]) (round (* 255 scale))))   (define (grays increment direction) (define colors (shades increment)) (apply hc-append ((if (eq? direction ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Raku
Raku
my ($width,$height) = 1280,768;   my $PGM = open "Greyscale-bars-perl6.pgm", :w orelse die "Can't create Greyscale-bars-perl6.pgm: $_";   $PGM.print: qq:to/EOH/; P2 # Greyscale-bars-perl6.pgm $width $height 65535 EOH   my ($h1,$h2,$h3,$h4) = divvy($height,4);   my @nums = ((0/7,1/7...7/7) X* 65535)»...
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#PARI.2FGP
PARI/GP
  guessnumber2(b)={ my(c=0,d=b,a=0); for(x=1,b, for(y=1,b, if(a<c||a==c||a==d||a>d, a=random(b), break() ) ); print("I guess "a" am I h,l,or e ?"); g=input(); if(g==h, d=a, if(g==l, c=a, if(g==e, break() ) ...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#E
E
def isHappyNumber(var x :int) { var seen := [].asSet() while (!seen.contains(x)) { seen with= x var sum := 0 while (x > 0) { sum += (x % 10) ** 2 x //= 10 } x := sum if (x == 1) { return true } } return false }   var count := 0 for x ? (isHappyNumber(x)) in (int >= 1) { pri...
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#OCaml
OCaml
(* Preamble -- some math, and an "angle" type which might be part of a common library. *) let pi = 4. *. atan 1. let radians_of_degrees = ( *. ) (pi /. 180.) let haversin theta = 0.5 *. (1. -. cos theta)   (* The angle type can track radians or degrees, which I'll use for automatic conversion. *) type angle = Deg of fl...
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
#GFA_Basic
GFA Basic
PRINT "Hello World"
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/...
#Phix
Phix
integer n = 0 sequence digits={0} procedure nNiven() while 1 do n += 1 for i=length(digits) to 0 by -1 do if i=0 then digits = prepend(digits,1) exit end if if digits[i]<9 then digits[i] += 1 exit ...
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
#Jsish
Jsish
prompt$ jsish Jsish interactive: see 'help [cmd]'. \ cancels > input. ctrl-c aborts running script. # require('JsiAgarGUI') 1 # JsiAgarGUI.alert("Goodbye, World!"); #
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Julia
Julia
using Tk   window = Toplevel("Hello World", 200, 100, false) pack_stop_propagate(window)   fr = Frame(window) pack(fr, expand=true, fill="both")   txt = Label(fr, "Hello World") pack(txt, expand=true)   set_visible(window, true)   # sleep(7)
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Raku
Raku
use GTK::Simple; use GTK::Simple::App;   my GTK::Simple::App $app .= new(title => 'GUI component interaction');   $app.set-content( my $box = GTK::Simple::VBox.new( my $value = GTK::Simple::Entry.new(text => '0'), my $increment = GTK::Simple::Button.new(label => 'Increment'), my $random ...
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 follow...
#AWK
AWK
# Tested using GAWK   function bits2str(bits, data, mask) { # Source: https://www.gnu.org/software/gawk/manual/html_node/Bitwise-Functions.html if (bits == 0) return "0"   mask = 1 for (; bits != 0; bits = rshift(bits, 1)) data = (and(bits, mask) ? "1" : "0") data   while ((le...
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Aime
Aime
o_("-- ", sshell().plan("expr", "8", "*", "9").link.b_dump('\n'), " --\n");
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Amazing_Hopper
Amazing Hopper
  /* JAMBO language - a flavour of Hopper */ #include <jambo.h> Main sys = `cat jm/sys1.jambo` Set( sys ) Prnl End  
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Applesoft_BASIC
Applesoft BASIC
100 HIMEM: 24576 110 LET A = 24576 120 LET P = 768 130 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256 140 DEF FN H(A) = INT (A / 256) 150 DEF FN L(A) = A - FN H(A) * 256 160 POKE P + 00,073: REM EOR 170 POKE P + 01,128: REM #$80 180 POKE P + 02,141: REM STA 190 POKE P + 03, FN L(A) 200 POKE P...
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.
#ALGOL_W
ALGOL W
begin  % simple list type  % record IntList( integer val; reference(IntList) next );    % find the maximum element of an IntList, returns 0 for an empty list  % integer procedure maxElement( reference(IntList) value list ) ; begin ...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program calPgcd64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#BASIC
BASIC
CONST matchtext = "Goodbye London!" CONST repltext = "Hello New York!" CONST matchlen = LEN(matchtext)   DIM L0 AS INTEGER, x AS INTEGER, filespec AS STRING, linein AS STRING   L0 = 1 WHILE LEN(COMMAND$(L0)) filespec = DIR$(COMMAND$(L0)) WHILE LEN(filespec) OPEN filespec FOR BINARY AS 1 li...
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#BBC_BASIC
BBC BASIC
FindThis$ = "Goodbye London!" ReplaceWith$ = "Hello New York!"   DIM Files$(3) Files$() = "C:\test1.txt", "C:\test2.txt", "C:\test3.txt", "C:\test4.txt"   FOR f% = 0 TO DIM(Files$(),1) infile$ = Files$(f%) infile% = OPENIN(infile$) IF infile%=0 ERROR 100, "Failed to...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ALGOL_60
ALGOL 60
begin comment Hailstone sequence - Algol 60; integer array collatz[1:400]; integer icollatz;   integer procedure mod(i,j); value i,j; integer i,j; mod:=i-(i div j)*j;   integer procedure hailstone(num); value num; integer num; begin integer i,n; icollatz:=1; n:=num; i:=0; ...
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...
#zkl
zkl
fcn colorGraph(nodeStr){ // "0-1 1-2 2-0 3" numEdges,graph := 0,Dictionary(); // ( 0:(1,2), 1:L(0,2), 2:(1,0), 3:() ) foreach n in (nodeStr.split(" ")){ // parse string to graph n=n - " "; if(n.holds("-")){ a,b := n.split("-"); // keep as string graph.appendV(a,b); graph.appendV(b,a); numEdges...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim As Integer ancho = 143, alto = 188, x, y, p, red, green, blue, luminancia Dim As String imagen = "Mona_Lisa.bmp" Screenres ancho,alto,32 Bload imagen   For x = 0 To ancho-1 For y = 0 To alto-1 p = Point(x,y) red = p Mod 256 p = p \ 256 green = p Mod 256 p = p \ 256 ...
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#FreeBASIC
FreeBASIC
Dim As Integer ancho = 143, alto = 188, x, y, p, red, green, blue, luminancia Dim As String imagen = "Mona_Lisa.bmp" Screenres ancho,alto,32 Bload imagen   For x = 0 To ancho-1 For y = 0 To alto-1 p = Point(x,y) red = p Mod 256 p = p \ 256 green = p Mod 256 p = p \ 256 ...
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 t...
#J
J
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
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 ...
#Common_Lisp
Common Lisp
(defun next-hamm (factors seqs) (let ((x (apply #'min (map 'list #'first seqs)))) (loop for s in seqs for f in factors for i from 0 with add = t do (if (= x (first s)) (pop s)) ;; prevent a value from being added to multiple lists (when add (setf (elt seqs i) (nconc s (list (* x f)))) ...
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#ERRE
ERRE
  PROGRAM GUESS_NUMBER   ! ! for rosettacode.org !   BEGIN   RANDOMIZE(TIMER) N=0 R=INT(RND(1)*100+1)  ! RND function gives a random number from 0 to 1 G=0 C$=""   WHILE G<>R DO INPUT("Pick a number between 1 and 100";G) IF G=R THEN PRINT("You got it!") N+=1 PRINT("It took";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,   a...
#Euphoria
Euphoria
include get.e   integer n,g n = rand(10)   puts(1,"I have thought of a number from 1 to 10.\n") puts(1,"Try to guess it!\n")   while 1 do g = prompt_number("Enter your guess: ",{1,10}) if n = g then exit end if puts(1,"Your guess was wrong. Try again!\n") end while   puts(1,"Well done! You 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 th...
#EchoLisp
EchoLisp
  (lib 'struct) (struct result (score starter))   ;; the score of i in sequence ( .. i j ...) is max (i , i + score (j)) ;; to compute score of (a b .. x y z) : ;; start with score(z) and compute scores of y , z , ..c, b , a. ;; this is O(n)   ;; return value of sub-sequence (define (max-max L into: result) (define v...
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...
#Crystal
Crystal
number = rand(1..10)   puts "Guess the number between 1 and 10"   loop do begin user_number = gets.to_s.to_i if user_number == number puts "You guessed it." break elsif user_number > number puts "Too high." else puts "Too low." end rescue ArgumentError puts "Please ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#RapidQ
RapidQ
  Declare Sub PaintCanvas   Create Form as Qform Caption = "Rosetta Greyscale" Center create Canv as QCanvas align = 5 onPaint = PaintCanvas end create end create   Sub PaintCanvas NumRows = 4 'Change for number of rows for curbar = 0 to NumRows-1 Bars = 2^(curbar+3) ...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Ring
Ring
  # Project : Greyscale bars/Display   load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Greyscale bars/Display") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(...
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Run_BASIC
Run BASIC
for i = 1 to 4 incr = int(256 / (i * 8)) c = 256 html "<table style='width: 200px; height: 11px;' border=0 cellpadding=0 cellspacing=0><tr>" for j = 1 to i * 8 html "<td style='background-color: rgb(";c;",";c;",";c;");'></td>" c = c - incr next j html "</tr>" next i html "</table>" 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 score...
#Pascal
Pascal
Program GuessIt(input, output);   var done, ok: boolean; guess, upp, low: integer; res: char;   begin writeln ('Choose a number between 0 and 1000.'); write ('Press Enter and I will start to guess the number.'); readln; upp := 1000; low := 0; repeat ok := false; guess := ( (...
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make -- Run application. local l_val: INTEGER do from l_val := 1 until l_val > 100 loop if is_happy_number (l_val) then print (l_val.out) print ("%N") end l_val := l_val + 1 end end   feature ...