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/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... | #VBScript | VBScript |
filepath = "SPECIFY FILE PATH HERE"
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objdict = CreateObject("Scripting.Dictionary")
Set objfile = objfso.OpenTextFile(filepath,1)
txt = objfile.ReadAll
For i = 1 To Len(txt)
char = Mid(txt,i,1)
If objdict.Exists(char) Then
objdict.Item(char) = objdi... |
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... | #Whitespace | Whitespace |
... |
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... | #Java | Java | package hu.pj.alg.test;
import hu.pj.alg.BoundedKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class BoundedKnapsackForTourists {
public BoundedKnapsackForTourists() {
BoundedKnapsack bok = new BoundedKnapsack(400); // 400 dkg = 400 dag = 4 kg
// making the lis... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #6502_Assembly | 6502 Assembly | JMP PrintChar ; jump to the label "PrintChar" where a routine to print a letter to the screen is located. |
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... | #Arturo | Arturo | knuth: function [arr][
if 0=size arr -> return []
loop ((size arr)-1)..0 'i [
j: random 0 i
tmp: arr\[i]
set arr i arr\[j]
set arr j tmp
]
return arr
]
print knuth []
print knuth [10]
print knuth [10 20]
print knuth [10 20 30] |
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.
| #Java | Java | import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
Test() {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
}
... |
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.
| #JavaScript | JavaScript |
let thePressedKey;
function handleKey(evt) {
thePressedKey = evt;
console.log(thePressedKey);
}
document.addEventListener('keydown', handleKey);
|
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.
| #PowerShell | PowerShell | while ($Host.UI.RawUI.KeyAvailable) {
$Host.UI.RawUI.ReadKey() | Out-Null
} |
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.
| #PureBasic | PureBasic | While Inkey(): Wend |
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.
| #Python | Python | def flush_input():
try:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch()
except ImportError:
import sys, termios
termios.tcflush(sys.stdin, termios.TCIOFLUSH)
|
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... | #ALGOL_68 | ALGOL 68 | IF FILE input file;
STRING file name = "data.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on log... |
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... | #Factor | Factor | USING: accessors combinators kernel locals math math.order
math.vectors sequences sequences.product combinators.short-circuit ;
IN: knapsack
CONSTANT: values { 3000 1800 2500 }
CONSTANT: weights { 0.3 0.2 2.0 }
CONSTANT: volumes { 0.025 0.015 0.002 }
CONSTANT: max-weight 25.0
CONSTANT: max-volume 0.25
TUPLE: boun... |
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... | #JavaScript | JavaScript | const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
var wait_key = async function() {
return await new Promise(function(resolve,reject) {
var key_listen = function(str,key) {
process.stdin.removeListener('keypress', key_listen);
resolve(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.
| #Tcl | Tcl | package require Tk
# Show off some emacs-like bindings...
pack [label .l -text "C-x C-s to save, C-x C-c to quit"]
focus .
bind . <Control-x><Control-s> {
tk_messageBox -message "We would save here"
}
bind . <Control-x><Control-c> {exit} |
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.
| #Vedit_macro_language | Vedit macro language | // Configure a key to access menu item.
// The menu item may then contain the commands directly, or it may call a macro from disk.
// This has the advantage that the key binding is shown in the menu.
Key_Add("Shft-F6","[MENU]TV", OK)
// Configure a key to perform visual mode edit operations (similar to recorded key ... |
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... | #GNU_APL | GNU APL | ⍝ Data
Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage'
Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9
Prices←36 43 90 45 30 56 67 95 98
⍝ Solution
Order←⍒Worth←Prices÷Weights ⍝ 'Worth' is each item value for 1 kg.
diff←{¯1↓(⍵,0)-0,⍵} ⍝ 'diff' betw... |
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... | #Vedit_macro_language | Vedit macro language | File_Open("c:\txt\a_text_file.txt")
Update()
for (#1='A'; #1<='Z'; #1++) {
Out_Reg(103) Char_Dump(#1,NOCR) Out_Reg(CLEAR)
#2 = Search(@103, BEGIN+ALL+NOERR)
Message(@103) Num_Type(#2)
} |
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... | #Wren | Wren | var width = 75
var height = 52
var maxSteps = 12000
var up = 0
var right = 1
var down = 2
var left = 3
var direction = [up, right, down, left]
var white = 0
var black = 1
var x = (width/2).floor
var y = (height/2).floor
var m = List.filled(height, null)
for (i in 0...height) m[i] = List.filled(width, 0)
var... |
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... | #JavaScript | JavaScript | <html><head><title></title></head><body></body></html>
<script type="text/javascript">
var data= [
{name: 'map', weight: 9, value:150, pieces:1},
{name: 'compass', weight: 13, value: 35, pieces:1},
{name: 'water', weight:153, value:200, pieces:2},
{name: 'sa... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #68000_Assembly | 68000 Assembly | In addition, for nearby subroutines, BSR can be used in place of JSR to save data. There is also BRA (branch always) for unconditional local jumping, which the original 6502 didn't have.
|
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #8086_Assembly | 8086 Assembly | JCXZ bar
foo:
LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo
bar: |
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... | #AutoHotkey | AutoHotkey | MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
shuffle(list) { ; shuffle comma separated list, converted to array
StringSplit a, list, `, ; make array (length = a0)
Loop % a0-1 {
Random i, A_Index, a0 ; swap item 1,2... with ... |
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.
| #Julia | Julia | using Gtk
function keypresswindow()
tcount = 0
txt = "Press a Key"
win = GtkWindow("Keypress Test", 500, 30) |> (GtkFrame() |> ((vbox = GtkBox(:v)) |> (lab = GtkLabel(txt))))
function keycall(w, event)
ch = Char(event.keyval)
tcount += 1
set_gtk_property!(lab, :label, "You have... |
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.
| #Kotlin | Kotlin | // version 1.1
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities
class Test : JFrame() {
init {
println("Press any key to see its code or 'enter' to quit\n")
addKeyListener(object : KeyAdapter() {
override fun ... |
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.
| #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 sav... |
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.
| #Raku | Raku | use Term::termios;
constant $saved = Term::termios.new( :fd($*IN.native-descriptor) ).getattr;
constant $termios = Term::termios.new( :fd($*IN.native-descriptor) ).getattr;
# set some modified input flags
$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);
$termios.unset_lflags(< ECHO ICANON IEXTEN>);
$termios.set... |
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... | #Amazing_Hopper | Amazing Hopper |
/* Kernighans large earthquake problem. */
#include <flow.h>
#include <flow-flow.h>
#define MAX_LINE 1000
DEF-MAIN(argv,argc)
MSET(fd, Event )
TOK-INIT
OPEN-INPUT("datos.txt")(fd)
COND( IS-NOT-FILE-ERROR? )
TOK-SEP( " " ), TOK(3)
WHILE( NOT( EOF(fd) ) )
LET( Event := USING(MAX_L... |
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... | #Forth | Forth | \ : value ; immediate
: weight cell+ ;
: volume 2 cells + ;
: number 3 cells + ;
\ item value weight volume number
create panacea 30 , 3 , 25 , 0 ,
create ichor 18 , 2 , 15 , 0 ,
create gold 25 , 20 , 2 , 0 ,
create sack 0 , 250 , 250 ,
: fits? ( item -- ? )
dup weight @ sack weight @ > ... |
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... | #Julia | Julia | using Gtk.ShortNames
function keypresswindow()
# This code creates the Gtk widgets on the screen.
txt = "Type Y or N"
win = Window("Keypress Test", 250, 30) |> (Frame() |> ((vbox = Box(:v)) |> (lab = Label(txt))))
# this is the keystroke processing code, a function and a callback for the function... |
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.
| #Wren | Wren | /* keyboard_macros.wren */
var GrabModeAsync = 1
var Mod1Mask = 1 << 3
var KeyPress = 2
var XK_F6 = 0xffc3
var XK_F7 = 0xffc4
foreign class XEvent {
construct new() {}
foreign eventType
}
foreign class XDisplay {
construct openDisplay(displayName) {}
foreign defaultRootWindow()
... |
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... | #Go | Go | package main
import (
"fmt"
"sort"
)
type item struct {
item string
weight float64
price float64
}
type items []item
var all = 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",... |
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... | #Vlang | Vlang | import os
struct LetterFreq {
rune int
freq int
}
fn main(){
file := os.read_file('unixdict.txt')?
mut freq := map[rune]int{}
for c in file {
freq[c]++
}
mut lf := []LetterFreq{}
for k,v in freq {
lf << LetterFreq{u8(k),v}
}
lf.sort_with_compare(fn(a &LetterFreq... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, Dir;
[SetVid($13); \set 320x200 graphic video mode
X:= 50; Y:= 50; Dir:= 0; \start in middle facing east
repeat if ReadPix(X,Y) then \(black and white are reversed)
[Dir:= Dir-1;\left\ Point(X,Y, 0\bl... |
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... | #jq | jq | # Item {name, weight, value, count}
def Item($name; $weight; $value; $count): {$name, $weight, $value, $count};
def items: [
Item("map"; 9; 150; 1),
Item("compass"; 13; 35; 1),
Item("water"; 153; 200; 2),
Item("sandwich"; 50; 60; 2),
Item("glucose"; 15; 60; 2),
Item("tin"; 68; 45; 3),
I... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #Ada | Ada |
procedure Goto_Test is
begin
Stuff;
goto The_Mother_Ship; -- You can do this if you really must!
Stuff;
if condition then
Stuff;
<<Jail>>
Stuff;
end if;
Stuff;
-- Ada does not permit any of the following
goto Jail;
goto The_Sewer;
goto The_Morgue;
Stuff;
case... |
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... | #AutoIt | AutoIt |
Dim $a[10]
ConsoleWrite('array before permutation:' & @CRLF)
For $i = 0 To 9
$a[$i] = Random(20,100,1)
ConsoleWrite($a[$i] & ' ')
Next
ConsoleWrite(@CRLF)
_Permute($a)
ConsoleWrite('array after permutation:' & @CRLF)
For $i = 0 To UBound($a) -1
ConsoleWrite($a[$i] & ' ')
Next
ConsoleWrite(@CRLF)
Func _Permut... |
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.
| #Lingo | Lingo | -- in some movie script
-- event handler
on keyDown
pressedKey = _key.key
put "A key was pressed:" && pressedKey
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.
| #LiveCode | LiveCode | repeat 100 times
-- exit loop if "." or the escapeKey is pressed
if 46 is in the keysDown or 65307 is in the keysdown then
answer "exiting"
exit repeat
else
-- do stuff
wait 200 millisec
end if
end repeat |
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.
| #REXX | REXX | call dropbuf |
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.
| #Ring | Ring |
# Project: Keyboard input/Flush the keyboard buffer
Fflush(stdin)
|
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... | #AppleScript | AppleScript | on kernighansEarthquakes(magnitudeToBeat)
-- A local "owner" for the long AppleScript lists. Speeds up references to their items and properties.
script o
property individualEntries : {}
property qualifyingEntries : {}
end script
-- Read the text file assuming it's UTF-8 encoded and get... |
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... | #Fortran | Fortran | PROGRAM KNAPSACK
IMPLICIT NONE
REAL :: totalWeight, totalVolume
INTEGER :: maxPanacea, maxIchor, maxGold, maxValue = 0
INTEGER :: i, j, k
INTEGER :: n(3)
TYPE Bounty
INTEGER :: value
REAL :: weight
REAL :: volume
END TYPE Bounty
TYPE(Bounty) :: panacea, ichor, gold, sack, current
... |
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... | #Kotlin | Kotlin | // version 1.0.6
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities
class Test: JFrame() {
init {
while (System.`in`.available() > 0) System.`in`.read()
println("Do you want to quit Y/N")
addKeyListener(object: KeyA... |
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... | #Groovy | Groovy | import static java.math.RoundingMode.*
def knapsackCont = { list, maxWeight = 15.0 ->
list.sort{ it.weight / it.value }
def remainder = maxWeight
List sack = []
for (item in list) {
if (item.weight < remainder) {
sack << [name: item.name, weight: item.weight,
... |
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... | #Whitespace | Whitespace | |
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... | #zkl | zkl | white:=0xff|ff|ff; black:=0;
w:=h:=100; bitmap:=PPM(w,h,white);
x:=w/2; y:=h/2; dir:=0; // start in middle facing east
do{
if(bitmap[x,y]){ dir-=1; bitmap[x,y]=black; } // white-->black, turn left
else { dir+=1; bitmap[x,y]=white; } // black-->white, turn right
switch(dir.bitAnd(3)){ // dir is alway... |
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... | #Julia | Julia | using MathProgBase, Cbc
struct KPDSupply{T<:Integer}
item::String
weight::T
value::T
quant::T
end
Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)")
function solve(gear::Vector{KPDSupply{T}}, capacity::Integer) where T<:Integer
w =... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #ARM_Assembly | ARM Assembly | MOV PC,R0 ;loads the program counter with the value in R0. (Any register can be used for this)
LDR PC,[R0] ;loads the program counter with the 32-bit value at the memory location specified by R0 |
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... | #AWK | AWK | # Shuffle an _array_ with indexes from 1 to _len_.
function shuffle(array, len, i, j, t) {
for (i = len; i > 1; i--) {
# j = random integer from 1 to i
j = int(i * rand()) + 1
# swap array[i], array[j]
t = array[i]
array[i] = array[j]
array[j] = t
}
}
# Test program.
BEGIN {
len = split("11 22 33 ... |
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.
| #Logo | Logo | if key? [make "keyhit 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.
| #M2000_Interpreter | M2000 Interpreter |
k$=inkey$
|
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.
| #Ruby | Ruby | require 'io/console'
$stdin.iflush |
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.
| #Scala | Scala | def flush() { out.flush() } |
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... | #APL | APL | quakes←{
⍺←6
nl←⎕UCS 13 10
file←80 ¯1⎕MAP ⍵
lines←((~file∊nl)⊆file)~¨⊂nl
keep←⍺{0::0 ⋄ ⍺ < ⍎3⊃(~⍵∊4↑⎕TC)⊆⍵}¨lines
↑keep/lines
} |
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... | #Arturo | Arturo | data: {
3/13/2009 CostaRica 5.1
8/27/1883 Krakatoa 8.8
5/18/1980 MountStHelens 7.6
}
define :earthquake [date place magnitude][]
print first sort.descending.by:'magnitude map split.lines data =>
[to :earthquake split.words &] |
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... | #Go | Go | package main
import "fmt"
type Item struct {
Name string
Value int
Weight, Volume float64
}
type Result struct {
Counts []int
Sum int
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func Knapsack(items []Item, weight, volume float64) (best Result) {
if len(items) =... |
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... | #Liberty_BASIC | Liberty BASIC |
nomainwin
open "Y/N" for graphics_nsb_nf as #1
#1 "trapclose Quit"
#1 "down;setfocus;when characterInput KeyCheck"
#1 "place 10 50;\Press Y or N"
Inkey$=""
wait
sub KeyCheck hndle$,k$
k$=upper$(k$)
#hndle$ "cls;place 10 50"
select case k$
case "Y"
#hndle$ "\ Yes"
case "N"
... |
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... | #Haskell | Haskell | import Data.List (sortBy)
import Data.Ord (comparing)
import Text.Printf (printf)
import Control.Monad (forM_)
import Data.Ratio (numerator, denominator)
maxWgt :: Rational
maxWgt = 15
data Bounty = Bounty
{ itemName :: String
, itemVal, itemWgt :: Rational
}
items :: [Bounty]
items =
[ Bounty "beef" 36 3... |
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... | #Wren | Wren | import "io" for File
import "/fmt" for Fmt
var text = File.read("mit10000.txt")
var freqs = List.filled(26, 0)
for (c in text.codePoints) {
if (c >= 97 && c <= 122) {
freqs[c-97] = freqs[c-97] + 1
}
}
var totalFreq = freqs.reduce { |sum, f| sum + f }
System.print("Frequencies of letters in mit10000.tx... |
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... | #Kotlin | Kotlin | // version 1.1.2
data class Item(val name: String, val weight: Int, val value: Int, val count: Int)
val items = listOf(
Item("map", 9, 150, 1),
Item("compass", 13, 35, 1),
Item("water", 153, 200, 2),
Item("sandwich", 50, 60, 2),
Item("glucose", 15, 60, 2),
Item("tin", 68, 45, 3),
Item("b... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #Arturo | Arturo | ; Define a function.
function()
{
MsgBox, Start
gosub jump
free:
MsgBox, Success
}
; Call the function.
function()
goto next
return
jump:
MsgBox, Suspended
return
next:
Loop, 3
{
gosub jump
}
return
/*
Output (in Message Box):
Start
Suspended
Success
Suspended
Suspended
Suspended
*/ |
http://rosettacode.org/wiki/Knight%27s_tour | Knight's tour |
Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e... | #11l | 11l | V _kmoves = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
F chess2index(=chess, boardsize)
‘Convert Algebraic chess notation to internal index format’
chess = chess.lowercase()
V x = chess[0].code - ‘a’.code
V y = boardsize - Int(chess[1..])
R (x, y)
F boardstring(board, bo... |
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... | #BASIC | BASIC | RANDOMIZE TIMER
DIM cards(51) AS INTEGER
DIM L0 AS LONG, card AS LONG
PRINT "before:"
FOR L0 = 0 TO 51
cards(L0) = L0
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT
FOR L0 = 51 TO 0 STEP -1
card = INT(RND * (L0 + 1))
IF card <> L0 THEN SWAP cards(card), cards(L0)
NEXT
PRINT : PRINT "after:"
FOR L0 = 0... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | i = {};
EventHandler[Panel[Dynamic[i],
ImageSize -> {300, 300}], {"KeyDown" :>
AppendTo[i, CurrentValue["EventKey"]]}] |
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.
| #MiniScript | MiniScript | x = key.available |
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.
| #Nim | Nim | import os, illwill
illwillInit(fullscreen=false)
while true:
var key = getKey()
case key
of Key.None:
echo "not received a key, I can do other stuff here"
of Key.Escape, Key.Q:
break
else:
echo "Key pressed: ", $key
sleep(1000)
|
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.
| #Oforth | Oforth | import: console
: checkKey
| key |
System.Console receiveTimeout(2000000) ->key // Wait a key pressed for 2 seconds
key ifNotNull: [ System.Out "Key pressed : " << key << cr ]
"Done" println ; |
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.
| #Seed7 | Seed7 | while keypressed(KEYBOARD) do
ignore(getc(KEYBOARD));
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.
| #Sidef | Sidef | var k = frequire('Term::ReadKey');
k.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 ch... |
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.
| #Tcl | Tcl | # No waiting for input
fconfigure stdin -blocking 0
# Drain the data by not saving it anywhere
read stdin
# Flip back into blocking mode (if necessary)
fconfigure stdin -blocking 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.
| #Vedit_macro_language | Vedit macro language | Key_Purge() |
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... | #AWK | AWK | awk '$3 > 6' data.txt |
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... | #Bash | Bash | #!/bin/bash
while read line
do
[[ ${line##* } =~ ^([7-9]|6\.0*[1-9]).*$ ]] && echo "$line"
done < data.txt |
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... | #BASIC256 | BASIC256 |
f = freefile
filename$ = "data.txt"
open f, filename$
dim tok$(1)
while not eof(f)
tok$[] = readline(f)
if (right(tok$[], 4)) > 6 then print tok$[]
end while
close f
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... | #Groovy | Groovy | def totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() }
def totalVolume = { list -> list.collect{ it.item.volume * it.count }.sum() }
def totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }
def knapsackUnbounded = { possibleItems, BigDecimal weightMax, BigDecimal volumeMax ->... |
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... | #LiveCode | LiveCode | on KeyDown k
if toUpper(k) is among the items of "Y,N" then
answer "Thanks for your response"
else
answer "You need to enter Y or N"
end if
put empty into me
end KeyDown |
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... | #Logo | Logo | to yorn
type [Press Y or N to continue: ]
local "clear
make "clear readchars 0 ; clear input buffer
local "yorn
do.until [make "yorn readchar] [or equal? :yorn "Y equal? :yorn "N]
print :yorn
output :yorn
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... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
room := 15
every (x := !(choices := get_items())).uprice := x.price / x.weight
choices := reverse(sortf(choices,4))
every (value := 0, x := !choices) do {
if x.weight <= room then {
printf("Take all of the %s (%r kg) worth $%r\n",x.name,x.weight,x.price)
value +:= x.pr... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int A(256), C, I;
[for C:= 0 to 256-1 do A(C):= 0;
repeat C:= ChIn(1); \device 1 doesn't buffer nor echo chars
A(C):= A(C)+1; \count character
until C=\EOF\$1A;
C:= 0;
for I:= 0 to 128-1 do \only show 7-bit ASCII
... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Transpose@{#[[;; , 1]],
LinearProgramming[-#[[;; , 3]], -{#[[;; , 2]]}, -{400},
{0, #[[4]]} & /@ #, Integers]} &@{{"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},
... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #AutoHotkey | AutoHotkey | ; Define a function.
function()
{
MsgBox, Start
gosub jump
free:
MsgBox, Success
}
; Call the function.
function()
goto next
return
jump:
MsgBox, Suspended
return
next:
Loop, 3
{
gosub jump
}
return
/*
Output (in Message Box):
Start
Suspended
Success
Suspended
Suspended
Suspended
*/ |
http://rosettacode.org/wiki/Knight%27s_tour | Knight's tour |
Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e... | #360_Assembly | 360 Assembly | * Knight's tour 20/03/2017
KNIGHT CSECT
USING KNIGHT,R13 base registers
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
S... |
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... | #bc | bc | seed = 1 /* seed of the random number generator */
scale = 0
/* Random number from 0 to 32767. */
define rand() {
/* Formula (from POSIX) for random numbers of low quality. */
seed = (seed * 1103515245 + 12345) % 4294967296
return ((seed / 65536) % 32768)
}
/* Shuffle the first _count_ elements of shuffle[]. *... |
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.
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use Term::ReadKey;
ReadMode 4;
my $key;
until(defined($key = ReadKey(-1))){
# anything
sleep 1;
}
print "got key '$key'\n";
ReadMode('restore'); |
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.
| #Phix | Phix | integer key = get_key() -- if key was not pressed get_key() returns -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.
| #PicoLisp | PicoLisp | (setq *LastKey (key)) |
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.
| #Wren | Wren | import "io" for Stdin
System.print("Press some keys followed by enter.")
while (true) {
var b = Stdin.readByte() // reads and removes a key from the buffer
System.print("Removed key with code %(b).")
if (b == 10) break // buffer will be empty when enter key pressed
}
System.print("Keyboard buffer is now... |
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.
| #XPL0 | XPL0 | code OpenI=13;
OpenI(0) |
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... | #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
char *lw, *lt;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Unable to open file\n");
exit(1);
}
printf("Those earthquakes wit... |
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... | #Haskell | Haskell | import Data.List (maximumBy)
import Data.Ord (comparing)
(maxWgt, maxVol) = (25, 0.25)
items =
[Bounty "panacea" 3000 0.3 0.025,
Bounty "ichor" 1800 0.2 0.015,
Bounty "gold" 2500 2.0 0.002]
data Bounty = Bounty
{itemName :: String,
itemVal :: Int,
itemWgt, itemVol :: Double}
... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module Simple {
\\ a small modification from BBC BASIC entry
REPEAT {} UNTIL INKEY$ = ""
PRINT "Press Y or N to continue"
REPEAT {
k$ =Ucase$(Key$)
} UNTIL K$="Y" OR k$="N"
PRINT "The response was "; k$
}
Simple
|
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | CreateDialog[TextCell["Yes or no?[Y/N]"],
NotebookEventActions -> {
"KeyDown" :> Switch[ToUpperCase@CurrentValue["EventKey"],
"Y", Print["You said yes"]; DialogReturn[],
"N", Print["You said no"]; DialogReturn[]
]}]; |
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... | #J | J | 'names numbers'=:|:;:;._2]0 :0
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
)
'weights prices'=:|:".numbers
order=: \:prices%weights
take=: 15&<.&.(+/\) order{weights
result=: (*take)#(order{names),.' ',... |
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... | #Yabasic | Yabasic | dim ascCodes(255)
f = open("unixdict.txt", "r")
if f then
while(not eof(#f))
line input #f a$
for i = 1 to len(a$)
c = asc(mid$(a$, i, 1))
ascCodes(c) = ascCodes(c) + 1
next
wend
for i = 1 to 255
c = ascCodes(i)
if c print chr$(i), " = ", ... |
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... | #Mathprog | Mathprog | /*Knapsack
This model finds the integer optimal packing of a knapsack
Nigel_Galloway
January 9th., 2012
*/
set Items;
param weight{t in Items};
param value{t in Items};
param quantity{t in Items};
var take{t in Items}, integer, >=0, <=quantity[t];
knap_weight : sum{t in Items} take[t] * weight[t] <= 400;
... |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #BASIC | BASIC | 10 GOTO 100: REM jump to a specific line
20 RUN 200: REM start the program running from a specific line |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #BASIC256 | BASIC256 | print "First line."
gosub sub1
print "Fifth line."
goto Ending
sub1:
print "Second line."
gosub sub2
print "Fourth line."
return
Ending:
print "We're just about done..."
goto Finished
sub2:
print "Third line."
return
Finished:
print "... with goto and gosub, thankfully."
end |
http://rosettacode.org/wiki/K-d_tree | K-d tree |
This page uses content from Wikipedia. The original article was at K-d tree. 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)
A k-d tree (short for k-dimensional tree) is a space-partitioning data str... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX_DIM 3
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
... |
http://rosettacode.org/wiki/Knight%27s_tour | Knight's tour |
Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e... | #Ada | Ada | generic
Size: Integer;
package Knights_Tour is
subtype Index is Integer range 1 .. Size;
type Tour is array (Index, Index) of Natural;
Empty: Tour := (others => (others => 0));
function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour;
-- finds tour via backtracking
-- eithe... |
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... | #BQN | BQN | Knuth ← {
𝕊 arr:
l ← ≠arr
{
arr ↩ ⌽⌾(⟨•rand.Range l, 𝕩⟩⊸⊏)arr
}¨↕l
arr
}
P ← •Show Knuth
P ⟨⟩
P ⟨10⟩
P ⟨10, 20⟩
P ⟨10, 20, 30⟩ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.