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/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.
| #Kotlin | Kotlin | // version 1.2.31
import javax.swing.JFrame
import javax.swing.JLabel
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
fun main(args: Array<String>) {
val directions = "<html><b>Ctrl-S</b> to show frame title<br>" +
"<b>Ctrl-H</b> to hide it</html>"
with (JFrame()) {
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
struct item { double w, v; const char *name; } items[] = {
{ 3.8, 36, "beef" },
{ 5.4, 43, "pork" },
{ 3.6, 90, "ham" },
{ 2.4, 45, "greaves" },
{ 4.0, 30, "flitch" },
{ 2.5, 56, "brawn" },
{ 3.7, 67, "welt" },
{ 3.0, 95, "salami" },
{ 5.9, 98, "sausage" },
};
int ite... |
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... | #Scala | Scala | import io.Source.fromFile
def letterFrequencies(filename: String) =
fromFile(filename).mkString groupBy (c => c) mapValues (_.length) |
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)
| #Visual_Basic | Visual Basic |
Public Function IsLeapYear1(ByVal theYear As Integer) As Boolean
'this function utilizes documented behaviour of the built-in DateSerial function
IsLeapYear1 = (VBA.Day(VBA.DateSerial(theYear, 2, 29)) = 29)
End Function
Public Function IsLeapYear2(ByVal theYear As Integer) As Boolean
'this function uses the well-kn... |
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)
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
For Each y In {1900, 1994, 1996, Date.Now.Year}
Console.WriteLine("{0} is {1}a leap year.", y, If(Date.IsLeapYear(y), String.Empty, "not "))
Next
End Sub
End Module |
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... | #Ring | Ring |
load "guilib.ring"
load "stdlib.ring"
new qapp
{
win1 = new qwidget() {
setwindowtitle("drawing using qpainter")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
... |
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... | #Swift | Swift |
import Foundation
func lastFridays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 2...13 {
let lastDayOfMonth = DateComponents(calendar: calendar,
year: year,
month: month,
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
int count;
} item_t;
item_t items[] = {
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", ... |
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... | #ALGOL_68 | ALGOL 68 | MODE BOUNTY = STRUCT(STRING name, INT value, weight, volume);
[]BOUNTY items = (
("panacea", 3000, 3, 25),
("ichor", 1800, 2, 15),
("gold", 2500, 20, 2)
);
BOUNTY sack := ("sack", 0, 250, 250);
OP * = ([]INT a,b)INT: ( # dot product operator #... |
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 ... | #VBA | VBA | Option Base 1
Function levenshtein(s1 As String, s2 As String) As Integer
Dim n As Integer: n = Len(s1) + 1
Dim m As Integer: m = Len(s2) + 1
Dim d() As Integer, i As Integer, j As Integer
ReDim d(n, m)
If n = 1 Then
levenshtein = m - 1
Exit Function
Else
If m = 1 Then
... |
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... | #D | D | import std.stdio: stdout, write, writefln;
extern (C) nothrow {
void _STI_conio();
void _STD_conio();
int kbhit();
int getch();
}
void main() {
_STI_conio();
write("Enter Y or N: ");
stdout.flush();
int c;
do {
while(!kbhit()) {}
c = getch();
// Visual... |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
\\ Scan statement exist from version 1
\\ We can make targets and use function keys, in console
\\ Scan track mouse click on targets and functions keys state
\\ when any of these selected then a call to a global module happen
\\ show$(hide$("&8%", "master",3), "code1", 1... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetOptions[EvaluationNotebook[], NotebookEventActions -> {{"KeyDown", "t"} :> Print["You pressed \"t\""]}] |
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... | #C.23 | C# | using System; //4790@3.6
class Program
{
static void Main()
{
Console.WriteLine(knapSack(15) + "\n");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 1000; i > 0; i--) knapSack(15);
Console.Write(sw.Elapsed); Console.Read(); // 0.60 µs
}
static string... |
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... | #Scheme | Scheme | (use-modules (ice-9 format))
(define (char-freq port table)
(if
(eof-object? (peek-char port))
table
(char-freq port (add-char (read-char port) table))))
(define (add-char char table)
(cond
((null? table) (list (list char 1)))
((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr ta... |
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)
| #Vlang | Vlang | fn is_leap(year int) bool {
return year %400 ==0 || (year%4 ==0 && year%100!=0)
}
fn main() {
for y in 1950..2012 {
if is_leap(y) {
println(y)
}
}
}
|
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)
| #WDTE | WDTE | let str => import 'strings';
let multiple of n => == (% n of) 0;
let leap year => str.format '{} is{} a leap year.' year (switch year {
multiple 400 => '';
multiple 100 => ' not';
multiple 4 => '';
default => ' not';
}) -- io.writeln io.stdout; |
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... | #Ruby | Ruby | class Ant
class OutOfBoundsException < StandardError; end
class Plane
def initialize(x, y)
@size_x, @size_y = x, y
@cells = Array.new(y) {Array.new(x, :white)}
end
def white?(px, py)
@cells[py][px] == :white
end
def toggle_colour(px, py)
@cells[py][px] = (white?(p... |
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... | #Tcl | Tcl | package require Tcl 8.5
set year [lindex $argv 0]
foreach dm {02/1 03/1 04/1 05/1 06/1 07/1 08/1 09/1 10/1 11/1 12/1 12/32} {
# The [clock scan] code is unhealthily clever; use it for our own evil purposes
set t [clock scan "last friday" -base [clock scan $dm/$year -gmt 1] -gmt 1]
# Print the interesting pa... |
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... | #C.23 | C# | using System; // 4790@3.6
class program
{
static void Main()
{
knapSack(40);
var sw = System.Diagnostics.Stopwatch.StartNew();
Console.Write(knapSack(400) + "\n" + sw.Elapsed); // 51 µs
Console.Read();
}
static string knapSack(uint w1)
{
init(); change();
... |
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... | #AutoHotkey | AutoHotkey | Item = Panacea,Ichor,Gold
Value = 3000,1800,2500
Weight= 3,2,20 ; *10
Volume= 25,15,2 ; *1000
StringSplit I, Item, `, ; Put input in arrays
StringSplit W, Weight,`,
StringSplit $, Value, `,
StringSplit V, Volume,`,
SetFormat Float, 0.3
W := 250, V := 25... |
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 ... | #VBScript | VBScript | ' Levenshtein distance - 23/04/2020
Function Min(a,b)
If a < b then Min = a : Else Min = b
End Function 'Min
Function Levenshtein(s1, s2)
Dim d(), i, j, n1, n2, d1, d2, d3
n1 = Len(s1) + 1
n2 = Len(s2) + 1
ReDim d(n1, n2)
If n1 = 1 Then
Levenshtein = n2 - 1
Exit Function
... |
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... | #Delphi | Delphi |
program Obtain_a_Y_or_N_response;
{$APPTYPE CONSOLE}
uses
System.Console;
function GetKey(acepted: string): Char;
var
key: Char;
begin
while True do
begin
if Console.KeyAvailable then
begin
key := UpCase(Console.ReadKey().KeyChar);
if pos(key, acepted) > 0 then
exit(key);
... |
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.
| #Nim | Nim | import tables
import gintro/[glib, gobject, gio]
import gintro/gtk except Table
import gintro/gdk except Window
type
MacroProc = proc(app: App)
MacroTable = Table[int, MacroProc] # Mapping key values -> procedures.
App = ref object of Application
dispatchTable: MacroTable
label: Label
#--------... |
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.
| #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
Label
Window = {QTk.build td(label(text:"Hello" handle:Label))}
in
{Window bind(event:"<Control-x><Control-s>"
action:proc {$}
{Label set(text:"This is not Emacs.")}
end
)}
{Window bind(event:"<Control-x><Control-c>"
... |
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... | #C.2B.2B | C++ | #include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
double result;
double capacity = 15;
int NumberOfItems;
int number;
struct items
{
char name[32];
double weight;
double price;
double m;
} item[256];
bool cmp(items a,items b)
{
return a.price/a.weight > b.price/b.w... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: charHash is hash [char] integer;
const proc: main is func
local
var charHash: numberOfChars is charHash.EMPTY_HASH;
var char: ch is ' ';
begin
ch := getc(IN);
while ch <> EOF do
if ch in numberOfChars then
incr(numberOfChars[ch]);
else
... |
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)
| #WebAssembly | WebAssembly | (module
;; function isLeapYear: returns 1 if its argument (e.g. 2004) is a leap year, 0 otherwise.
;; Returns year%4==0 and (year%100!=0 or year%400==0)
(func $isLeapYear (param $year i32) (result i32)
(i32.and
(i32.eqz (i32.rem_u (get_local $year) (i32.const 4))) ;; year%4 == 0
(i32.or
(... |
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)
| #Wortel | Wortel | @let {
isLeapYear !?{\~%%1H \~%%4H \~%%4}
!-isLeapYear @range[1900 2000]
} |
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... | #Run_BASIC | Run BASIC | dim plane(100,100)
x = 50: y = 50: minY = 100
while (x>0) and (x<100) and (y>0) and (y<100)
if plane(x,y) then
nxt = nxt - 1
if nxt < 1 then nxt = 4
else
nxt = nxt + 1
if nxt > 4 then nxt = 1
end if
x = x + (nxt = 2) - (nxt = 4)
y = y + (nxt = 3) - (nxt = 1)
plane(x,y) = (plane... |
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... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
year=2012
LOOP month=1,12
LOOP day=31,22,-1
dayofweek=DATE (number,day,month,year,nummer)
IF (dayofweek==5) THEN
PRINT year,"-",month,"-",day
EXIT
ENDIF
ENDLOOP
ENDLOOP
|
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... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <memory>
#include <sys/time.h>
using std::cout;
using std::endl;
class StopTimer
{
public:
StopTimer(): begin_(getUsec()) {}
unsigned long long getTime() const { return getUsec() - begin_; }
private:
static unsigned... |
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... | #11l | 11l | F knuth_shuffle(&x)
L(i) (x.len - 1 .< 0).step(-1)
V j = random:(0..i)
swap(&x[i], &x[j])
V x = Array(0..9)
knuth_shuffle(&x)
print(‘shuffled: ’x) |
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.
| #6502_Assembly | 6502 Assembly | define sysLastKey $ff
main:
jsr getKeyPress
;put the rest of your program here.
jsr delay
jmp main
getKeyPress:
lda $ff
sta $00
rts
delay:
nop
nop
dex
bne delay
rts |
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.
| #6502_Assembly | 6502 Assembly | lda #$00
sta $FF |
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... | #Bracmat | Bracmat | (knapsack=
( things
= (panacea.3000.3/10.25/1000)
(ichor.1800.2/10.15/1000)
(gold.2500.2.2/1000)
)
& 0:?maxvalue
& :?sack
& ( add
= cumwght
cumvol
cumvalue
cumsack
name
wght
val
vol
tings
n
ncumwght
ncumval... |
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 ... | #Visual_Basic | Visual Basic | Function min(x As Integer, y As Integer) As Integer
If x < y Then
min = x
Else
min = y
End If
End Function
Function levenshtein(s As String, t As String) As Integer
Dim ls As Integer, lt As Integer
Dim i As Integer, j As Integer, cost As Integer
' degenerate cases
ls = Len(s)
l... |
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... | #EGL | EGL | handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}
ui Div { };
const KEY_N int = 78;
const KEY_Y int = 89;
function start()
document.onKeyDown = d_onKeyDown;
end
function d_onKeyDown(e Event in)
case (e.ch)
when (KEY_N)
ui.inne... |
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.
| #Perl | Perl | use strict;
use warnings;
use Term::ReadKey;
ReadMode 4; # change to raw input mode
sub logger { my($message) = @_; print "$message\n" }
while (1) {
if (my $c = ReadKey 0) { # read a single character
if ($c eq 'q') { logger "QUIT"; last }
elsif ($c =~ /\n|\r/) { logger "CR" }
elsif ($c... |
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... | #Clojure | Clojure |
; Solve Continuous Knapsack Problem
; Nicolas Modrzyk
; January 2015
(def maxW 15.0)
(def 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]})
(defn rob [items maxW]
(l... |
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... | #SenseTalk | SenseTalk |
put file "~/Documents/addresses.csv" into source
repeat with each character of source
if it is a controlChar then next repeat -- skip control characters
if it is a lowercase then put "." after it -- make keys distinct
add 1 to counts.(it)
end repeat
repeat with each (theChar, count) in counts
put char 1 of th... |
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)
| #Wren | Wren | var isLeapYear = Fn.new { |y|
return ((y % 4 == 0) && (y % 100!= 0)) || (y % 400 == 0)
}
System.print("Leap years between 1900 and 2020 inclusive:")
var c = 0
for (i in 1900..2020) {
if (isLeapYear.call(i)) {
System.write("%(i) ")
c = c + 1
if (c % 15 == 0) System.print()
}
} |
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... | #Rust | Rust | struct Ant {
x: usize,
y: usize,
dir: Direction
}
#[derive(Clone,Copy)]
enum Direction {
North,
East,
South,
West
}
use Direction::*;
impl Ant {
fn mv(&mut self, vec: &mut Vec<Vec<u8>>) {
let pointer = &mut vec[self.y][self.x];
//change direction
match *poin... |
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... | #UNIX_Shell | UNIX Shell | #!/bin/sh
if [ -z $1 ]; then exit 1; fi
# weed out multiple erros due to bad year
ncal 1 $1 > /dev/null && \
for m in 01 02 03 04 05 06 07 08 09 10 11 12; do
echo $1-$m-`ncal $m $1 | grep Fr | sed 's/.* \([0-9]\)/\1/'`
done |
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... | #Clojure | Clojure | (ns knapsack
(:gen-class))
(def groupeditems [
["map", 9, 150, 1]
["compass", 13, 35, 1]
["water", 153, 200, 3]
["sandwich", 50, 60, 2]
["glucose", 15, 60, 2]
["tin", 68, 45, 3]
["ban... |
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... | #360_Assembly | 360 Assembly |
* Knuth shuffle 02/11/2015
KNUTHSH CSECT
USING KNUTHSH,R15
LA R6,1 i=1
LOOPI1 C R6,=A(CARDS) do i=1 to cards
BH ELOOPI1
STC R6,PACK(R6) pack(i)=i
LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI... |
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.
| #Action.21 | Action! | Proc Main()
Byte KEY,k=764
KEY=K
Return |
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.
| #Ada | Ada | Ch : Character;
Available : Boolean;
Ada.Text_IO.Get_Immediate (Ch, Available); |
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.
| #8086_Assembly | 8086 Assembly | mov ax,0C00h ;equivalent of "mov ah,0Ch mov al,0"
int 21h |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program keyboardInput64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstant... |
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.
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
PrintE("Program is halted for 200 frames.")
PrintE("Type character to fill the buffer.")
Wait(200)
PutE()
DO
IF CH=$FF THEN
Pr... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
double value;
double weight;
double volume;
} item_t;
item_t items[] = {
{"panacea", 3000.0, 0.3, 0.025},
{"ichor", 1800.0, 0.2, 0.015},
{"gold", 2500.0, 2.0, 0.002},
};
int n = sizeof (items) / sizeof (item_t);
i... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Function LevenshteinDistance(ByVal String1 As String, ByVal String2 As String) As Integer
Dim Matrix(String1.Length, String2.Length) As Integer
Dim Key As Integer
For Key = 0 To String1.Length
Matrix(Key, 0) = Key
Next
For Key = 0 To String2.Length
Matrix... |
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... | #Elm | Elm | import Char
import Graphics.Element exposing (Element, empty, show)
import Keyboard
view : Int -> Element
view keyCode =
let
char =
Char.fromCode keyCode
showChar =
toString >> ((++) "The last (y/n) key pressed was: ") >> show
in
case char of
'n' ->
showChar char
... |
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.
| #Phix | Phix | include pGUI.e
function C_Keyed(Ihandle /*ih*/, atom /*c*/)
-- (Note without K_c below this does not respond to 'c', just 'C')
?"you pressed C"
return IUP_DEFAULT
end function
procedure F2_keyed()
?"you pressed F2"
end procedure
function key_cb(Ihandle /*ih*/, atom c)
if c=K_F2 then F2_keyed()
... |
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... | #Common_Lisp | Common Lisp | (defstruct item
(name nil :type string)
(weight nil :type real)
(price nil :type real))
(defun price-per-weight (item)
(/ (item-price item) (item-weight item)))
(defun knapsack (items total-weight)
(loop with sorted = (sort items #'> :key #'price-per-weight)
while (plusp total-weight)
for ... |
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... | #Sidef | Sidef | func letter_frequency(File file) {
file.read.chars.grep{.match(/[[:alpha:]]/)} \
.group_by {|letter| letter.downcase} \
.map_val {|_, val| val.len} \
.sort_by {|_, val| -val}
}
var top = letter_frequency(File(__FILE__))
top.each{|pair| say "#{pair[0]}: #{pair[1]}"} |
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)
| #X86_Assembly | X86 Assembly | align 16
; Input year as signed dword in EAX
IsLeapYear:
test eax,11b
jz .4
retn ; 75% : ZF=0, not a leap year
.4:
mov ecx,100
cdq
idiv ecx
test edx,edx
jz .100
cmp edx,edx
retn ; 24% : ZF=1, leap year
.100:
test eax,11b
retn ; 1% : ZF=?, leap year if EAX%400=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... | #Scala | Scala | class Langton(matrix:Array[Array[Char]], ant:Ant) {
import Langton._
val rows=matrix.size
val cols=matrix(0).size
def isValid = 0 <= ant.row && ant.row < cols && 0 <= ant.col && ant.col < rows
def isBlack=matrix(ant.row)(ant.col)==BLACK
def changeColor(c:Char)={matrix(ant.row)(ant.col)=c; matrix}
def... |
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... | #Visual_FoxPro | Visual FoxPro |
*!* OOP implementaion
LOCAL lnYear As Integer, oCalc As fricalc
CLEAR
lnYear = VAL(INPUTBOX("Year", "Year"))
oCalc = NEWOBJECT("fricalc")
oCalc.LastFriday(lnYear)
DEFINE CLASS fricalc As Session
DataSession = 2 && Private
PROCEDURE Init
*!* These date settings are private to this class
SET DATE YMD
SET CENTURY ON... |
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... | #Common_Lisp | Common Lisp | ;;; memoize
(defmacro mm-set (p v) `(if ,p ,p (setf ,p ,v)))
(defun knapsack (max-weight items)
(let ((cache (make-array (list (1+ max-weight) (1+ (length items)))
:initial-element nil)))
(labels ((knapsack1 (spc items)
(if (not items) (return-from knapsack1 (list 0 0 '())))
(mm-set (aref cache spc (... |
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... | #6502_Assembly | 6502 Assembly | define sysRandom $fe
define tempMask $ff
define range $00
define tempX $01
define tempY $02
define tempRandIndex $03
define temp $04
CreateIdentityTable:
txa
sta $0200,x
sta $1000,x
inx
bne CreateIdentityTable
;creates a sorted array from 0-255 starting at addr $1000
;also creates another one at $02... |
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.
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
DEF-MAIN(argv, argc)
BREAK-ON
SET(c,0)
WHILE (1)
COND( KEY-PRESSED? )
SCAN-CODE(c)
BREAK-IF ( c ) IS-ESCAPE
CEND
PRNL( "CODE = ", c )
WEND
PRNL( "Last key pressed: ", c )
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.
| #ARM_Assembly | ARM Assembly |
/* Programme assembleur ARM Raspberry */
/* Assembleur ARM Raspberry : Vincent Leboulou */
/* Blog : http://assembleurarmpi.blogspot.fr/ */
/* modèle B 512MO */
/************************************/
/* Constantes */
/************************************/
.equ STDIN, 0 @ Linux in... |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Flushtest is
use Text_IO;
begin
Put_Line ("Type anything for 2 s");
delay 2.0;
Flush_Input:
declare
Ch : Character;
More : Boolean;
begin
loop
Get_Immediate (Ch, More);
exit when not More;
end loop;
end Flush_Input;
New_Line;
... |
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.
| #ARM_Assembly | ARM Assembly |
/* Programme assembleur ARM Raspberry */
/* modèle B 512MO */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/************************************... |
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... | #C.23 | C# | /* Items Value Weight Volume
a 30 3 25
b 18 2 15
c 25 20 2
<=250 <=250 */
using System;
class Program
{
static void Main()
{
uint[] r = items1();
Console.WriteLine(r[0] + " v " + r[1] ... |
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 ... | #Wren | Wren | var levenshtein = Fn.new { |s, t|
var ls = s.count
var lt = t.count
var d = List.filled(ls + 1, null)
for (i in 0..ls) {
d[i] = List.filled(lt + 1, 0)
d[i][0] = i
}
for (j in 0..lt) d[0][j] = j
for (j in 1..lt) {
for (i in 1..ls) {
if (s[i-1] == t[j-1]) {
... |
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... | #ERRE | ERRE |
!$KEY
................
! flush the keyboard buffer
! --------------------------------
! you can use POKE(198,0) in C-64
! ERRE version
! --------------------------------
REPEAT
GET(K$)
UNTIL K$=""
PRINT("Press Y or N to continue")
REPEAT
GET(K$)
UNTIL INSTR("YyNn",K$)<>0
!
! with C-64 you must write a line lik... |
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.
| #PicoLisp | PicoLisp | (load "@lib/led.l" "@lib/term.l")
(fkey *XtF1
(prinl "Initialized value to " (setq *Number 1)) )
(fkey *XtUp
(prinl "Incremented to " (inc '*Number)) )
(fkey *XtDown
(prinl "Decremented to " (dec '*Number)) )
(fkey *XtHome
(prinl "Current value is " *Number) ) |
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... | #D | D | import std.stdio, std.algorithm, std.string;
struct Item {
string name;
real amount, value;
@property real valuePerKG() @safe const pure nothrow @nogc {
return value / amount;
}
string toString() const pure /*nothrow*/ @safe {
return format("%10s %7.2f %7.2f %7.2f",
... |
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... | #SIMPOL | SIMPOL | constant iBUFSIZE 500
function main(string filename)
fsfileinputstream fpi
integer e, i, aval, zval, cval
string s, buf, c
array chars
e = 0
fpi =@ fsfileinputstream.new(filename, error=e)
if fpi =@= .nul
s = "Error, file """ + filename + """ not found{d}{a}"
else
chars =@ array.new()
av... |
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)
| #XLISP | XLISP | (DEFUN LEAP-YEARP (YEAR)
(AND (= (MOD YEAR 4) 0) (OR (/= (MOD YEAR 100) 0) (= (MOD YEAR 400) 0))))
; Test the function
(DISPLAY (MAPCAR LEAP-YEARP '(1600 1640 1800 1928 1979 1990 2000 2004 2005 2016))) |
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... | #Scilab | Scilab | grid_size=100; //side length of the square grid
ant_pos=round([grid_size/2 grid_size/2]); //ant's initial position at center of grid
head_direction='W'; //ant's initial direction can be either
//'N' north, 'S' south, 'E' ... |
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... | #Vlang | Vlang | import time
import os
fn main() {
mut year := 0
mut t := time.now()
year = os.input("Please select a year: ").int()
println("Last Fridays of each month of $year")
println("==================================")
for i in 1..13 {
mut j := time.month_days[i-1]
if i == 2 {
... |
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... | #Crystal | Crystal | record Item, name : String, weight : Int32, value : Int32, count : Int32
record Selection, mask : Array(Int32), cur_index : Int32, total_value : Int32
class Knapsack
@threshold_value = 0
@threshold_choice : Selection?
getter checked_nodes = 0
def knapsack_step(taken, items, remaining_weight)
if taken.... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program knuthshuffle64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstante... |
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.
| #AutoHotkey | AutoHotkey | ; Input [, OutputVar, Options, EndKeys, MatchList]
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds |
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.
| #AWK | AWK |
# syntax: TAWK -f KEYBOARD_INPUT_KEYPRESS_CHECK.AWK
BEGIN {
arr["\b"] = "BACKSPACE"
arr["\t"] = "TAB"
arr["\x0D"] = "ENTER"
printf("%s Press any key; ESC to exit\n",ctime())
while (1) {
nkeys++
key = getkey()
if (key in arr) { key = arr[key] }
space = ((length(key) > 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.
| #AWK | AWK |
# syntax: TAWK -f KEYBOARD_INPUT_FLUSH_THE_KEYBOARD_BUFFER.AWK
BEGIN {
while (kbhit()) {
getkey()
}
exit(0)
}
|
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.
| #Axe | Axe | While getKey(0)
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... | #C_sharp | C_sharp | /*Knapsack
This model finds the integer optimal packing of a knapsack
Nigel_Galloway
January 29th., 2012
*/
using Microsoft.SolverFoundation.Services;
namespace KnapU
{
class Item {
public string Name {get; set;}
public int Value {get; set;}
public double Weight {get; set;}
... |
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 ... | #zkl | zkl | fcn levenshtein(s1,s2){
sz2,costs:=s2.len() + 1, List.createLong(sz2,0); // -->zero filled List
foreach i in (s1.len() + 1){
lastValue:=i;
foreach j in (sz2){
if (i==0) costs[j]=j;
else if (j>0){
newValue:=costs[j-1];
if (s1[i-1]!=s2[j-1])
newValue=newValue.min(lastValue,... |
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... | #Euphoria | Euphoria | integer key
puts(1,"Your answer? (Y/N)\n")
while get_key()!=-1 do
end while
while 1 do
key = get_key()
if key!=-1 and (key = 'Y' or key = 'y' or key = 'N' or key = 'n') then
exit
end if
end while
printf(1,"Your response was %s\n",key) |
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.
| #PureBasic | PureBasic | #Win = 0
#Demo1 = 0
#Demo2 = 1
If OpenWindow(#Win,50,50,200,60,"PureBasic",#PB_Window_SystemMenu)
;
AddKeyboardShortcut(#Win,#PB_Shortcut_F1, #Demo1)
AddKeyboardShortcut(#Win,#PB_Shortcut_F|#PB_Shortcut_Alt, #Demo2)
;
Repeat
WEvent = WaitWindowEvent()
Select WEvent
Case #PB_Event_Menu
... |
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... | #EchoLisp | EchoLisp |
(lib 'struct)
(lib 'sql) ;; for table
(define T (make-table (struct meal (name poids price))))
(define meals
'((🐂-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 ... |
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... | #Smalltalk | Smalltalk | bagOfChars := 'someFile' asFilename contentsAsString asBag.
bag sortedCounts
select:[:assoc | assoc value isLetter ]
thenDo:[:assoc | assoc printCR]. |
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)
| #XPL0 | XPL0 | func LeapYear(Y); \Return 'true' if Y is a leap year
int Y;
[if rem(Y/100)=0 then return rem(Y/400)=0;
return rem(Y/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)
| #Yabasic | Yabasic | sub leapyear(year)
if mod(year, 4) <> 0 then return false : fi
if mod(year, 100) = 0 and mod(year, 400) <> 0 then return false : fi
return TRUE
end sub
for year = 1800 to 2900 step 100
print year;
if leapyear(year) then print " is a leap year" else print " is not a leap year" : fi
next year
print
... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum;
const proc: main is func
local
const integer: width is 75;
const integer: height is 52;
var array array boolean: m is height times width times FALSE;
var direction: dir is UP;
var integer: x is width di... |
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... | #Wren | Wren | import "os" for Process
import "/date" for Date
var args = Process.arguments
if (args.count != 1) {
Fiber.abort("Please pass just the year to be processed.")
}
var year = Num.fromString(args[0])
System.print("The dates of the last Fridays in the month for %(year) are:")
Date.default = Date.isoDate
for (m in 1..... |
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... | #D | D | import std.stdio, std.typecons, std.functional;
immutable struct Item {
string name;
int weight, value, quantity;
}
immutable Item[] items = [
{"map", 9, 150, 1}, {"compass", 13, 35, 1},
{"water", 153, 200, 3}, {"sandwich", 50, 60, 2},
{"glucose", 15, 60, 2}, {"t... |
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... | #ACL2 | ACL2 | :set-state-ok t
(defun array-swap (name array i j)
(let ((ai (aref1 name array i))
(aj (aref1 name array j)))
(aset1 name
(aset1 name array j ai)
i aj)))
(defun shuffle-r (name array m state)
(if (zp m)
(mv array state)
(mv-let (i state)
(r... |
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.
| #Axe | Axe | getKey→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.
| #BASIC | BASIC | K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(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.
| #C | C | #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.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 | ECHO);
tcsetattr(STDIN_FILENO... |
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.
| #Bash | Bash | while read -t 0.01; do
true
done |
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.
| #BASIC | BASIC | 10 IF PEEK (49152) > 127 THEN C = PEEK (49168): GOTO 10 |
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.
| #BBC_BASIC | BBC BASIC | *FX 15,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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
// Get a chance to make stdin input buffer dirty.
//
char text[256];
getchar();
// This DOES NOT WORK properly on all modern systems including Linux & W10.
// Obsolete, don't use this. BTW, there is no fpurge in MSVC l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.