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/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...
#Clojure
Clojure
(defstruct item :value :weight :volume)   (defn total [key items quantities] (reduce + (map * quantities (map key items))))   (defn max-count [item max-weight max-volume] (let [mcw (/ max-weight (:weight item)) mcv (/ max-volume (:volume item))] (min mcw mcv)))
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 ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM ZX Spectrum Basic - Levenshtein distance 20 INPUT "first word:",n$ 30 INPUT "second word:",m$ 40 LET n=LEN n$:LET m=LEN m$:DIM d(m+1,n+1) 50 FOR i=1 TO m:LET d(i+1,1)=i:NEXT i 60 FOR j=1 TO n:LET d(1,j+1)=j:NEXT j 70 FOR j=1 TO n 80 FOR i=1 TO m 90 LET r=d(i,j)-(n$(j)=m$(i)):REM substitution 100 ...
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...
#F.23
F#
open System   let rec yorn () = let rec flush () = if Console.KeyAvailable then ignore (Console.ReadKey()); flush () flush ()   printf "\nY or N? " match Console.ReadKey().Key with | ConsoleKey.Y -> 'Y' | ConsoleKey.N -> 'N' | _ -> yorn()   printfn "\nYour choice: %c" (yorn())
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...
#Forth
Forth
: flush ( -- ) \ discard pending input begin key? while key drop repeat ;   : y-or-n ( c-addr u -- f ) flush begin cr 2dup type key bl or \ note 1. dup [char] y = swap [char] n = over or \ note 2. if nip nip exit then drop again ;   \ Note 1. KEY BL OR returns a lowercase letter in ...
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.
#Python
Python
#!/usr/bin/env python import curses   def print_message(): stdscr.addstr('This is the message.\n')   stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1)   stdscr.addstr('CTRL+P for message or q to quit.\n') while True: c = stdscr.getch() if c == 16: print_message() elif c == ord('...
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...
#Eiffel
Eiffel
  class CONTINUOUS_KNAPSACK   create make   feature   make local tup: TUPLE [name: STRING; weight: REAL_64; price: REAL_64] do create tup create items.make_filled (tup, 1, 9) create sorted.make sorted.extend (-36.0 / 3.8) sorted.extend (-43.0 / 5.4) sorted.extend (-90.0 / 3.6) sorted.exte...
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...
#Swift
Swift
import Foundation   let dictPath: String   switch CommandLine.arguments.count { case 2: dictPath = CommandLine.arguments[1] case _: dictPath = "/usr/share/dict/words" }   let wordsData = FileManager.default.contents(atPath: dictPath)! let allWords = String(data: wordsData, encoding: .utf8)! let words = allWords.com...
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)
#Yorick
Yorick
func is_leap(y) { return ((y % 4 == 0) & (y % 100 != 0)) | (y % 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)
#zkl
zkl
Time.Date.isLeapYear(1988) //-->True T(1988,1989,1900,2000).apply(Time.Date.isLeapYear) //-->L(True,False,False,True)
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...
#Sidef
Sidef
define dirs = [[1,0], [0,-1], [-1,0], [0,1]] define size = 100   enum |White, Black| var plane = size.of { size.of (White) }   var (x, y) = ([size >> 1] * 2)... var dir = dirs.len.irand   var moves = 0 loop { (x >= 0) && (y >= 0) && (x < size) && (y < size) || break   given (plane[x][y]) { when (White) ...
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func WeekDay(Year, Month, Day); \Return day of week (0=Sun, 1=Mon ... 6=Sat) int Year, Month, Day; \works for years from 1583 onward [if Month<=2 then [Month:= Month+12; Year:= Year-1]; return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*...
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...
#EchoLisp
EchoLisp
  (lib 'struct) (lib 'sql) (lib 'hash)   (define H (make-hash)) (define T (make-table (struct goodies (name poids valeur qty)))) (define IDX (make-vector 0))     ;; convert to 0/1 PB ;; transorm vector [1 2 3 4 (n-max 3) 5 (n-max 2) 6 .. ] ;; into vector of repeated indices : [1 2 3 4 4 4 5 5 6 ... ]   (define (make-01...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Action.21
Action!
PROC PrintTable(INT ARRAY tab BYTE size) BYTE i   FOR i=0 TO size-1 DO PrintF("%I ",tab(i)) OD PutE() RETURN   PROC KnuthShuffle(INT ARRAY tab BYTE size) BYTE i,j INT tmp   i=size-1 WHILE i>0 DO j=Rand(i+1) tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==-1 OD RETURN   PROC Main() ...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Common_Lisp
Common Lisp
(defun keypress-check () (with-screen (scr :input-echoing nil :input-blocking nil :input-buffering nil :enable-function-keys t) (loop ;; Determine if a key has been pressed ... (if (key-pressed-p scr) ;; ... and store this in a variable. (let ((ch (get-char scr))) ;; ex...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#C.23
C#
string chr = string.Empty; if(Console.KeyAvailable) chr = Console.ReadKey().Key.ToString();
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#D
D
extern (C) { void _STI_conio(); void _STD_conio(); int kbhit(); int getch(); }   void main() { void flushKB() { while (kbhit()) getch(); }   _STI_conio();   flushKB();   _STD_conio(); }
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#DCL
DCL
$ wait 0::10  ! gives us 10 seconds to get keystrokes into the type-ahead buffer $ on control_y then $ goto clean $ set terminal /noecho $ loop: read /prompt="" /time=0 sys$command /error=clean buffer $ goto loop $ clean: $ set terminal /echo
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Delphi
Delphi
  program Flush_the_keyboard_buffer;   {$APPTYPE CONSOLE}   uses Winapi.Windows;   var StdIn: THandle;   begin StdIn := GetStdHandle(STD_INPUT_HANDLE); Writeln('Press any key you want, they will be erased:'); Sleep(5000); FlushConsoleInputBuffer(StdIn); Writeln('Now press any key you want, they will NOT b...
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...
#Common_Lisp
Common Lisp
(defun fill-knapsack (items max-volume max-weight) "Items is a list of lists of the form (name value weight volume) where weight and value are integers. max-volume and max-weight, also integers, are the maximum volume and weight of the knapsack. fill-knapsack returns a list of the form (total-value inventory total-vo...
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...
#Fortran
Fortran
  CHARACTER*120 FUNCTION REPLY(QUERY) !Obtain a text in reply. Concocted by R.N.McLean (whom God preserve), December MM. CHARACTER*(*) QUERY !The question. CHARACTER*120 TEXT !Alas, oh for proper strings. INTEGER MSG,KEYS,LSTNB !Let's hope everyone has the same type. COMMON /IOUNITS...
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.
#Racket
Racket
  #lang racket   (define-syntax-rule (with-raw body ...) (let ([saved #f]) (define (stty x) (system (~a "stty " x)) (void)) (dynamic-wind (λ() (set! saved (with-output-to-string (λ() (stty "-g")))) (stty "raw -echo opost")) (λ() body ...) (λ() (stty s...
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.
#Raku
Raku
my $TTY = open("/dev/tty"); my @INPUT;   sub log($mess) { print "$mess\r\n" }   INIT { shell "stty raw -echo min 1 time 1"; log "(raw mode)"; } END { shell "stty sane"; log "(sane mode)"; }   loop { push @INPUT, $TTY.getc unless @INPUT; given @INPUT.shift { when "q" | "\c4" { log "QUIT"; last; }   ...
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...
#Elixir
Elixir
defmodule KnapsackProblem do def select( max_weight, items ) do Enum.sort_by( items, fn {_name, weight, price} -> - price / weight end ) |> Enum.reduce( {max_weight, []}, &select_until/2 ) |> elem(1) |> Enum.reverse end   def task( items, max_weight ) do IO.puts "The robber takes the following...
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...
#Tcl
Tcl
proc letterHistogram {fileName} { # Initialize table (in case of short texts without every letter) for {set i 97} {$i<=122} {incr i} { set frequency([format %c $i]) 0 } # Iterate over characters in file set f [open $fileName] foreach c [split [read $f] ""] { # Count them if they'...
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...
#Swift
Swift
import Foundation   let WIDTH = 100 let HEIGHT = 100   struct Point { var x:Int var y:Int }   enum Direction: Int { case North = 0, East, West, South }   class Langton { let leftTurn = [Direction.West, Direction.North, Direction.South, Direction.East] let rightTurn = [Direction.East, Direction.South...
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...
#zkl
zkl
var [const] D=Time.Date; fcn lastDay(y,d){ [1..12].pump(List,'wrap(m){ // 12 months, closure for y & d [D.daysInMonth(y,m)..1,-1].pump(Void,'wrap(_d){ // work backwards D.weekDay(y,m,_d) : if (_==d) return(Void.Stop,D.toYMDString(y,m,_d)) }) }) } lastDay(2012,D.Friday).concat("\n")...
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...
#FreeBASIC
FreeBASIC
#define PesoMax 400 #define items 22 #define Tabu Chr(9)   Type Knapsack articulo As String*22 peso As Integer valor As Integer pieza As Integer End Type Dim item(1 To 22) As Knapsack => { _ ("map ", 9, 150, 0), ("compass ", 13, 35, 0), _ ("water ",...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Ada
Ada
generic type Element_Type is private; type Array_Type is array (Positive range <>) of Element_Type;   procedure Generic_Shuffle (List : in out Array_Type);
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Clojure
Clojure
$ lein trampoline run
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#D
D
extern (C) { void _STI_conio(); void _STD_conio(); int kbhit(); int getch(); }   void main() { _STI_conio();   char c; if (kbhit()) c = cast(char)getch();   _STD_conio(); }
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Delphi
Delphi
unit Unit1;   interface   uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs;   type TForm1 = class(TForm) procedure FormKeyPress(Sender: TObject; var Key: Char); private SavedPressedKey: Char; end;   var Form1: TForm1;   implementation   {$R *.dfm}   procedure T...
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#ERRE
ERRE
  !$KEY .......... REPEAT GET(K$) UNTIL K$="" ..........  
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Euphoria
Euphoria
while get_key()!=-1 do end while
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Get characters from the keyboard buffer until there are none left While Inkey <> "" : Wend Print "Keyboard buffer flushed" Sleep
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Go
Go
package main   import ( "log"   gc "code.google.com/p/goncurses" )   func main() { _, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() gc.FlushInput() }
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...
#D
D
void main() @safe /*@nogc*/ { import std.stdio, std.algorithm, std.typecons, std.conv;   static struct Bounty { int value; double weight, volume; }   immutable Bounty panacea = {3000, 0.3, 0.025}; immutable Bounty ichor = {1800, 0.2, 0.015}; immutable Bounty gold = {2500, ...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   While InKey <> "" : Wend '' flush keyboard buffer Print "Do you want to continue y/n : "; Dim answer As String   Do answer = LCase(Inkey) Loop Until answer = "y" OrElse answer = "n"   Print answer '' echo response to console If answer = "y" Then Print "OK, continuing" Else Print "OK, finishing...
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...
#FutureBasic
FutureBasic
void local fn DoDialog( ev as long ) CFStringRef key   select ( ev ) case _windowKeyDown cls key = fn EventCharacters select ( lcase(key) ) case @"y",@"n" printf @"You pressed the \"%@\" key",key DialogEventSetBool(YES)// we handled the event end select 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.
#REBOL
REBOL
rebol [ Title: "Keyboard Macros" URL: http://rosettacode.org/wiki/Keyboard_macros ]   ; Application specific keyboard bindings using REBOL VID ; dialect. Implementation of the "Averageman" calculator -- ; See http://www.atariarchives.org/bcc2/showpage.php?page=63 for details.   view layout [ style btn button ...
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...
#Erlang
Erlang
  -module( knapsack_problem_continuous ).   -export( [price_per_weight/1, select/2, task/0] ).   price_per_weight( Items ) -> [{Name, Weight, Price / Weight} || {Name, Weight, Price} <-Items].   select( Max_weight, Items ) -> {_Remains, Selected_items} = lists:foldr( fun select_until/2, {Max_weight, []}, lists:keysort...
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT words = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")   DICT letters create MODE {} COMPILE LOOP word=words letters=SPLIT (word,|":?:") LOOP letter=letters DICT letters ADD/QUIET/COUNT letter ENDLOOP ENDLOOP ENDCOMPILE DICT letters unload letter,size,cnt   index =DIGIT_INDEX ...
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...
#Tcl
Tcl
package require Tk   proc step {workarea} { global x y dir if {[lindex [$workarea get $x $y] 0]} { $workarea put black -to $x $y if {[incr dir] > 3} {set dir 0} } else { $workarea put white -to $x $y if {[incr dir -1] < 0} {set dir 3} } switch $dir { 0 {incr x} 1 {incr y} 2 {incr x -1} 3 {in...
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...
#Go
Go
package main   import "fmt"   type Item struct { name string weight, value, qty int }   var items = []Item{ {"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, ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Aime
Aime
void shuffle(list l) { integer i;   i = ~l; if (i) { i -= 1; while (i) { l.spin(i, drand(i)); i -= 1; } } }
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Elena
Elena
import extensions;   public program() { auto chr := emptyString; if (console.KeyAvailable) { chr := console.readChar() } }
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#ERRE
ERRE
  !$KEY ......... GET(K$) .........  
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Euphoria
Euphoria
integer key key = get_key() -- if key was not pressed get_key() returns -1
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Haskell
Haskell
import Control.Concurrent (threadDelay) import Control.Monad (when) import System.IO (hFlush, stdout) import System.Posix   -- If the file descriptor is associated with a terminal, then flush its input, -- otherwise do nothing. termFlush :: Fd -> IO () termFlush fd = do isTerm <- queryTerminal fd when isTerm $ disc...
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#i
i
procedure flushKB() while kbhit() do getch() # flush input end
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Icon_and_Unicon
Icon and Unicon
procedure flushKB() while kbhit() do getch() # flush input end
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...
#E
E
pragma.enable("accumulator")   /** A data type representing a bunch of stuff (or empty space). */ def makeQuantity(value, weight, volume, counts) { def quantity { to __printOn(out) { for name => n in counts { out.print(`$n $name `) } out.print(`(val=$value wt=$weight vol=$volume)`) } to valu...
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...
#GlovePIE
GlovePIE
if var.end=0 then var.end=0 debug="Press the Y key or the N key to continue:" endif if pressed(Key.Y)and var.end=0 then var.end=1 debug="You pressed the Y key." endif if pressed(Key.N)and var.end=0 then var.end=1 debug="You pressed the N key." endif
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...
#Go
Go
package main   import ( "log"   gc "code.google.com/p/goncurses" )   func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch 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.
#REXX
REXX
/*REXX program can re-define most keys (including F keys) on a PC keyboard.*/ trace off parse arg ! if !all(arg()) then exit if !cms then address ''   signal on halt signal on noValue signal on syntax   /*if not DOS, issue error. */ if \!dos then call er 23,',...
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...
#F.23
F#
  //Fill a knapsack optimally - Nigel Galloway: February 1st., 2015 let items = [("beef", 3.8, 36);("pork", 5.4, 43);("ham", 3.6, 90);("greaves", 2.4, 45);("flitch" , 4.0, 30);("brawn", 2.5, 56);("welt", 3.7, 67);("salami" , 3.0, 95);("sausage", 5.9, 98)] |> List.sortBy(fun(_,weight,value) -> float(-value)/...
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...
#TXR
TXR
@(do (defvar h (hash :equal-based))) @(repeat) @(coll :vars ())@\ @{letter /[A-Za-z]/}@(filter :upcase letter)@\ @(do (inc [h letter 0]))@\ @(end) @(end) @(do (dohash (key value h) (format t "~a: ~a\n" key value)))
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...
#TI-83_BASIC
TI-83 BASIC
PROGRAM:LANT :ClrDraw :0→N :47→A :31→B :90→Θ :Repeat getKey :If pxl-Test(B,A) :Then :Θ+90→Θ :Else :Θ-90→Θ :End :Pxl-Change(B,A) :A+cos(Θ°)→A :B+sin(Θ°)→B :N+1→N :End  
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...
#Groovy
Groovy
def totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() } def totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }   def knapsackBounded = { possibleItems -> def n = possibleItems.size() def m = (0..n).collect{ i -> (0..400).collect{ w -> []} } (1..400).each { w -> ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#ALGOL_68
ALGOL 68
PROC between = (INT a, b)INT : ( ENTIER (random * ABS (b-a+1) + (a<b|a|b)) );   PROC knuth shuffle = (REF[]INT a)VOID: ( FOR i FROM LWB a TO UPB a DO INT j = between(LWB a, UPB a); INT t = a[i]; a[i] := a[j]; a[j] := t OD );
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#F.23
F#
open System;   let chr = if Console.KeyAvailable then Console.ReadKey().Key.ToString() else String.Empty
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Forth
Forth
variable last-key : check key? if key last-key ! then ;
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim k As String Do k = Inkey Loop Until k <> ""   If Len(k) = 1 Then Print "The key pressed was "; k; " (ascii "; Asc(k); ")" Else Print "An extended key was pressed" End If   Sleep
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Julia
Julia
  using Gtk   function flush_keyboard() win = GtkWindow("", 1, 1) keyget(w, event) = Int32(0) signal_connect(keyget, win, "key-press-event") visible(win, false) sleep(0.25) end  
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { while (System.`in`.available() > 0) System.`in`.read() println("Goodbye!") }
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ feed keyboard Keyboard "abcd" \\ Work in Windows not in Linux (no Osk.exe exist) \\ no error return in linux Keyboard ! 'open virtual keyboard Wait 3000 \\ flush keyboard \\ we can use Do or Repeat (is the same) Repeat { a$=inkey$ ...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#11l
11l
L(ln) File(‘data.txt’).read_lines() I Float(ln.split(‘ ’, group_delimiters' 1B)[2]) > 6 print(ln)
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...
#EchoLisp
EchoLisp
  (require 'struct) (require 'hash) (require 'sql)   (define H null) ;; cache (define T (make-table (struct goodies (name valeur poids volume )))) (define-syntax-rule (name i) (table-xref T i 0)) (define-syntax-rule (valeur i) (table-xref T i 1)) (define-syntax-rule (poids i) (table-xref T i 2)) (define-syntax-rule (vo...
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...
#GW-BASIC_2
GW-BASIC
10 IF INKEY$<>"" THEN GOTO 10: REM flush the keyboard buffer 20 PRINT "Press Y or N to continue" 30 LET k$ = INKEY$ 40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GOTO 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.
#Ring
Ring
  load "guilib.ring"   app = new qApp { win = new qWidget() { setWindowTitle("Don't accept Spaces") move(100,100) resize(400,400) new qLineedit(win) { myfilter = new qAllEvents(win) { setkeypressevent("keypress()") ...
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...
#Forth
Forth
include lib/selcsort.4th \ use a tiny sorting algorithm   150 value left \ capacity in 1/10th kilo   create items \ list of items ," beef" 38 , 3600 , \ description, weight, price (cents) ," pork" 54 , 4300 , \ weight in...
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...
#Vala
Vala
  using Gee;   void main(string[] args){ string filename = args[1]; var file = FileStream.open(filename, "r");   var counter = new HashMap<char, int>();   string line = file.read_line(); while (line != null){ for (int x = 0; x < line.length; x++){ counter[line[x]] = counter[line[...
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...
#VBA
VBA
  Option Explicit   Sub Ant() Dim TablDatas(1 To 200, 1 To 256) As String, sDir As String, sFile As String, Str As String Dim ColA As Integer, LigA As Long, ColF As Integer, LigF As Long, i As Long, j As Integer, Num As Long Dim Top As Boolean, Left As Boolean, Bottom As Boolean, Right As Boolean   'init variables ...
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...
#Haskell
Haskell
inv = [("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), ("cream",11,70,1), ("camera",32,30,1), -- what to do if we end up taking one trouser? ("tshirt",24,15,2), ("trou...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#AppleScript
AppleScript
set n to 25   set array to {} repeat with i from 1 to n set end of array to i end repeat copy {array, array} to {unshuffled, shuffled} repeat with i from n to 1 by -1 set j to (((random number) * (i - 1)) as integer) + 1 set shuffled's item i to array's item j if j ≠ i's contents then set array's item j to array's ...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Gambas
Gambas
Public Sub Form_KeyPress()   'Requires a TextBox or similar on the Form to work Print Key.Text;   End
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Go
Go
package main   import ( "log" "time"   gc "code.google.com/p/goncurses" )   func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() gc.Cursor(0) s.Move(20, 0) s.Print("Key check in ") for i := 3; i >= 1; i-- { s.MovePrint(20,...
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#MiniScript
MiniScript
key.clear
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Nim
Nim
const TCIFLUSH: cint = 0 proc tcflush(fd, queue_selector: cint): cint {.header: "termios.h".}   discard tcflush(cint(getFileHandle(stdin)), TCIFLUSH)
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#8080_Assembly
8080 Assembly
FCB1: equ 5Ch ; FCB for first command line argument puts: equ 9 ; CP/M syscall to print a string fopen: equ 15 ; CP/M syscall to open a file fread: equ 20 ; CP/M syscall to read a block from a file dta: equ 80h ; Default disk transfer address org 100h lxi d,FCB1 ; Try to open the file given on the command line mvi ...
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...
#Eiffel
Eiffel
  class KNAPSACK   create make   feature   make do create panacea; panacea := [3000, 0.3, 0.025] create ichor; ichor := [1800, 0.2, 0.015] create gold; gold := [2500, 2.0, 0.002] create sack; sack := [0, 25.0, 0.25] find_solution end   feature {NONE}   panacea: TUPLE [value: INTEGER; ...
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...
#Haskell
Haskell
import System.IO   hFlushInput :: Handle -> IO () hFlushInput hdl = do r <- hReady hdl if r then do c <- hGetChar hdl hFlushInput hdl else return ()   yorn :: IO Char yorn = do c <- getChar if c == 'Y' || c == 'N' then return c else if c == 'y' then return 'Y' else if c == 'n' then return 'N' ...
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.
#Ruby
Ruby
Shoes.app do @info = para "NO KEY is PRESSED." keypress do |k| @info.replace "#{k.inspect} was PRESSED." end end
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...
#Fortran
Fortran
program KNAPSACK_CONTINUOUS implicit none   real, parameter :: maxweight = 15.0 real :: total_weight = 0, total_value = 0, frac integer :: i, j   type Item character(7) :: name real :: weight real :: value end type Item   type(Item) :: items(9), temp   items(1) = Item("beef", 3.8, 36.0) ...
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...
#VBA
VBA
  Public Sub LetterFrequency(fname) 'count number of letters in text file "fname" (ASCII-coded) 'note: we count all characters but print only the letter frequencies   Dim Freqs(255) As Long Dim abyte As Byte Dim ascal as Byte 'ascii code for lowercase a Dim ascau as Byte 'ascii code for uppercase a   'try to open the f...
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...
#Vim_Script
Vim Script
" return character under cursor function! CurrChar() return matchstr(getline('.'), '\%' . col('.') . 'c.') endfunction   " draw all-white grid (arguments are characters to use for white and black) function! LangtonClear(white, black) let l:bufname = 'langtons.ant' if bufexists(l:bufname) let l:winnum = bufw...
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...
#J
J
'names numbers'=:|:".;._2]0 :0 'map'; 9 150 1 'compass'; 13 35 1 'water'; 153 200 2 'sandwich'; 50 60 2 'glucose'; 15 60 2 'tin'; 68 ...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program knuthShuffle.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*******************...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Haskell
Haskell
import Control.Concurrent import Control.Monad import Data.Maybe import System.IO   main = do c <- newEmptyMVar hSetBuffering stdin NoBuffering forkIO $ do a <- getChar putMVar c a putStrLn $ "\nChar '" ++ [a] ++ "' read and stored in MVar" wait c where wait c = do ...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Icon_and_Unicon
Icon and Unicon
procedure main() delay(1000) # give user a chance to input if kbhit() then # test for input write("You entered ",x := getch()) # read w/o echo else # use getche for echo write("No input waiting") end
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Oforth
Oforth
import: console   System.Console flush
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Perl
Perl
use Term::ReadKey; ReadMode 'restore'; # Flush the keyboard and returns input stream to initial state # ReadMode 0; # Numerical equivalent of keyboard restore (move comment marker to use instead)   # A more complete example for use in keyboard handler programming. # We should also check we are being used ...
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Phix
Phix
while get_key()!=-1 do end while
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#PicoLisp
PicoLisp
(while (key 10))
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   BYTE FUNC FindFirstNonspace(CHAR ARRAY s BYTE start) WHILE start<=s(0) AND s(start)=32 DO start==+1 OD RETURN (start)   BYTE FUNC FindFirstSpace(CHAR ARRAY s BYTE start) WHILE start<=s(0) AND s(start)#32 DO start==+1 OD RETURN (start)   BYTE FUNC Found(CHAR ARRAY s REAL P...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Ada
Ada
-- Kernighans large earthquake problem with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Fixed; use Ada.Strings.Fixed; use Ada.Strings;   procedure Main is Inpt_File : File_Type; Space  : Natural; begin Open (File => Inpt_File, Mode => In_File, Name => "data.txt"); while not End_Of_File (Inpt_Fil...
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...
#Elixir
Elixir
defmodule Item do defstruct volume: 0.0, weight: 0.0, value: 0 def new(volume, weight, value) do  %__MODULE__{volume: volume, weight: weight, value: value} end end   defmodule Knapsack do def solve_unbounded(items, maximum) do {max_volume, max_weight} = {maximum.volume, maximum.weight} max_items = En...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() write("Response was ",getResponse("OK? (Y or N): ")) end   procedure getResponse(prompt) while kbhit() do getch() # flush input writes(prompt) repeat if map(answer := getch()) == ("y"|"n") then break return answer end
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...
#Inform_7
Inform 7
Qwantz is a room.   When play begins: say "A wizard has turned you into a whale. Is this awesome (Y/N)? "; if the player consents, say "Awesome!"; end the story.
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.
#Scala
Scala
import java.awt.event.{KeyAdapter, KeyEvent}   import javax.swing.{JFrame, JLabel, WindowConstants}     object KeyboardMacroDemo extends App { val directions = "<html><b>Ctrl-S</b> to show frame title<br>" + "<b>Ctrl-H</b> to hide it</html>"   new JFrame { add(new JLabel(directions))   addKeyListener(new Ke...
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...
#FreeBASIC
FreeBASIC
#define PesoMax 15.0 Type Knapsack articulo As String*7 peso As Double precio As Double End Type 'build item list Dim item(1 To 9) As Knapsack => { _ ("beef", 3.8, 36), ("pork", 5.4, 43), ("ham", 3.6, 90), _ ("greaves", 2.4, 45), ("flitch", 4.0, 30), ("brawn", 2.5, 56), _ ("welt", 3.7, 67),...