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/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #Phix | Phix | without js
-- Joystick library for Euphoria (Windows)
-- /Mic, 2002
--
-- integer joy_init()
-- returns the number of joysticks attached to the computer
--
-- sequence joy_get_state(integer joy_num)
-- returns the current state of joystick #joy_num (can be either 1 or 2).
-- the format of the return sequence is:
-- ... |
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... | #Tcl | Tcl | package require TclOO
oo::class create KDTree {
variable t dim
constructor {points} {
set t [my Build 0 $points 0 end]
set dim [llength [lindex $points 0]]
}
method Build {split exset from to} {
set exset [lsort -index $split -real [lrange $exset $from $to]]
if {![llength $exset]} {return 0}
set ... |
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... | #D | D | import std.stdio, std.algorithm, std.random, std.range,
std.conv, std.typecons, std.typetuple;
int[N][N] knightTour(size_t N=8)(in string start)
in {
assert(start.length >= 2);
} body {
static struct P { int x, y; }
immutable P[8] moves = [P(2,1), P(1,2), P(-1,2), P(-2,1),
... |
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... | #DWScript | DWScript | procedure KnuthShuffle(a : array of Integer);
var
i, j, tmp : Integer;
begin
for i:=a.High downto 1 do begin
j:=RandomInt(a.Length);
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
end;
end; |
http://rosettacode.org/wiki/K-means%2B%2B_clustering | K-means++ clustering | K-means++ clustering
K-means
This data was partitioned into 7 clusters using the K-means algorithm.
The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C... | #Lua | Lua |
local function load_data(npoints, radius)
-- Generate random data points
--
local data = {}
for i = 1,npoints do
local ang = math.random() * (2.0 * math.pi)
local rad = math.random() * radius
data[i] = {x = math.cos(ang) * rad, y = math.sin(ang) * rad}
end
return data
end
local function pr... |
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... | #Ring | Ring |
# Project : Kernighans large earthquake problem
load "stdlib.ring"
nr = 0
equake = list(3)
fn = "equake.txt"
fp = fopen(fn,"r")
while not feof(fp)
nr = nr + 1
equake[nr] = readline(fp)
end
fclose(fp)
for n = 1 to len(equake)
for m = 1 to len(equake[n])
if equake[n][m] = " "
... |
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... | #Ruby | Ruby | ruby -nae "$F[2].to_f > 6 && print" 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... | #Rust | Rust | fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::io::{BufRead, BufReader};
for line in BufReader::new(std::fs::OpenOptions::new().read(true).open("data.txt")?).lines() {
let line = line?;
let magnitude = line
.split_whitespace()
.nth(2)
.and_... |
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... | #Scala | Scala | scala.io.Source.fromFile("data.txt").getLines
.map("\\s+".r.split(_))
.filter(_(2).toDouble > 6.0)
.map(_.mkString("\t"))
.foreach(println) |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #FreeBASIC | FreeBASIC |
#define pix 1./120
#define zero_x 320
#define zero_y 240
#define maxiter 250
type complex
r as double
i as double
end type
operator + (x as complex, y as complex) as complex
dim as complex ret
ret.r = x.r + y.r
ret.i = x.i + y.i
return ret
end operator
operator * (x as complex, y as comp... |
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... | #Pascal | Pascal | Program Knapsack(output);
uses
math;
type
bounty = record
value: longint;
weight, volume: real;
end;
const
panacea: bounty = (value:3000; weight: 0.3; volume: 0.025);
ichor: bounty = (value:1800; weight: 0.2; volume: 0.015);
gold: bounty = (value:2500; weight: 2.0; volume: 0.002);
sa... |
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... | #Scala | Scala | println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.") |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "keybd.s7i";
const func boolean: yesOrNo (in string: prompt) is func
result
var boolean: yes is FALSE;
local
var char: answer is ' ';
begin
while keypressed(KEYBOARD) do
ignore(getc(KEYBOARD));
end while;
write(prompt);
repeat
answer := low... |
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... | #PHP | PHP | /* Added by @1x24. Translated from C++. Uses the PHP 7.x spaceship operator */
$data = [
[
'name'=>'beef',
'weight'=>3.8,
'cost'=>36,
],
[
'name'=>'pork',
'weight'=>5.4,
'cost'=>43,
],
[
'name'=>'ham',
'weight'=>3.6,
'cost'=>90,
],
[
'name'=>'greaves',
'w... |
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... | #REXX | REXX | /*REXX program solves a knapsack problem (22 items + repeats, with weight restriction.*/
call @gen /*generate items and initializations. */
call @sort /*sort items by decreasing their weight*/
call build ... |
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... | #Harbour | Harbour | import Control.Monad.Cont
data LabelT r m = LabelT (ContT r m ())
label :: ContT r m (LabelT r m)
label = callCC subprog
where subprog lbl = let l = LabelT (lbl l) in return l
goto :: LabelT r m -> ContT r m b
goto (LabelT l) = const undefined <$> l
runProgram :: Monad m => ContT r m r -> m r
runProgram progr... |
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... | #Haskell | Haskell | import Control.Monad.Cont
data LabelT r m = LabelT (ContT r m ())
label :: ContT r m (LabelT r m)
label = callCC subprog
where subprog lbl = let l = LabelT (lbl l) in return l
goto :: LabelT r m -> ContT r m b
goto (LabelT l) = const undefined <$> l
runProgram :: Monad m => ContT r m r -> m r
runProgram progr... |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #Ceylon | Ceylon |
module knapsack "1.0.0" {
}
|
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #CLU | CLU | % This program assumes a 64-bit system.
% On a 32-bit system, the main task (show Kaprekar numbers < 10,000)
% will run correctly, but the extra credit part will crash with
% an overflow exception.
% Yield all positive splits of a number
splits = iter (n, base: int) yields (int,int)
step: int := base
while n ... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #CoffeeScript | CoffeeScript | splitAt = (str, idx) ->
ans = [ str.substring(0, idx), str.substring(idx) ]
if ans[0] == ""
ans[0] = "0"
ans
getKaprekarParts = (longValue, sqrStr, base) ->
for j in [ 0 .. sqrStr.length / 2 ]
parts = splitAt(sqrStr, j)
nums = (parseInt(n, base) for n in parts)
# if t... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #D | D | import std.stdio, std.json;
void main() {
auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
writeln(toJSON(&j));
} |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #Dart | Dart | import 'dart:convert' show jsonDecode, jsonEncode;
main(){
var json_string = '''
{
"rosetta_code": {
"task": "json",
"language": "dart",
"descriptions": [ "fun!", "easy to learn!", "awesome!" ]
}
}
''';
// decode string into Map<String, dynamic>
var json_object = jsonDecode(json_string);
for (... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #PicoLisp | PicoLisp | (load "@lib/openGl.l")
(setq *JoyX 0.0 *JoyY 0.0)
(glutInit)
(glutInitDisplayMode (| GLUT_RGBA GLUT_DOUBLE GLUT_ALPHA GLUT_DEPTH))
(glutInitWindowSize 400 400)
(glutCreateWindow "Joystick")
(glClearColor 0.3 0.3 0.5 0)
(displayPrg
(glClear GL_COLOR_BUFFER_BIT)
(glBegin GL_LINES)
(glVertex2f *JoyX (- *... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #PureBasic | PureBasic | If InitJoystick() = 0
MessageRequester("Error!", "Need to connect a joystick", #PB_MessageRequester_Ok)
End
EndIf
;some constants for Window positioning
#WindowW = 100: #WindowH = 100
#CrossW = 10
#p1 = (#WindowW - #CrossW) / 2
#p2 = (#WindowW / 2 - #CrossW)
If OpenWindow(0, 0, 0, #WindowW * 2 + 10, #WindowH, "... |
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... | #Wren | Wren | import "/dynamic" for Tuple
import "/math" for Nums
import "/seq" for Lst
import "/sort" for Sort
import "random" for Random
// A Point is represented by a 2 element List of Nums
var PtSqd = Fn.new { |p, q| Nums.sum(Lst.zip(p, q).map { |r| (r[0] - r[1]) * (r[0] - r[1]) }) }
var HyperRect = Tuple.create("HyperRect",... |
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... | #EchoLisp | EchoLisp |
(require 'plot)
(define *knight-moves*
'((2 . 1)(2 . -1 ) (1 . -2) (-1 . -2 )(-2 . -1) (-2 . 1) (-1 . 2) (1 . 2)))
(define *hit-squares* null)
(define *legal-moves* null)
(define *tries* 0)
(define (square x y n ) (+ y (* x n)))
(define (dim n) (1- (* n n))) ; n^2 - 1
;; check legal knight move from sq
;; ret... |
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... | #E | E | def shuffle(array, random) {
for bound in (2..(array.size())).descending() {
def i := random.nextInt(bound)
def swapTo := bound - 1
def t := array[swapTo]
array[swapTo] := array[i]
array[i] := t
}
} |
http://rosettacode.org/wiki/K-means%2B%2B_clustering | K-means++ clustering | K-means++ clustering
K-means
This data was partitioned into 7 clusters using the K-means algorithm.
The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | initM[list_List, k_Integer, distFunc_Symbol] :=
Module[{m = {RandomChoice[list]}, n, d},
While[Length[m] < k,
n = RandomChoice@Nearest[m, #] & /@ list;
d = Apply[distFunc, Transpose[{n, list}], {1}];
m = Append[m, RandomChoice[d -> list]]
];
m
];
kmeanspp[list_, k_,
opts : OptionsPatter... |
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... | #Snobol | Snobol | input(.quake, 1,, 'data.txt') :f(err)
num = '.0123456789'
line test = quake :f(end)
test span(num) . magnitude rpos(0) :f(line)
output = gt(magnitude,6) test :(line)
err output = 'Error!'
end |
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... | #Swift | Swift | import Foundation
guard let path = Array(CommandLine.arguments.dropFirst()).first else {
fatalError()
}
let fileData = FileManager.default.contents(atPath: path)!
let eventData = String(data: fileData, encoding: .utf8)!
for line in eventData.components(separatedBy: "\n") {
guard let lastSpace = line.lastIndex... |
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... | #Tcl | Tcl | catch {console show} ;## show console when running from tclwish
catch {wm withdraw .}
set filename "data.txt"
set fh [open $filename]
set NR 0 ;# number-of-record, means linenumber
while {[gets $fh line]>=0} { ;# gets returns length of line, -1 means eof
incr NR
set line2 [re... |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"image"
"image/color"
"image/png"
"log"
"os"
"sync"
)
func main() {
const (
width, height = 800.0, 600.0
maxIter = 255
cX, cY = -0.7, 0.27015
fileName = "julia.png"
)
img := image.NewNRGBA(image.Rect(0, 0, width, height))
var wg sync.WaitGroup
wg.Add(widt... |
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... | #Perl | Perl | my (@names, @val, @weight, @vol, $max_vol, $max_weight, $vsc, $wsc);
if (1) { # change 1 to 0 for different data set
@names = qw(panacea icor gold);
@val = qw(3000 1800 2500);
@weight = qw(3 2 20 );
@vol = qw(25 15 2 );
$max_... |
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... | #Sidef | Sidef | func prompt_yn {
static rk = frequire('Term::ReadKey');
rk.ReadMode(4); # change to raw input mode
var key = '';
while (key !~ /[yn]/i) {
while (rk.ReadKey(-1) != nil) {}; # discard any previous input
print "Type Y/N: ";
say (key = rk.ReadKey(0)); # read a single... |
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... | #Tcl | Tcl | proc yesno {{message "Press Y or N to continue"}} {
fconfigure stdin -blocking 0
exec stty raw
read stdin ; # flush
puts -nonewline "${message}: "
flush stdout
while {![eof stdin]} {
set c [string tolower [read stdin 1]]
if {$c eq "y" || $c eq "n"} break
}
puts [string to... |
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... | #Picat | Picat | go =>
items(Items),
weights(Weights),
values(Values),
knapsack_max_weight(MaxWeight),
knapsack(Weights,Values,MaxWeight, X,TotalWeight,TotalValue),
nl,
printf("Total weight: %0.2f Total value: %0.2f\n", TotalWeight,TotalValue),
foreach(I in 1..Items.len)
if X[I] > 0.0 then
printf("%-8w: ... |
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... | #Ruby | Ruby |
# Item struct to represent each item in the problem
Struct.new('Item', :name, :weight, :value, :count)
$items = [
Struct::Item.new('map', 9, 150, 1),
Struct::Item.new('compass', 13, 35, 1),
Struct::Item.new('water', 153, 200, 3),
Struct::Item.new('sandwich', 50, 60, 2),
Struct::Item.new('glucose', 15, 60,... |
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... | #i | i | //'i' does not have goto statements, instead control flow is the only legal way to navigate the program.
concept there() {
print("Hello there")
return //The return statement goes back to where the function was called.
print("Not here")
}
software {
loop {
break //This breaks the loop, the code after the loop bl... |
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... | #J | J | F=: verb define
smoutput 'Now we are in F'
G''
smoutput 'Now we are back in F'
)
G=: verb define
smoutput 'Now we are in G'
throw.
)
F''
Now we are in F
Now we are in G |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #Clojure | Clojure | (def item-data
[ "map" 9 150
"compass" 13 35
"water" 153 200
"sandwich" 50 160
"glucose" 15 60
"tin" 68 45
"banana" 27 60
"apple" 39 40
"cheese" 23 30
"beer" 52 10
"suntan cream" 11 70
"camera" 32 30
"t-shirt"... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #Common_Lisp | Common Lisp | ;; make an infinite list whose accumulated sums give all
;; numbers n where n mod (base - 1) == n^2 mod (base - 1)
(defun res-list (base)
(let* ((b (- base 1))
(l (remove-if-not
(lambda (x) (= (rem x b) (rem (* x x) b)))
(loop for x from 0 below b collect x)))
(ret (append l (list b)))
... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #Delphi | Delphi |
program JsonTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Json;
type
TJsonObjectHelper = class helper for TJsonObject
public
class function Deserialize(data: string): TJsonObject; static;
function Serialize: string;
end;
{ TJsonObjectHelper }
class function TJsonObjectHelper.... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #Python | Python | import sys
import pygame
pygame.init()
# Create a clock (for framerating)
clk = pygame.time.Clock()
# Grab joystick 0
if pygame.joystick.get_count() == 0:
raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()
# Create display
size = width, height = 600, 600
screen = pygame.displ... |
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... | #zkl | zkl | class KdTree{
const NEAREST=0, DIST_SQD=1, NODES_VISITED=2;
class KdNode{
fcn init(_dom_elt,_split,_left,_right){
var dom_elt=_dom_elt.apply("toFloat"),
split=_split, left=_left, right=_right;
}
}
fcn init(pts,_bounds){ // pts is points is ( (x,y,..),..)
var n=fcn(split, exset){
... |
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... | #Elixir | Elixir | defmodule Board do
import Integer, only: [is_odd: 1]
defmodule Cell do
defstruct [:value, :adj]
end
@adjacent [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]
defp initialize(rows, cols) do
board = for i <- 1..rows, j <- 1..cols, into: %{}, do: {{i,j}, true}
for i <- 1..rows, j <- ... |
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... | #EasyLang | EasyLang | func shuffle . a[] .
for i = len a[] downto 2
r = random i
swap a[r] a[i - 1]
.
.
arr[] = [ 1 2 3 ]
call shuffle arr[]
print arr[]
|
http://rosettacode.org/wiki/K-means%2B%2B_clustering | K-means++ clustering | K-means++ clustering
K-means
This data was partitioned into 7 clusters using the K-means algorithm.
The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C... | #Nim | Nim | #
# compile:
# nim c -d:release kmeans.nim
#
# and pipe the resultant EPS output to a file, e.g.
#
# kmeans > results.eps
#
import random, math, strutils
const
FloatMax = 1.0e100
nPoints = 100_000
nClusters = 11
type
Point = object
x, y: float
group: int
Points = seq[Point]
ClusterDist =... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
Module Module1
Function LargeEarthquakes(filename As String, limit As Double) As IEnumerable(Of String())
Return From line In File.ReadLines(filename)
Let parts = line.Split(CType(Nothing, Char()), StringSplitOptions.RemoveEmptyEntries)
Where Double.Parse(... |
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... | #Vlang | Vlang | import os
fn main() {
lines := os.read_lines('data.txt')?
println('Those earthquakes with a magnitude > 6.0 are:\n')
for line in lines {
fields := line.fields()
mag := fields[2].f64()
if mag > 6.0 {
println(line)
}
}
} |
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... | #Wren | Wren | import "io" for File
import "os" for Process
import "/pattern" for Pattern
var args = Process.arguments
if (args.count != 1) Fiber.abort("Please pass just the name of the date file.")
var fileName = args[0]
var lines = File.read(fileName).split("\n").map { |l| l.trim() }.where { |l| l != "" }
var p = Pattern.new("+1/... |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Go | Go | package main
import (
"image"
"image/color"
"image/png"
"log"
"os"
"sync"
)
func main() {
const (
width, height = 800.0, 600.0
maxIter = 255
cX, cY = -0.7, 0.27015
fileName = "julia.png"
)
img := image.NewNRGBA(image.Rect(0, 0, width, height))
var wg sync.WaitGroup
wg.Add(widt... |
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... | #Phix | Phix | -- demo\rosetta\knapsack.exw
with javascript_semantics
function knapsack(sequence res, goodies, atom profit, weight, volume, at=1, sequence chosen={})
atom {?,pitem,witem,vitem} = goodies[at]
integer n = min(floor(weight/witem),floor(volume/vitem))
chosen &= n
profit += n*pitem -- increase profit
... |
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... | #TXR | TXR | (with-resources ((tio-orig (tcgetattr) (tcsetattr tio-orig)))
(let ((tio (copy tio-orig)))
tio.(go-raw)
(tcsetattr tio tcsaflush) ;; third arg optional, defaults to tcsadrain
(whilet ((k (get-char))
((not (member k '(#\y #\n #\Y #\N)))))))) |
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... | #UNIX_Shell | UNIX Shell | getkey() {
local stty="$(stty -g)"
trap "stty $stty; trap SIGINT; return 128" SIGINT
stty cbreak -echo
local key
while true; do
key=$(dd count=1 2>/dev/null) || return $?
if [ -z "$1" ] || [[ "$key" == [$1] ]]; then
break
fi
done
stty $stty
echo "$key"
return 0
}
yorn() {
echo -... |
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... | #PicoLisp | PicoLisp | (scl 2)
(de *Items
("beef" 3.8 36.0)
("pork" 5.4 43.0)
("ham" 3.6 90.0)
("greaves" 2.4 45.0)
("flitch" 4.0 30.0)
("brawn" 2.5 56.0)
("welt" 3.7 67.0)
("salami" 3.0 95.0)
("sausage" 5.9 98.0) )
(let K
(make
(let Weight 0
(for I (by '((L) (*/ (caddr L) -1.0 (cadr L))) sort... |
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... | #SAS | SAS | /* create SAS data set */
data mydata;
input item $1-23 weight value pieces;
datalines;
map 9 150 1
compass 13 35 1
water 153 200 2
sandwich 50 60 2
glucose 15 60 2
tin 68 45 3
bana... |
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... | #Java | Java | loop1: while (x != 0) {
loop2: for (int i = 0; i < 10; i++) {
loop3: do {
//some calculations...
if (/*some condition*/) {
//this continue will skip the rest of the while loop code and start it over at the next iteration
continue loop1;
}
... |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #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 (l... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #D | D | import std.stdio, std.conv, std.algorithm, std.range;
bool isKaprekar(in long n) pure /*nothrow*/ @safe
in {
assert(n > 0, "isKaprekar(n) is defined for n > 0.");
} body {
if (n == 1)
return true;
immutable sn = text(n ^^ 2);
foreach (immutable i; 1 .. sn.length) {
immutable a = sn[0... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #EchoLisp | EchoLisp |
;; JSON standard types : strings, numbers, and arrays (vectors)
(export-json #(6 7 8 9)) → "[6,7,8,9]"
(export-json #("alpha" "beta" "gamma")) → "["alpha","beta","gamma"]"
(json-import "[6,7,8,9]") → #( 6 7 8 9)
(json-import #<< ["alpha","beta","gamma"] >>#) → #( "alpha" "beta" "gamma")
;; EchoLisp ty... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #Raku | Raku | use experimental :pack;
# Joysticks generally show up in the /dev/input/ directory as js(n) where n is
# the number assigned by the OS. E.G. /dev/input/js1 . In my particular case:
my $device = '/dev/input/js0';
my $exit = 0;
my $event-stream = $device.IO.open(:bin);
my $js = $event-stream.Supply(:8size);
my ... |
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... | #Elm | Elm | module Main exposing (main)
import Browser exposing (element)
import Html as H
import Html.Attributes as HA
import List exposing (filter, head, length, map, map2, member, tail)
import List.Extra exposing (andThen, minimumBy)
import String exposing (join)
import Svg exposing (g, line, rect, svg)
import Svg.Attributes ... |
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... | #EchoLisp | EchoLisp |
Remark- The native '''shuffle''' function implementation in EchoLisp has been replaced by this one.
Thx Rosetta Code.
(lib 'list) ;; for list-permute
;; use "inside-out" algorithm, no swapping needed.
;; returns a random permutation vector of [0 .. n-1]
(define (rpv n (j))
(define v (make-vector n))
(for [(i n)]... |
http://rosettacode.org/wiki/K-means%2B%2B_clustering | K-means++ clustering | K-means++ clustering
K-means
This data was partitioned into 7 clusters using the K-means algorithm.
The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C... | #Phix | Phix | -- demo\rosetta\K_means_clustering.exw
-- Press F5 to restart
include pGUI.e
Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
constant TITLE = "K-means++ clustering"
constant useGoInitialData = false -- (not very well centered)
constant N = 30000, -- number of points
K... |
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... | #XPL0 | XPL0 | int C;
[loop [OpenO(8); \get line from input file
repeat C:= ChIn(1);
ChOut(8, C); \save it in buffer device 8
if C = $1A\EOF\ then quit;
until C = $0A\LF\;
OpenI(8);
repeat until ChIn(8) <= $20\space\;
repeat until ChIn(8) > ... |
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... | #Yabasic | Yabasic | if peek("argument") then
filename$ = peek$("argument")
else
filename$ = "data.txt"
end if
dim tok$(1)
a = open(filename$)
if not a error "Could not open '" + filename$ + "' for reading"
while(not eof(a))
line input #a a$
void = token(a$, tok$())
if val(tok$(3)) > 6 print a$
wend
close a |
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... | #zkl | zkl | fcn equake(data,out=Console){
data.pump(out,fcn(line){ 6.0line.split()[-1] },Void.Filter)
} |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Haskell | Haskell | import System.Environment (getArgs)
plotChar :: Int -> Float -> Float -> Float -> Float -> Char
plotChar iter cReal cImag y x
| zReal^2 > 10000 = ' '
| iter == 1 = '#'
| otherwise = plotChar (pred iter) cReal cImag zImag zReal
where
zReal = x * x - y * y + cReal
zImag = x * y * 2 + cImag
par... |
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... | #Picat | Picat | import mip.
go =>
data(Items,Value,Weight,Volume,MaxWeight,MaxVolume),
knapsack_problem(Value,Weight,Volume,MaxWeight,MaxVolume, X,Z),
println(z=Z),
println(x=X),
N = Items.len,
foreach({Item,Num} in zip(Items,X), Num > 0)
printf("Take %d of %w\n", Num,Item)
end,
print("\nTotal volume: "),
... |
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... | #PicoLisp | PicoLisp | (de *Items
("panacea" 3 25 3000)
("ichor" 2 15 1800)
("gold" 20 2 2500) )
(de knapsack (Lst W V)
(when Lst
(let X (knapsack (cdr Lst) W V)
(if (and (ge0 (dec 'W (cadar Lst))) (ge0 (dec 'V (caddar Lst))))
(maxi
'((L) (sum cadddr L))
(li... |
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... | #VB-DOS | VB-DOS | OPTION EXPLICIT
DIM T AS INTEGER
T = MSGBOX("Click on yes or no", 4, "Option")
PRINT "The response is ";
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no";
PRINT "."
END |
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response | Keyboard input/Obtain a Y or N response |
Task
Obtain a valid Y or N response from the keyboard.
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing Y or N key-press from being evaluated.
The response should be obtained as soon as Y or N are pressed, and there should be no need t... | #Vedit_macro_language | Vedit macro language | Key_Purge() // flush keyboard buffer
do {
#1 = Get_Key("Are you sure? (Y/N): ") // prompt for a key
#1 &= 0xdf // to upper case
} while (#1 != 'Y' && #1 != '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... | #PL.2FI | PL/I | *process source xref attributes;
KNAPSACK_CONTINUOUS: Proc Options(main);
/*--------------------------------------------------------------------
* 19.09.2014 Walter Pachl translated from FORTRAN
*-------------------------------------------------------------------*/
Dcl (divide,float,hbound,repeat) Builtin;
Dcl ... |
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... | #Sidef | Sidef | var raw = <<'TABLE'
map 9 150 1
compass 13 35 1
water 153 200 2
sandwich 50 60 2
glucose 15 60 2
tin 68 45 3
banana 27 60 3
apple 39 40 3
cheese 23 30 1
beer 52 ... |
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... | #jq | jq | label $out | ... break $out ... |
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... | #Julia | Julia |
function example()
println("Hello ")
@goto world
println("Never printed")
@label world
println("world")
end
|
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #Crystal | Crystal | require "bit_array"
struct BitArray
def clone
BitArray.new(size).tap { |new| new.to_slice.copy_from (to_slice) }
end
end
record Item, name : String, weight : Int32, value : Int32
record Selection, mask : BitArray, cur_index : Int32, total_value : Int32
class Knapsack
@threshold_value = 0
@threshold_... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #Dart | Dart |
import 'dart:math';
void main()
{
int x1;
for(x1=1;x1<1000000;x1++){
int x;
int i,y,y1,l1,z,l;
double o,o1,o2,o3;
x=pow(x1,2);
for(i=0;;i++)
{z=pow(10,i);
if(x%z==x)break;}
if(i.isEven)
{
y=pow(10,i/2);
l=x%y;
o=x/y;
o=o-l/y;
o3=o;
for(int j=0;j<4;j++)
{
if(o%10==0)
o=o/10;
... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #Elixir | Elixir | defmodule KaprekarNumber do
def check(n), do: check(n, 10)
def check(1,_base), do: {"1", ""}
def check(n, base) when rem(n*(n-1), (base-1)) != 0, do: false # casting out nine
def check(n, base) do
square = Integer.to_string(n*n, base)
check(n, base, square, 1, String.length(square)-1)
end
d... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #EGL | EGL | record familyMember
person person;
relationships relationship[]?;
end
record person
firstName string;
lastName string;
age int;
end
record relationship
relationshipType string;
id int;
end |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #Elena | Elena | import extensions;
import extensions'dynamic;
public program()
{
var json := "{ ""foo"": 1, ""bar"": [10, ""apples""] }";
var o := json.fromJson();
console.printLine("json.foo=",o.foo);
console.printLine("json.bar=",o.bar)
} |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #Tcl | Tcl | package require Tk 8.6
package require mkLibsdl
# This code assumes we're dealing with the first pair of axes on the first
# joystick; modern joysticks are complex...
# Callback for all joystick activity
proc display {joyDict} {
global x y buttons message
set axis -1
dict with joyDict {
if {$joystick !... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #Wren | Wren | import "input" for Keyboard, GamePad
import "graphics" for Canvas, Color
import "dome" for Window
var Buttons = [
"left", "right", "up", "down", "A", "B", "X", "Y",
"back", "start", "guide", "leftshoulder", "rightshoulder"
]
var Symbols = ["L", "R", "U", "D", "A", "B", "X", "Y", "BK", "S", "G", "LS", "RS"]
... |
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... | #Erlang | Erlang |
-module( knights_tour ).
-export( [display/1, solve/1, task/0] ).
display( Moves ) ->
%% The knigh walks the moves {Position, Step_nr} order.
%% Top left corner is {$a, 8}, Bottom right is {$h, 1}.
io:fwrite( "Moves:" ),
lists:foldl( fun display_moves/2, erlang:length(Moves), lists:keysort(2, Moves) ),
io:nl... |
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... | #Egel | Egel |
import "prelude.eg"
import "random.ego"
using System
using List
using Math
def swap =
[ I J XX -> insert I (nth J XX) (insert J (nth I XX) XX) ]
def shuffle =
[ XX ->
let INDICES = reverse (fromto 0 ((length XX) - 1)) in
let SWAPS = map [ I -> I (between 0 I) ] INDICES in
fol... |
http://rosettacode.org/wiki/K-means%2B%2B_clustering | K-means++ clustering | K-means++ clustering
K-means
This data was partitioned into 7 clusters using the K-means algorithm.
The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C... | #Python | Python | from math import pi, sin, cos
from collections import namedtuple
from random import random, choice
from copy import copy
try:
import psyco
psyco.full()
except ImportError:
pass
FLOAT_MAX = 1e100
class Point:
__slots__ = ["x", "y", "group"]
def __init__(self, x=0.0, y=0.0, group=0):
... |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #J | J | load '~addons/graphics/fvj4/complex_dynamics.ijs'
pal2=: 255,~0,<.(254$1 0.8 0.6)*Hue 5r6*(i.%<:)254
g=: [: %: 0.3746j0.102863 0.132565j0.389103 _0.373935j_0.353777 1&p.
view_image pal2;b=:g escapetc (10 255) 500 zl_clur _1.5 1.5j1.5 |
http://rosettacode.org/wiki/Julia_set | Julia set |
Task
Generate and draw a Julia set.
Related tasks
Mandelbrot Set
| #Java | Java | import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class JuliaSet extends JPanel {
private static final int MAX_ITERATIONS = 300;
private static final double ZOOM = 1;
private static final double CX = -0.7;
private static final double CY = 0.27015;
private static ... |
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... | #PowerShell | PowerShell | # Define the items to pack
$Item = @(
[pscustomobject]@{ Name = 'panacea'; Unit = 'vials' ; value = 3000; Weight = 0.3; Volume = 0.025 }
[pscustomobject]@{ Name = 'ichor' ; Unit = 'ampules'; value = 1800; Weight = 0.2; Volume = 0.015 }
[pscustomobject]@{ Name = 'gold' ; Unit = 'bars' ; value = 2500; ... |
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response | Keyboard input/Obtain a Y or N response |
Task
Obtain a valid Y or N response from the keyboard.
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing Y or N key-press from being evaluated.
The response should be obtained as soon as Y or N are pressed, and there should be no need t... | #Vlang | Vlang | import term.ui as tui
struct App {
mut:
tui &tui.Context = 0
}
fn event(e &tui.Event, x voidptr) {
mut app := &App(x)
app.tui.clear()
app.tui.set_cursor_position(0, 0)
app.tui.write('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
if e.typ == .key_down {
mut cap := ''
if !... |
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... | #Wee_Basic | Wee Basic | print 1 "Enter Y for yes, or N for no. (not case sensitive)"
let loop=0
let keycode=0
while loop=0
let keycode=key()
if keycode=121
let response$="y"
let loop=1
elseif keycode=89
let response$="Y"
let loop=1
elseif keycode=110
let response$="n"
let loop=1
elseif keycode=78
let response$="N"
let loop=1
endif
wend
print ... |
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... | #Prolog | Prolog | :- use_module(library(simplex)).
% tuples (name, weights, value).
knapsack :-
L = [( 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),
... |
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... | #Swift | Swift | public struct KnapsackItem: Hashable {
public var name: String
public var weight: Int
public var value: Int
public init(name: String, weight: Int, value: Int) {
self.name = name
self.weight = weight
self.value = value
}
}
public func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem... |
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... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
intArrayOf(4, 5, 6).forEach lambda@ {
if (it == 5) return@lambda
println(it)
}
println()
loop@ for (i in 0 .. 3) {
for (j in 0 .. 3) {
if (i + j == 4) continue@loop
if (i + j == 5) break@loop
p... |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | 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 to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #D | D | import std.stdio, std.algorithm, std.typecons, std.array, std.range;
struct Item { string name; int weight, value; }
Item[] knapsack01DinamicProgramming(immutable Item[] items, in int limit)
pure nothrow @safe {
auto tab = new int[][](items.length + 1, limit + 1);
foreach (immutable i, immutable it; items... |
http://rosettacode.org/wiki/Kaprekar_numbers | Kaprekar numbers | A positive integer is a Kaprekar number if:
It is 1 (unity)
The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
... | #Erlang | Erlang |
-mode(compile).
-import(lists, [seq/2]).
kaprekar(1) -> true;
kaprekar(N) when N < 1 -> false;
kaprekar(N) ->
Sq = N*N,
if
(N rem 9) =/= (Sq rem 9) -> false;
true -> kaprekar(N, Sq, 10)
end.
kaprekar(_, Sq, M) when (Sq div M) =:= 0 -> false;
kaprekar(N, Sq, M) ->
L = Sq div M,
... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #Emacs_Lisp | Emacs Lisp | (require 'cl-lib)
(cl-assert (fboundp 'json-parse-string))
(cl-assert (fboundp 'json-serialize))
(defvar example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(defvar example-object '((foo . "bar") (baz . [1 2 3])))
;; decoding
(json-parse-string example) ;=> #s(hash-table [...]))
;; using json.el-style options
(json... |
http://rosettacode.org/wiki/JSON | JSON | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| #Erlang | Erlang |
-module(json).
-export([main/0]).
main() ->
JSON =
"{
\"firstName\": \"John\",
\"lastName\": \"Smith\",
\"age\": 25,
\"address\": {
\"streetAddress\": \"21 2nd Street\",
\"city\": \"New York\",
\"state\": \"NY\",
\"postalCode\": \"10021\"
},
... |
http://rosettacode.org/wiki/Joystick_position | Joystick position | The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.
... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM o$(5)
20 LET xm=0: LET xx=31: REM screen limits
30 LET ym=0: LET yx=18
40 LET xo=16: LET yo=9: REM origin
50 LET xc=xo: LET yc=yo
60 PRINT AT yc,xc;" ": REM entry point for scan loop - blank cursor
70 LET xc=xo: LET yc=yo
80 LET t=IN 31
90 IF t=1 OR t=5 OR t=9 OR t=17 OR t=21 OR t=25 THEN LET xc=xx: LET o$(2)="R... |
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... | #ERRE | ERRE |
! **********************************************************************
! * *
! * IL GIRO DEL CAVALLO - come collocare un cavallo su di una *
! * scacchiera n*n passando una sola volta *
! * ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.