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/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Yabasic
Yabasic
sub gcd(u, v) local t   u = int(abs(u)) v = int(abs(v)) while(v) t = u u = v v = mod(t, v) wend return u end sub   sub lcm(m, n) return m / gcd(m, n) * n end sub   print "Least common multiple: ", lcm(12345, 23044)
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#zkl
zkl
fcn lcm(m,n){ (m*n).abs()/m.gcd(n) } // gcd is a number method
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#SequenceL
SequenceL
  import <Utilities/Sequence.sl>; import <Utilities/Math.sl>;   main(args(2)) := LenenshteinDistance(args[1], args[2]);   LenenshteinDistance(s(1), t(1)) := 0 when equalList(s,t) else size(t) when size(s) = 0 else size(s) when size(t) = 0 else LenenshteinDistanceIterative(s, t, 0 ... size(t), duplicate(0, size(t) +...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#8080_Assembly
8080 Assembly
rawio: equ 6 ; Raw console input puts: equ 9 ; String output bdos: equ 5 ; CP/M entry point org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Routine: read 'Y' or 'N' from the keyboard. ;;; Output: carry flag clear if Y pressed, set if N pressed. yesno: mvi c,rawio ; Rea...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#R
R
letter.frequency <- function(filename) { file <- paste(readLines(filename), collapse = '') chars <- strsplit(file, NULL)[[1]] summary(factor(chars)) }
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Scala
Scala
//use Java's calendar class new java.util.GregorianCalendar().isLeapYear(year)
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Scheme
Scheme
(define (leap-year? n) (apply (lambda (a b c) (or a (and (not b) c))) (map (lambda (m) (zero? (remainder n m))) '(400 100 4))))
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#PicoLisp
PicoLisp
(de ant (Width Height X Y) (let (Field (make (do Height (link (need Width)))) Dir 0) (until (or (le0 X) (le0 Y) (> X Width) (> Y Height)) (let Cell (nth Field X Y) (setq Dir (% (+ (if (car Cell) 1 3) Dir) 4)) (set Cell (not (car Cell))) (case Dir (0 ...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Ruby
Ruby
require 'date'   def last_friday(year, month) # Last day of month: Date.new interprets a negative number as a relative month/day from the end of year/month. d = Date.new(year, month, -1) d -= (d.wday - 5) % 7 # Subtract days after Friday. end   year = Integer(ARGV.shift) (1..12).each {|month| puts last_friday(ye...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Sidef
Sidef
func lev(s, t) is cached {   s || return t.len t || return s.len   var s1 = s.ft(1) var t1 = t.ft(1)   s[0] == t[0] ? __FUNC__(s1, t1)  : 1+Math.min( __FUNC__(s1, t1), __FUNC__(s, t1), __FUNC__(s1, t ) ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#8086_Assembly
8086 Assembly
.model small .stack 1024   .data   ;no data needed   .code   start: mov ax,@code mov ds,ax   call PRIMM BYTE "Exit program and return to MS-DOS? (Y/N)",0   mov ax,0C00h int 21h ;flush keyboard buffer   forever: call waitKey ;returns ASCII code in AL   and AL,11011111b ;igno...
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#AutoHotkey
AutoHotkey
Loop, 200 ; loop 200 times while not paused { TrayTip, counting, %A_Index% press alt-p to pause Sleep, 1000 }   !p:: ; links alt-p key combination to the method pauseme() (system wide) pauseMe() Return   !r:: ; links alt-r key combination to the method resume() (system wide) resume() Return   pauseMe() { ...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Racket
Racket
  #lang racket (require math)   (define (letter-frequencies ip) (count-samples (port->list read-char ip)))   (letter-frequencies (open-input-string "abaabdc"))  
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Seed7
Seed7
const func boolean: isLeapYear (in integer: year) is return (year rem 4 = 0 and year rem 100 <> 0) or year rem 400 = 0;
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Sidef
Sidef
func isleap(year) { if (year %% 100) { return (year %% 400); } return (year %% 4); }
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#PowerShell
PowerShell
  $Size = 100   $G = @() 1..$Size | ForEach { $G += ,( @( 1 ) * $Size ) }   $x = $y = $Size / 2   # Direction of next move $Dx = 1 $Dy = 0   # While we are still on the grid... While ( $x -ge 0 -and $y -ge 0 -and $x -lt $Size -and $y -lt $Size ) { # Change direction $Dx, $Dy = ( $Dy * $G[$x][$y] ), -( $D...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Run_BASIC
Run BASIC
input "Year:";yr dayOne$ = "01-01-";yr n1 = date$(dayOne$) for i = 1 to 12 n1 = n1 + 26 m1$ = left$(date$(n1),2) while m1$ = left$(date$(n1),2) ' find end of month n1 = n1 + 1 wend n1 = n1 -1 while (n1 Mod 7) <> 3 ' find Friday n1 = n1 - 1 wend print date$(n1) ' print last Friday's date ...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Simula
Simula
BEGIN   INTEGER PROCEDURE LEVENSHTEINDISTANCE(S1, S2); TEXT S1, S2; BEGIN INTEGER N, M; N := S1.LENGTH; M := S2.LENGTH; IF N = 0 THEN LEVENSHTEINDISTANCE := M ELSE IF M = 0 THEN LEVENSHTEINDISTANCE := N ELSE BEGIN INTEGER ARRAY D(0:N, 0:M); ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#8th
8th
  \ get a yes or no response from the keyboard : yes-no con:key $20 bor dup 'y n:= if ;; then dup 'n n:= if ;; then drop yes-no ; : no? 'n n:= if "No" else "Yes" then . ;   "Yes or no? " con:print yes-no no? cr bye  
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Action.21
Action!
PROC MAIN() Byte Key=764   Printe("Press Y or N to continue")   key=255   Do Until Key=43 or Key=35 Od   Print("You pressed ") If Key=43 then Printe("Yes") Fi If Key=35 then Printe("No ") Fi   RETURN
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#BBC_BASIC
BBC BASIC
*KEY 1 |!|A *KEY 2 |!|B REPEAT key% = INKEY(1) CASE key% OF WHEN &81: PROCmethod1 WHEN &82: PROCmethod2 ENDCASE UNTIL FALSE END   DEF PROCmethod1 PRINT "You pressed F1" ENDPROC   DEF PROCmethod2 PRINT "You pressed F2...
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#C
C
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h>   int main() { Display *d; XEvent event;   d = XOpenDisplay(NULL); if ( d != NULL ) { /* or simply XK_F7 should work too */ XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, /* normall...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Raku
Raku
.&ws.say for slurp.comb.Bag.sort: -*.value;   sub ws ($pair) { $pair.key ~~ /\n/ ?? ('NEW LINE' => $pair.value) !! $pair.key ~~ /\s/ ?? ($pair.key.uniname => $pair.value) !! $pair }
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Smalltalk
Smalltalk
  Date today isLeapYear.  
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#SNOBOL4
SNOBOL4
define('leap(yr)')  :(end_leap) leap eq(remdr(yr,400),0) :s(return) eq(remdr(yr,100),0) :s(freturn) eq(remdr(yr,4),0)  :s(return)f(freturn) end_leap   * # Test and display (with ?: kluge) test = "output = ('10' ? (*leap(yr) 1 | 0)) ': ' yr" yr = '1066'; eval(test) ...
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Processing
Processing
/* * we use the following conventions: * directions 0: up, 1: left, 2: down: 3: right * * pixel white: true, black: false * * turn right: true, left: false * */   // number of iteration steps per frame // set this to 1 to see a slow animation of each // step or to 10 or 100 for a faster animation   final int ST...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Rust
Rust
use std::env::args; use time::{Date, Duration};   fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = ...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Smalltalk
Smalltalk
'kitten' levenshteinTo: 'sitting' s:1 k:1 c:1 i:1 d:1 -> 3 'rosettacode' levenshteinTo: 'raisethysword' s:1 k:1 c:1 i:1 d:1 -> 8
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Ada
Ada
function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is Answer : Character; begin Ada.Text_IO.Put (Prompt); loop Ada.Text_IO.Get_Immediate (Answer); case Answer is when 'Y'|'y' => return True; when 'N'|'n' => return False; ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#AutoHotkey
AutoHotkey
Loop, { Input, Key, L1 if (Key = "n" || Key = "y") break } MsgBox, % "The response was """ Key """." ExitApp
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Clojure
Clojure
  (ns hello-seesaw.core (:use seesaw.core))   (defn -main [& args] (invoke-later (-> (frame  :listen [:key-pressed (fn [e] (println (.getKeyChar e) " key pressed"))]  :on-close :exit) pack! show!)))  
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Delphi
Delphi
  program Key_Bindings_test;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, Winapi.Windows, Messages, Classes;   type // Class of application without window TWindowlessApplication = class private Terminated: Boolean; F7_id: Word; F6_id: Word; WIN_A: Word; procedure HandleMes...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Raven
Raven
define count_letters use $words { } as $wordHash [ ] as $keys [ ] as $vals $words each chr dup $wordHash swap get 0 prefer 1 + # stack: chr cnt swap $wordHash swap set $wordHash keys copy sort each dup $keys push $wordHash swap get $vals push $keys $vals combine print "\n" p...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Standard_ML
Standard ML
fun isLeapYear y = y mod (if y mod 100 = 0 then 400 else 4) = 0
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Stata
Stata
gen leap = mod(year,400)==0 | mod(year,4)==0 & mod(year,100)!=0
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Prolog
Prolog
%_______________________________________________________________ % Langtons ant. :-dynamic black/1.   plot_point(Row, Col) :- % Output a 5x5 black box at R,C new(C, box(5,5)), X is Col * 5 - 2, Y is Row * 5 - 2, send(C, colour, colour(black)), send(C, fill_pattern, colour(blue)), send(C, center(point(X,Y))), send...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Scala
Scala
import java.util.Calendar import java.text.SimpleDateFormat   object Fridays {   def lastFridayOfMonth(year:Int, month:Int)={ val cal=Calendar.getInstance cal.set(Calendar.YEAR, year) cal.set(Calendar.MONTH, month) cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY) cal.set(Calendar.DAY_OF_WEEK_IN_MONT...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Swift
Swift
func levDis(w1: String, w2: String) -> Int {   let (t, s) = (w1.characters, w2.characters)   let empty = Repeat(count: s.count, repeatedValue: 0) var mat = [[Int](0...s.count)] + (1...t.count).map{[$0] + empty}   for (i, tLett) in t.enumerate() { for (j, sLett) in s.enumerate() { mat[i + 1][j + 1] = t...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#AWK
AWK
  # syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK BEGIN { printf("you entered %s\n",prompt_user()) exit(0) } function prompt_user( rec) { # AWK lacks the ability to get keyboard input without pressing the enter key. while (1) { printf("enter Y or N ") getline rec <"con" gsub...
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#EchoLisp
EchoLisp
  ;; see initial bindings : GREEK DICTIONARY (meta-keys) → (("0" "❌") ("1" "❗️") ("2" "❓") ("3" "✔️") ("4" "⛔️") ("5" "✅") ("6" "🚩") ("7" "⌚️") ("8" "🏁") ("9" "😜") ("a" "α") ("b" "β") ("g" "γ") ("d" "δ") ("e" "ε") ("z" "ζ") ("h" "η") ("t" "τ") ("i" "ι") ("k" "κ") ("l" "λ") ("m" "μ") ("n" "ν") ("x" "ξ") ("q" "ο") (...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#11l
11l
V items = [(‘beef’, 3.8, 36.0), (‘pork’, 5.4, 43.0), (‘ham’, 3.6, 90.0), (‘greaves’, 2.4, 45.0), (‘flitch’, 4.0, 30.0), (‘brawn’, 2.5, 56.0), (‘welt’, 3.7, 67.0), (‘salami’, 3.0, 95.0), (‘sausage’, 5.9, 98.0)]   V M...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#REXX
REXX
/*REXX program counts the occurrences of all characters in a file, and note that all */ /* Latin alphabet letters are uppercased for also counting {Latin} letters (both cases).*/ /*════════════════════════════════════~~~~~~~~~~════════════════════════════════════════*/ abc = 'abcdefghijklmnopqrstuvwxyz' ...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Swift
Swift
func isLeapYear(year: Int) -> Bool { return year.isMultiple(of: 100) ? year.isMultiple(of: 400) : year.isMultiple(of: 4) }   [1900, 1994, 1996, 1997, 2000].forEach { year in print("\(year): \(isLeapYear(year: year) ? "YES" : "NO")") }
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#PureBasic
PureBasic
#White = $FFFFFF #Black = 0 #planeHeight = 100 #planeWidth = 100 #canvasID = 0 #windowID = 0 OpenWindow(#windowID, 0, 0, 150, 150, "Langton's ant", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) CanvasGadget(#canvasID, 25, 25, #planeWidth, #planeHeight) StartDrawing(CanvasOutput(#canvasID)) Box(0, 0, #planeWidth,...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "time.s7i"; include "duration.s7i";   const proc: main is func local var integer: weekday is 1; # 1 for monday, 2 for tuesday, and so on up to 7 for sunday. var integer: year is 0; var integer: month is 1; var time: aDate is time.value; var time: selected is t...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Tcl
Tcl
proc levenshteinDistance {s t} { # Edge cases if {![set n [string length $t]]} { return [string length $s] } elseif {![set m [string length $s]]} { return $n } # Fastest way to initialize for {set i 0} {$i <= $m} {incr i} { lappend d 0 lappend p $i } # Loop, computing the distance ta...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Axe
Axe
While getKey(0) End   While 1 If getKey(15) Disp "N",i Return ElseIf getKey(54) Disp "Y",i Return End End
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Go
Go
package main   /* #cgo LDFLAGS: -lX11 #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h>   static inline Window DefaultRootWindow_macro(Display *dpy) { return ScreenOfDisplay(dpy, DefaultScreen(dpy))->root; }   static inline int getXEvent_type(XEvent event) { return event.type; }   static inline ...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Ada
Ada
with Ada.Text_IO; with Ada.Float_Text_IO; with Ada.Strings.Unbounded;   procedure Knapsack_Continuous is package US renames Ada.Strings.Unbounded;   type Item is record Name  : US.Unbounded_String; Weight : Float; Value  : Positive; Taken  : Float; end record;   function "<" (Left, ...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Ring
Ring
  textData = read("C:\Ring\ReadMe.txt") ln =len(textData) charCount = list(255) totCount = 0   for i =1 to ln char = ascii(substr(textData,i,1)) charCount[char] = charCount[char] + 1 if char > 31 totCount = totCount + 1 ok next   for i = 32 to 255 if charCount[i] > 0 see char(i) + " = " + charCount[i] +...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Tcl
Tcl
proc isleap1 {year} { return [expr {($year % 4 == 0) && (($year % 100 != 0) || ($year % 400 == 0))}] } isleap1 1988 ;# => 1 isleap1 1989 ;# => 0 isleap1 1900 ;# => 0 isleap1 2000 ;# => 1
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Python
Python
  """Langton's ant implementation.""" from enum import Enum, IntEnum     class Dir(IntEnum): """Possible directions."""   UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3     class Color(Enum): """Possible colors."""   WHITE = " " BLACK = "#"     def invert_color(grid, x, y): """Invert the color o...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#SenseTalk
SenseTalk
  ask "What year?" put it into year   put !"The last Fridays of each month in [[year]] are:"   set lastDayOfMonth to year & "-01-31" -- start with January 31 of the year   repeat 12 times set lastFriday to lastDayOfMonth repeat until weekdayName of lastFriday is "Friday" subtract a day from lastFriday -- work back ...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#TSE_SAL
TSE SAL
// library: math: get: damerau: levenshtein <description></description> <version>1.0.0.0.23</version> <version control></version control> (filenamemacro=getmadle.s) [kn, ri, th, 08-09-2011 23:04:55] INTEGER PROC FNMathGetDamerauLevenshteinDistanceI( STRING s1, STRING s2 ) INTEGER L1 = Length( s1 ) INTEGER L2 = Length...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#BASIC
BASIC
10 LET C = PEEK (49168): REM CLEAR KEYBOARD 20 PRINT "PRESS Y OR N TO CONTINUE" 30 GET K$ 40 IF K$ < > "Y" AND K$ < > "N" THEN 30 50 PRINT "THE RESPONSE WAS ";K$  
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#HicEst
HicEst
! bound to application CALL F2 ! ... END   SUBROUTINE F2 ! this text shows as tooltip text. F2 ... F9 are possible ! synchronous call: CALL F2 ! asynchronous calls: F2 key ! mouse click on the F2 toolbar tool ! ALARM( delay_seconds, 2 )   ! che...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#AWK
AWK
# syntax: GAWK -f KNAPSACK_PROBLEM_CONTINUOUS.AWK BEGIN { # arr["item,weight,price"] arr["beef,3.8,36"] arr["pork,5.4,43"] arr["ham,3.6,90"] arr["greaves,2.4,45"] arr["flitch,4.0,30"] arr["brawn,2.5,56"] arr["welt,3.7,67"] arr["salami,3.0,95"] arr["sausage,5.9,98"] for (i in ar...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Ruby
Ruby
def letter_frequency(file) letters = 'a' .. 'z' File.read(file) . split(//) . group_by {|letter| letter.downcase} . select {|key, val| letters.include? key} . collect {|key, val| [key, val.length]} end   letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair}
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT LOOP year="1900'1994'1996'1997'2000",txt="" SET dayoftheweek=DATE(number,29,2,year,number) IF (dayoftheweek==0) SET txt="not " PRINT year," is ",txt,"a leap year" ENDLOOP
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#uBasic.2F4tH
uBasic/4tH
DO INPUT "Enter a year: "; y IF FUNC(_FNleap(y)) THEN PRINT y; " is a leap year" ELSE PRINT y; " is not a leap year" ENDIF LOOP END   _FNleap Param (1) RETURN ((a@ % 4 = 0) * ((a@ % 400 = 0) + (a@ % 100 # 0)))
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#R
R
  langton.ant = function(n = 100) { map = matrix(data = 0, nrow = n, ncol = n) p = floor(c(n/2, n/2)) d = sample(1:4, 1) i = 1 while(p[1] > 0 & p[1] <= n & p[2] > 0 & p[2] <= n) { if(map[p[1], p[2]] == 1) { map[p[1], p[2]] = 0 p = p + switch(d, c(0, 1), c(-1, 0), c(0, -1), c(1, 0)) d = ifelse(d == 4, 1,...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Sidef
Sidef
require('DateTime') var (year=2016) = ARGV.map{.to_i}...   for month (1..12) { var dt = %O<DateTime>.last_day_of_month(year => year, month => month) while (dt.day_of_week != 5) { dt.subtract(days => 1) } say dt.ymd }
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Turbo-Basic_XL
Turbo-Basic XL
  10 DIM Word_1$(20), Word_2$(20), DLDm(21, 21) 11 CLS 20 Word_1$="kitten" : Word_2$="sitting" : ? Word_1$;" - ";Word_2$ : EXEC _DLD_ : ? 30 Word_1$="rosettacode" : Word_2$="raisethysword" : ? Word_1$;" - ";Word_2$ : EXEC _DLD_ : ?   11000 END 11600 REM DamerauLevenshteinDistance INPUT(Word_1$, Word_2$, DLDm[]) USE(I, ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Batch_File
Batch File
  @echo off choice if errorlevel 2 echo You chose N if errorlevel 1 echo You chose Y >nul pause  
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#C
C
  #include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h>   void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; }   tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcset...
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Icon_and_Unicon
Icon and Unicon
  global kMap   procedure main() kMap := table() kMap["1"] := italicsOn kMap["2"] := italicsOff kMap["\x4"] := exit # ^D terminates while writes(exec(getch())) end   procedure exec(c) return (\kMap[c])() | c end   procedure italicsOn() return "<i>" end   procedure italicsOff() return ...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTSALIB" Sort% = FN_sortSAinit(1, 0) : REM Descending   nItems% = 9 maxWeight = 15.0   DIM items{(nItems%-1) name$, weight, price, worth} FOR item% = 0 TO nItems%-1 READ items{(item%)}.name$, items{(item%)}.weight, items{(item%)}.price items{(item%)}....
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Run_BASIC
Run BASIC
open "c:\rbp101\public\textFile.txt" for input as #f textData$ = input$(#f, lof( #f)) ln =len(textData$) close #f   dim charCount( 255)   for i =1 to ln char = asc(mid$(textData$,i,1)) charCount(char) = charCount(char) + 1 if char > 31 then totCount = totCount + 1 next i   for i = 32 to 255 if charC...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#UNIX_Shell
UNIX Shell
leap() { if expr $1 % 4 >/dev/null; then return 1; fi if expr $1 % 100 >/dev/null; then return 0; fi if expr $1 % 400 >/dev/null; then return 1; fi return 0; }
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Ursa
Ursa
decl int year set year (int args<1>) if (= (mod year 4) 0) if (and (= (mod year 100) 0) (not (= (mod year 400) 0))) out year " is not a leap year" endl console else out year " is a leap year" endl console end if else out year " is not a leap year" endl co...
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Racket
Racket
#lang racket   ;; contracts allow us to describe expected behaviour of funcitons (define direction/c (or/c 'u 'r 'l 'd)) (define turn/c (-> direction/c direction/c)) (define grid/c (hash/c integer? (hash/c integer? boolean?))) (define-struct/contract ant ([d direction/c] [x integer?] [y integer?]))   (define/contract (...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Smalltalk
Smalltalk
  Pharo Smalltalk   [ :yr | | firstDay firstFriday | firstDay := Date year: yr month: 1 day: 1. firstFriday := firstDay addDays: (6 - firstDay dayOfWeek). (0 to: 53) collect: [ :each | firstFriday addDays: (each * 7) ] thenSelect: [ :each | (((Date daysInMonth: each monthIndex forYear: yr) - each ...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#11l
11l
V items = [ ‘sandwich’ = (50, 60, 2), ‘map’ = (9, 150, 1), ‘compass’ = (13, 35, 1), ‘water’ = (153, 200, 3), ‘glucose’ = (15, 60, 2), ‘tin’ = (68, 45, 3), ‘banana’ = (27, 60, 3), ‘apple’ = (39, 40, 3), ‘cheese’ = (23, 30, 1), ‘beer’...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#11l
11l
T Bounty Int value Float weight, volume F (value, weight, volume) (.value, .weight, .volume) = (value, weight, volume)   V panacea = Bounty(3000, 0.3, 0.025) V ichor = Bounty(1800, 0.2, 0.015) V gold = Bounty(2500, 2.0, 0.002) V sack = Bounty( 0, 25.0, 0.25) V best = Bounty( 0, 0, 0)...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT distance=DISTANCE ("kitten", "sitting") PRINT distance  
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#C.23
C#
using System;   namespace Y_or_N { class Program { static void Main() { bool response = GetYorN(); }   static bool GetYorN() { ConsoleKey response; // Creates a variable to hold the user's response.   do { wh...
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Java
Java
  package keybord.macro.demo;   import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;   class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame();   String directions = "<html><b>Ctrl-S</b...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Befunge
Befunge
9:02p>:5+::::::0\g68*-55+*\1\g68*-+\0\pv>2gg!*::!2v >\`!v|:-1p\3\0p\2\+-*86g\3\*+55-*86g\2<<1v*g21\*g2< nib@_>0022p6>12p:212gg48*:**012gg/\-:0`3^+>,,55+%6v #v0pg2231$$_^#`+5g20:+1g21$_+#!:#<0#<<p22<\v84,+*8< *>22gg+::55*6*`\55*6*-*022gg\-:55+/68*+"."^>*"fo "v ^6*55:,+55$$_,#!1#`+#*:#82#42#:g<g22:4,,,,,,," kg"< 3836beef...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Rust
Rust
use std::collections::btree_map::BTreeMap; use std::{env, process}; use std::io::{self, Read, Write}; use std::fmt::Display; use std::fs::File;   fn main() { let filename = env::args().nth(1) .ok_or("Please supply a file name") .unwrap_or_else(|e| exit_err(e, 1));   let mut buf = String::new(); ...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Vala
Vala
void main() { DateYear[] years = { 1900, 1994, 1996, 1997, 2000 }; foreach ( DateYear year in years ) { string status = year.is_leap_year() ? "" : "not "; print (@"$year is $(status)a leap year.\n"); } }
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#VBA
VBA
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Raku
Raku
constant @vecs = [1,0,1], [0,-1,1], [-1,0,1], [0,1,1]; constant @blocky = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'.comb; constant $size = 100; enum Square <White Black>; my @plane = [White xx $size] xx $size; my ($x, $y) = $size/2, $size/2; my $dir = @vecs.keys.pick; my $moves = 0; loop { given @plane[$x][$y] { when :!defined { ...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#SQL
SQL
  SELECT to_char( next_day( last_day( add_months( to_date(  :yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday FROM dual CONNECT BY level <= 12;  
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#AutoHotkey
AutoHotkey
Item = map,compass,water,sandwich,glucose,tin,banana,apple,cheese,beer,suntan cream ,camera,tshirt,trousers,umbrella,waterproof trousers,waterproof overclothes,notecase ,sunglasses,towel,socks,book Weight= 9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30 Value = 150,35,200,60,60,45,60,40,30,1...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#360_Assembly
360 Assembly
* Knapsack problem/Unbounded 04/02/2017 KNAPSACK CSECT USING KNAPSACK,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#TypeScript
TypeScript
  function levenshtein(a: string, b: string): number { const m: number = a.length, n: number = b.length; let t: number[] = [...Array(n + 1).keys()], u: number[] = []; for (let i: number = 0; i < m; i++) { u = [i + 1]; for (let j: number = 0; j < n; j++) { u[j + 1] = a[i] ==...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#C.2B.2B
C++
#include <conio.h> #include <iostream>   using namespace std;   int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N');   if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }  
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#JavaScript
JavaScript
document.onkeydown = function(evt) { if (evt.keyCode === 118) { alert("You pressed F7!"); return false; } }
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Julia
Julia
using Gtk   function keypresswindow() tcount = 0 txt = "Press a Number Key" win = GtkWindow("Keyboard Macros Test", 300, 50) |> (GtkFrame() |> ((vbox = GtkBox(:v)) |> (lab = GtkLabel(txt)))) function keycall(w, event) ch = Char(event.keyval) if isdigit(ch) set_gtk_property!(l...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Bracmat
Bracmat
( ( fixed {function to convert a rational number to fixed point notation. The second argument is the number of decimals. } = value decimals powerOf10 .  !arg:(?value.?decimals) & 10^!decimals:?powerOf10 & str $ ( div$(!value.1) "." ...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#S-BASIC
S-BASIC
  $constant EOF = 1AH rem normal end-of-file marker   rem Convert character to upper case function upcase(ch = char) = char if ch >= 'a' and ch <= 'z' then ch = ch - 32 end = ch   rem Convert string to all upper case characters function allcaps(source = string) = string var p = integer for p = ...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#VBScript
VBScript
  Function IsLeapYear(yr) IsLeapYear = False If yr Mod 4 = 0 And (yr Mod 400 = 0 Or yr Mod 100 <> 0) Then IsLeapYear = True End If End Function   'Testing the function. arr_yr = Array(1900,1972,1997,2000,2001,2004)   For Each yr In arr_yr If IsLeapYear(yr) Then WScript.StdOut.WriteLine yr & " is leap year." El...
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Vedit_macro_language
Vedit macro language
while (#1 = Get_Num("Year: ")) { #2 = (#1 % 4 == 0) && ((#1 % 100 != 0) || (#1 % 400 == 0)) if (#2) { Message(" is leap year\n") } else { Message(" is not leap year\n") } }
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#REXX
REXX
/*REXX program implements Langton's ant walk and displays the ant's path (finite field).*/ parse arg dir char seed . /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/ if dir=='' | dir=="," then dir= random(1, 4)...
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Stata
Stata
program last_fridays args year clear qui set obs 12 gen day=dofm(mofd(mdy(_n,1,`year'))+1)-1 qui replace day=day-mod(dow(day)-5,7) format %td day list, noobs noheader sep(6) end   last_fridays 2012   +-----------+ | 27jan2012 | | 24feb2012 | | 30mar2012 | | 27apr2012 | | 25may2012 | | 29jun2012 | ...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Bracmat
Bracmat
(knapsack= ( things = (map.9.150.1) (compass.13.35.1) (water.153.200.2) (sandwich.50.60.2) (glucose.15.60.2) (tin.68.45.3) (banana.27.60.3) (apple.39.40.3) (cheese.23.30.1) (beer.52.10.3) (suntan cream.11.70.1) (camera.32.30.1) (T-shirt.24.15...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Ada
Ada
with Ada.Text_IO;   procedure Knapsack_Unbounded is   type Bounty is record Value  : Natural; Weight : Float; Volume : Float; end record;   function Min (A, B : Float) return Float is begin if A < B then return A; else return B; end if; end Min;   ...
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Vala
Vala
class LevenshteinDistance : Object { public static int compute (owned string s, owned string t, bool case_sensitive = false) { var n = s.length; var m = t.length; var d = new int[n + 1, m + 1]; if (case_sensitive == false) { s = s.down (); t = t.down (); ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Clojure
Clojure
$ lein trampoline run
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Common_Lisp
Common Lisp
  (defun rosetta-y-or-n () (clear-input *query-io*) (y-or-n-p))