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/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...
#Clojure
Clojure
(defn shuffle [vect] (reduce (fn [v i] (let [r (rand-int i)] (assoc v i (v r) r (v i)))) vect (range (dec (count vect)) 1 -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.
#Wren
Wren
import "scheduler" for Scheduler import "timer" for Timer import "io" for Stdin, Stdout   Stdin.isRaw = true // no echoing or buffering   var b   Scheduler.add { b = Stdin.readByte() }   System.print("Awaiting keypress..") Timer.sleep(2000) // allow 2 seconds say if (b) { System.write("The key with code %(b) wa...
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int K, N; [N:= 0; repeat K:= KeyHit; \counts up until a key is pressed IntOut(0, N); ChOut(0, ^ ); N:= N+1; until K; ]
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...
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "time" )   type r2 struct { x, y float64 }   type r2c struct { r2 c int // cluster number }   // kmpp implements K-means++, satisfying the basic task requirement func kmpp...
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...
#Haskell
Haskell
import qualified Data.ByteString.Lazy.Char8 as C   main :: IO () main = do cs <- C.readFile "data.txt" mapM_ print $ C.lines cs >>= (\x -> [ x | 6 < (read (last (C.unpack <$> C.words x)) :: Float) ])
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...
#J
J
  NB. this program is designed for systems where the line ending is either LF or CRLF     NB. filename select_magnitude minimum NB. default file is /tmp/famous.quakers   select_magnitude=: '/tmp/famous.quakers'&$: : (4 :0) data =. 1!:1 boxopen x NB. read the file data =. data -. CR NB. remove nasty ca...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#BASIC
BASIC
escala = 1 / 81 zeroX = 160 zeroY = 100 maxiter = 32   CR = -.798 CI = .1618   SCREEN 13 FOR x = 0 TO 2 * zeroX - 1 FOR y = 0 TO 2 * zeroY - 1 zreal = (x - zeroX) * escala zimag = (zeroY - y) * escala FOR iter = 1 TO maxiter BR = CR + zreal * zreal - zimag * zimag zim...
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...
#Julia
Julia
  using JuMP using GLPKMathProgInterface   model = Model(solver=GLPKSolverMIP())   @variable(model, vials_of_panacea >= 0, Int) @variable(model, ampules_of_ichor >= 0, Int) @variable(model, bars_of_gold >= 0, Int)   @objective(model, Max, 3000*vials_of_panacea + 1800*ampules_of_ichor + 2500*bars_of_gold)   @constraint(...
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...
#Pascal
Pascal
Program ObtainYN;   uses crt;   var key: char;   begin write('Your answer? (Y/N): '); repeat key := readkey; until (key in ['Y', 'y', 'N', 'n']); writeln; writeln ('Your answer was: ', key); 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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Knapsack[shop_, capacity_] := Block[{sortedTable, overN, overW, output}, sortedTable = SortBy[{#1, #2, #3, #3/#2} & @@@ shop, -#[[4]] &]; overN = Position[Accumulate[sortedTable[[1 ;;, 2]]], a_ /; a > capacity, 1,1][[1, 1]]; overW = Accumulate[sortedTable[[1 ;;, 2]]][[overN]] - capacity;   output = Reverse@sortedT...
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...
#Perl
Perl
#!/usr/bin/perl   use strict;   my $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...
#D
D
$ return ! ignored since we haven't done a gosub yet $ $ if p1 .eqs. "" then $ goto main $ inner: $ exit $ $ main: $ goto label ! if label hasn't been read yet then DCL will read forward to find label $ label: $ write sys$output "after first occurrence of label" $ $ on control_y then $ goto continue1 ! we will use t...
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...
#AWK
AWK
  # syntax: GAWK -f KNAPSACK_PROBLEM_0-1.AWK BEGIN { # arr["item,weight"] = value arr["map,9"] = 150 arr["compass,13"] = 35 arr["water,153"] = 200 arr["sandwich,50"] = 160 arr["glucose,15"] = 60 arr["tin,68"] = 45 arr["banana,27"] = 60 arr["apple,39"] = 40 arr["cheese,23"] = 30 ...
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. ...
#Arturo
Arturo
k?: function [n][ n2: to :string n*n loop 0..dec size n2 'i [ a: (i > 0)? -> to :integer slice n2 0 dec i -> 0 b: to :integer slice n2 i dec size n2 if and? b > 0 n = a + b -> return true ] return false ]   loop 1..10000 'x [ if k? x -> print x ]
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Haskell
Haskell
import Text.Printf import Data.List   juggler :: Integer -> [Integer] juggler = takeWhile (> 1) . iterate (\x -> if odd x then isqrt (x*x*x) else isqrt x)   task :: Integer -> IO () task n = printf s n (length ns + 1) (i :: Int) (show...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#J
J
jug=: <.@^ 0.5+2|]
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).
#8th
8th
[1,2,3] . cr
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).
#Ada
Ada
  with Ada.Text_IO; with GNATCOLL.JSON;   procedure JSON_Test is use Ada.Text_IO; use GNATCOLL.JSON;   JSON_String : constant String := "{""name"":""Pingu"",""born"":1986}";   Penguin : JSON_Value := Create_Object; Parents : JSON_Array; begin Penguin.Set_Field (Field_Name => "name", ...
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. ...
#Applesoft_BASIC
Applesoft BASIC
100 GOSUB 400 110 P2 = PDL(2) : IF P2 <> O2 THEN O2 = P2 : VTAB 23 : HTAB 33 : PRINT P2; TAB(37); 120 B2 = FNB(2) : IF B2 <> N2 THEN N2 = B2 : VTAB 24 : HTAB 15 : PRINT P$(B2); 130 P3 = PDL(3) : IF P3 <> O3 THEN O3 = P3 : VTAB 23 : HTAB 37 : PRINT P3; : CALL -868 140 X = INT(P3 * RX) : Y = INT(P2 * RY(F)) 150 O = (X1 =...
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. ...
#AutoHotkey
AutoHotkey
; Uncomment if Gdip.ahk is not in your standard library ; #Include, Gdip.ahk   ; Comment for lower CPU usage SetBatchLines, -1   JoystickNumber := 0 ; (1-16) or (0 = Auto-detect) CrosshairSize := 100 BarWidth := 50 BarSpacing := BarWidth + 8 Color1 := 0x99000000 Color2 := 0x99ffffff Color3 := 0x99ff6600 Color4 := 0...
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...
#J
J
coclass 'kdnode' create=:3 :0 Axis=: ({:$y)|<.2^.#y Mask=: Axis~:i.{:$y if. 3>#y do. Leaf=:1 Points=: y else. Leaf=:0 data=. y /: Axis|."1 y n=. <.-:#data Points=: ,:n{data Left=: conew&'kdnode' n{.data Right=: conew&'kdnode' (1+n)}.data end. )   ...
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...
#BBC_BASIC
BBC BASIC
VDU 23,22,256;256;16,16,16,128 VDU 23,23,4;0;0;0; OFF GCOL 4,15 FOR x% = 0 TO 512-128 STEP 128 RECTANGLE FILL x%,0,64,512 NEXT FOR y% = 0 TO 512-128 STEP 128 RECTANGLE FILL 0,y%,512,64 NEXT GCOL 9   DIM Board%(7,7) X% = 0 Y% = 0 ...
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...
#CLU
CLU
knuth_shuffle = proc [T: type] (a: array[T]) lo: int := array[T]$low(a) hi: int := array[T]$high(a) for i: int in int$from_to_by(hi, lo+1, -1) do j: int := lo + random$next(i-lo+1) temp: T := a[i] a[i] := a[j] a[j] := temp end end knuth_shuffle   start_up = proc () po...
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...
#Haskell
Haskell
{-# LANGUAGE Strict,FlexibleInstances #-} module KMeans where   import Control.Applicative import Control.Monad.Random import Data.List (minimumBy, genericLength, transpose) import Data.Ord (comparing) import qualified Data.Map.Strict as M     type Vec = [Float] type Cluster = [Vec]   kMeansIteration :: [Vec] -> [Vec] ...
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...
#Java
Java
  import java.io.BufferedReader; import java.io.FileReader;   public class KernighansLargeEarthquakeProblem {   public static void main(String[] args) throws Exception { try (BufferedReader reader = new BufferedReader(new FileReader("data.txt")); ) { String inLine = null; while ( (i...
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...
#JavaScript
JavaScript
  const fs = require("fs"); const readline = require("readline");   const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); }   const fname = args[0];   const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: f...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#C
C
<executable name> <width of graphics window> <height of graphics window> <real part of complex number> <imag part of complex number> <limiting radius> <Number of iterations to be tested>
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#C.23
C#
using System.Drawing; // Note: You have to add the System.Drawing assembly // (right-click "references," Add Reference, Assemblies, Framework, // System.Drawing, OK) using System.Linq;   namespace RosettaJuliaSet { class Program { static void Main(string[] args) { const int w = ...
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...
#Kotlin
Kotlin
// version 1.1.2   data class Item(val name: String, val value: Double, val weight: Double, val volume: Double)   val items = listOf( Item("panacea", 3000.0, 0.3, 0.025), Item("ichor", 1800.0, 0.2, 0.015), Item("gold", 2500.0, 2.0, 0.002) )   val n = items.size val count = IntArray(n) val best = IntArray(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...
#Perl
Perl
use Term::ReadKey;   ReadMode 4; # change to raw input mode   my $key = '';   while($key !~ /(Y|N)/i) { 1 while defined ReadKey -1; # discard any previous input print "Type Y/N: "; $key = ReadKey 0; # read a single character print "$key\n"; }   ReadMode 0; # reset the terminal to normal mode   print "\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...
#Phix
Phix
integer key while get_key()!=-1 do end while -- flush puts(1,"Your answer? (Y/N)") while 1 do key = upper(get_key()) if find(key,"YN") then exit end if end while printf(1,"\nYour response was %s\n",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...
#Mathprog
Mathprog
/*Knapsack   This model finds the optimal packing of a knapsack   Nigel_Galloway January 10th., 2012 */ set Items; param weight{t in Items}; param value{t in Items};   var take{t in Items}, >=0, <=weight[t];   knap_weight : sum{t in Items} take[t] <= 15;   maximize knap_value: sum{t in Items} take[t] * (value[t]/...
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...
#Phix
Phix
with javascript_semantics atom t0 = time() constant goodies = { -- item weight value pieces {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin", ...
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...
#DCL
DCL
$ return ! ignored since we haven't done a gosub yet $ $ if p1 .eqs. "" then $ goto main $ inner: $ exit $ $ main: $ goto label ! if label hasn't been read yet then DCL will read forward to find label $ label: $ write sys$output "after first occurrence of label" $ $ on control_y then $ goto continue1 ! we will use t...
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...
#BASIC
BASIC
N = 7: G = 5: a = 2 ^ (N + 1) ' Author: DANILIN & Editor: Jjuanhdez or Unknow RANDOMIZE TIMER DIM L(N), C(N), j(N), q(a), d(a), q$(a)   FOR i = a - 1 TO (a - 1) \ 2 STEP -1 k = i DO ' cipher 0-1 q$(i) = LTRIM$(STR$(k MOD 2)) + q$(i) k = INT(k / 2) LOOP UNTIL k = 0 q$(i) = MID$(q$(i), 2,...
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. ...
#AutoHotkey
AutoHotkey
Kaprekar(L) { Loop, % L + ( C := 0 ) { S := ( N := A_Index ) ** 2 Loop % StrLen(N) { B := ( B := SubStr(S,1+A_Index) ) ? B : 0 If !B & ( (A := SubStr(S,1,A_Index)) <> 1 ) Break If ( N == A+B ) { R .= ", " N , C++ Bre...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#jq
jq
def juggler: . as $n | if $n < 1 then "juggler starting value must be a positive integer." | error else { a: $n, count: 0, maxCount: 0, max: $n } | until (.a == 1; if .a % 2 == 0 then .a |= isqrt else .a = ((.a * .a * .a)|isqrt) end | .count += 1 | if .a > .max ...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Julia
Julia
using Formatting   function juggler(k, countdig=true, maxiters=20000) m, maxj, maxjpos = BigInt(k), BigInt(k), BigInt(0) for i in 1:maxiters m = iseven(m) ? isqrt(m) : isqrt(m*m*m) if m >= maxj maxj, maxjpos = m, i end if m == 1 println(lpad(k, 9), lpad(i...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
next[n_Integer] := If[EvenQ@n, Floor[Sqrt[n]], Floor[n^(3/2)]]   stats[n_Integer] :=   Block[{data = Most@NestWhileList[next, n, # > 1 &], mx}, mx = First@Ordering[data, -1]; {n, Length[data], data[[mx]], mx - 1}]   {TableForm[Table[stats@n, {n, 20, 39}], TableHeadings -> {None, {"n", "length", "max", "max pos"}...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Nim
Nim
import math, strformat   func juggler(n: Positive): tuple[count: int; max: uint64; maxIdx: int] = var a = n.uint64 result = (0, a, 0) while a != 1: let f = float(a) a = if (a and 1) == 0: sqrt(f).uint64 else: uint64(f * sqrt(f)) inc result.count if a > result.max: result.max = a ...
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).
#AntLang
AntLang
  json:{[data]catch[eval[,|{[y]catch[{":" = "="; "[" = "<"; "]" = ">"; "," = ";"}[y];{x};{[]y}]}'("""("(\\.|[^\\"])*"|\-?[0-9]+(\.[0-9]+)?|\{|\}|\[|\]|\:|\,)"""~data)["strings"]];{x};{error["Invalid 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).
#ANTLR
ANTLR
  // Parse JSON // // Nigel Galloway - April 27th., 2012 // grammar JSON ; @members { String Indent = ""; } Number : (('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?; WS : (' ' | '\t' | '\r' |'\n') {skip();}; Tz : ' ' .. '!' | '#' .. '[' | ']' .. '~'; Control : '\\' ('"'|'\...
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. ...
#BBC_BASIC
BBC BASIC
VDU 23,22,512;512;8,16,16,0 VDU 5   GCOL 4,15 REPEAT B% = ADVAL(0) X% = ADVAL(1) / 64 Y% = 1023 - ADVAL(2) / 64 PROCjoy(B%,X%,Y%) WAIT 4 PROCjoy(B%,X%,Y%) UNTIL FALSE END   DEF PROCjoy(B%,X%,Y%) LOCAL I% LINE X%-32,Y%,...
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. ...
#C
C
#include <stdio.h> #include <stdlib.h>   void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } }   #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\...
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...
#Java
Java
import java.util.*;   public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0;   public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(no...
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...
#Bracmat
Bracmat
( knightsTour = validmoves WarnsdorffSort algebraicNotation init solve , x y fieldsToVisit . ~ | ( validmoves = x y jumps moves .  !arg:(?x.?y) & :?moves & ( jumps = dx dy Fs fxs fys fx fy .  !arg:(?dx....
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...
#CMake
CMake
# shuffle(<output variable> [<value>...]) shuffles the values, and # stores the result in a list. function(shuffle var) set(forever 1)   # Receive ARGV1, ARGV2, ..., ARGV${last} as an array of values. math(EXPR last "${ARGC} - 1")   # Shuffle the array with Knuth shuffle (Fisher-Yates shuffle). foreach(i RANG...
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...
#Huginn
Huginn
#! /bin/sh exec huginn -E "${0}" "${@}" #! huginn   import Algorithms as algo; import Mathematics as math; import OperatingSystem as os;   class Color { r = 0.; g = 0.; b = 0.; } class Point { x = 0.; y = 0.; group = -1; }   k_means_initial_centroids( points_, clusterCount_ ) { centroids = []; discreteRng = math.Rand...
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...
#jq
jq
jq -Rrn 'inputs | . as $line | [splits(" *") ] | select((.[2]|tonumber) > 6) | $line' 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...
#Julia
Julia
using DataFrames, CSV   df = CSV.File("kernighansproblem.txt", delim=" ", ignorerepeated=true, header=["Date", "Location", "Magnitude"], types=[DateTime, String, Float64], dateformat="mm/dd/yyyy") |> DataFrame   println(filter(row -> row[:Magnitude] > 6, df))  
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...
#Klingphix
Klingphix
arg pop nip len dup   ( [get nip] [drop drop "data.txt"] ) if   %f dup "r" fopen !f $f 0 < ( [drop "Could not open '" print print "' for reading" print -1 end ] [drop] ) if   [dup split 3 get tonum 6 > ( [drop print nl] [drop drop] ) if] [$f fgets dup -1 #] while   drop $f fclose   "End " input
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <complex>   const int BMP_SIZE = 600, ITERATIONS = 512; const long double FCT = 2.85, hFCT = FCT / 2.0;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); ...
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...
#Lua
Lua
items = { ["panaea"] = { ["value"] = 3000, ["weight"] = 0.3, ["volume"] = 0.025 }, ["ichor"] = { ["value"] = 1800, ["weight"] = 0.2, ["volume"] = 0.015 }, ["gold"] = { ["value"] = 2500, ["weight"] = 2.0, ["volume"] = 0.002 } }   max_weight = 25 max_volume = 0.25   max_num_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...
#PicoLisp
PicoLisp
(de yesno () (loop (NIL (uppc (key))) (T (= "Y" @) T) (T (= "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...
#PL.2FI
PL/I
yn: Proc Options(main): Dcl sysin stream input; Dcl sysprint stream output; Dcl c Char(1); Put Skip List('Please enter Y or N'); Get Edit(c)(a(1)); Select(c); When('Y','y','J','j') Put Skip List('YES'); When('N','n') Put Skip List('NO'); Otherwise Put Skip List('Undecided?'); End; End...
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#MiniZinc
MiniZinc
  %Knapsack Continuous. Nigel Galloway: October 7th., 2020. enum Items={beef,pork,ham,greaves,flitch,brawn,welt,salami,sausage}; array[Items] of float: weight=[3.8,5.4,3.6,2.4,4.0,2.5,3.7,3.0,5.9]; array[Items] of int: value =[36,43,90,45,30,56,67,95,9]; float: maxWeight=15.0; var float: wTaken=sum(n in Items)(quantit...
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...
#Picat
Picat
import mip,util.   go => data(AllItems,MaxWeight), [Items,Weights,Values,Pieces] = transpose(AllItems),   knapsack_bounded(Weights,Values,Pieces,MaxWeight, X,TotalWeight,TotalValue),   print_solution(Items,Weights,Values, X,TotalWeight,TotalValue), nl.   % Print the solution print_solution(Items,Weights,...
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
example:  !print "First part" yield  !print "Second part"   local :continue example !print "Interrupted" continue
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...
#Delphi
Delphi
  var x: Integer = 5;   label positive, negative, both;   begin if (x > 0) then goto positive else goto negative;   positive: writeln('pos'); goto both;   negative: writeln('neg'); both: readln; 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...
#Batch_File
Batch File
:: Initiate command line environment @echo off setlocal enabledelayedexpansion :: Establish arrays we'll be using set items=map compass water sandwich glucose tin banana apple cheese beer suntancream camera tshirt trousers umbrella waterprooftrousers waterproofoverclothes notecase sunglasses towel socks book set weig...
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. ...
#AWK
AWK
  # syntax: GAWK -f KAPREKAR_NUMBERS.AWK BEGIN { limit = 1000000 printf("%d\n",1) n = 1 for (i=2; i<limit; i++) { squared = sprintf("%.0f",i*i) for (j=1; j<=length(squared); j++) { L = substr(squared,1,j) + 0 R = substr(squared,j+1) + 0 if (R == 0) { continu...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Juggler_sequence use warnings; use Math::BigInt lib => 'GMP';   print " n l(n) i(n) h(n) or d(n)\n"; print " ------- ---- ---- ------------\n"; for my $i ( 20 .. 39, 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 226491...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Phix
Phix
with javascript_semantics include mpfr.e function juggler(integer n, bool bDigits=false) atom t0 = time(), t1 = time()+1 assert(n>=1) mpz a = mpz_init(n), h = mpz_init(n) integer l = 0, hi = 0 while mpz_cmp_si(a,1)!=0 do if mpz_odd(a) then mpz_pow_ui(a,a,3)...
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).
#Apex
Apex
class TestClass{ String foo {get;set;} Integer bar {get;set;} }   TestClass testObj = new TestClass(); testObj.foo = 'ABC'; testObj.bar = 123;   String serializedString = JSON.serialize(testObj); TestClass deserializedObject = (TestClass)JSON.deserialize(serializedString, TestClass.class);   //"testObj.foo == 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).
#Arturo
Arturo
print read.json {{ "foo": 1, "bar": [10, "apples"] }}   object: #[ name: "john" surname: "doe" address: #[ number: 10 street: "unknown" country: "Spain" ] married: false ]   print write.json ø object
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. ...
#Commodore_BASIC
Commodore BASIC
5 rem joystick - commodore vic-20 (expanded) 6 rem for rosetta code 10 print chr$(147);:poke 37154,peek(37154) and 127 15 j1=37137:j2=37152:sc=4118:co=37910:x=11:y=11 20 poke sc+x+y*22,43:poke co+x+y*22,0 25 j=(not peek(j1) and28)/4 30 j=j+(not peek(j1) and32)/2 35 j=j+(not peek(j2) and128)/16 40 print chr$(19);"joy: "...
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. ...
#Delphi
Delphi
  unit uMain;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls;   type TForm1 = class(TForm) tmr1: TTimer; lblPosition: TLabel; procedure tmr1Timer(Sender: TObject); procedure FormPaint(Sender: TObject); private { Private...
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...
#Julia
Julia
ENV["NN_DEBUG"] = true # or change DEBUG = true in NearestNeighbors.jl file   using NearestNeighbors   const data = [[2, 3] [5, 4] [9, 6] [4, 7] [8, 1] [7, 2]]   NearestNeighbors.reset_stats() const kdtree = KDTree(Float64.(data)) const indexpoint = [9,2] idx, dist = knn(kdtree, indexpoint, 1) println("Wikipedia exampl...
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...
#Kotlin
Kotlin
// version 1.1.51   import java.util.Random   typealias Point = DoubleArray   fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()   class HyperRect (val min: Point, val max: Point) { fun copy() = HyperRect(min.copyOf(), max.copyOf()) }   data class NearestNeighbor(val nearest: Point?, val dist...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h>   typedef unsigned char cell; int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };   void init_board(int w, int h, cell **a, cell **b) { int i, j, k, x, y, p = w + 4, q = h + 4; /* b is board; a is boar...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. knuth-shuffle.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 i PIC 9(8). 01 j PIC 9(8).   01 temp PIC 9(8).   LINKAGE SECTION. 78 Table-Len VA...
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...
#J
J
NB. Selection of initial centroids, per K-means++ initialCentroids =: (] , randomCentroid)^:(<:@:]`(,:@:seedCentroid@:[))~ seedCentroid =: {~ ?@# randomCentroid =: [ {~ [: wghtProb [: <./ distance/~ distance =: +/&.:*:@:-"1 NB. Extra credit #3 (N-dimensional is the sa...
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...
#Kotlin
Kotlin
// Version 1.2.40   import java.io.File   fun main(args: Array<String>) { val r = Regex("""\s+""") println("Those earthquakes with a magnitude > 6.0 are:\n") File("data.txt").forEachLine { if (it.split(r)[2].toDouble() > 6.0) println(it) } }
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...
#Lua
Lua
-- arg[1] is the first argument provided at the command line for line in io.lines(arg[1] or "data.txt") do -- use data.txt if arg[1] is nil magnitude = line:match("%S+$") if tonumber(magnitude) > 6 then print(line) end end
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. JULIA-SET-PROGRAM. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-COMPLEX-CONSTANT. 05 C-REAL PIC S9V999. 05 C-IMAGINARY PIC S9V999. 01 WS-ARGAND-PLANE. 05 X PIC S9(9)V999. 05 Y PIC S9(9)V999. 01 WS-COMPLEX-VARIA...
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...
#MiniZinc
MiniZinc
  %Knapsack problem/Unbounded. Nigel Galloway, August 13th., 2021 enum Items ={panacea,ichor,gold}; array[Items] of float: weight =[0.3,0.2,2.0]; constraint sum(n in Items)(take[n]*weight[n])<=25.0; array[Items] of int: value =[3000,1800,2500]; array[Items] of float: volume =[0.025,0.01...
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...
#M4
M4
divert(-1) define(`set2d',`define(`$1[$2][$3]',`$4')') define(`get2d',`defn(`$1[$2][$3]')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')   define(`min', `define(`ma',eval($1))`'define(`mb',eval($2))`'ifelse(eval(ma<mb),1,ma,mb)')...
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...
#PowerShell
PowerShell
  do { $keyPress = [System.Console]::ReadKey() } until ($keyPress.Key -eq "Y" -or $keyPress.Key -eq "N")   $keyPress | Format-Table -AutoSize  
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...
#PureBasic
PureBasic
PrintN("Press Y or N to continue")   Repeat ; Get the key being pressed, or a empty string. Key$=UCase(Inkey()) ; ; To Reduce the problems with an active loop ; a Delay(1) will release the CPU for the rest ; of this quanta if no key where pressed. Delay(1) Until Key$="Y" Or Key$="N" PrintN("The response...
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...
#Nim
Nim
import algorithm import strformat   type Item = object name: string weight: float price: float unitPrice: float   var items = @[Item(name: "beef", weight: 3.8, price: 36.0), Item(name: "pork", weight: 5.4, price: 43.0), Item(name: "ham", weight: 3.6, price: 90.0), Item(...
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...
#PicoLisp
PicoLisp
(de *Items ("map" 9 150 1) ("compass" 13 35 1) ("water" 153 200 3) ("sandwich" 50 60 2) ("glucose" 15 60 2) ("tin" 68 45 3) ("banana" 27 60 3) ("apple" 39 40 3) ("cheese" 23 30 1) ("beer" 52 10 3) ("suntan cream" 11 ...
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...
#Erlang
Erlang
  PROGRAM GOTO_ERR   LABEL 99,100   PROCEDURE P1 INPUT(I) IF I=0 THEN GOTO 99 END IF END PROCEDURE   PROCEDURE P2 99: PRINT("I'm in procdedure P2") END PROCEDURE   BEGIN 100: INPUT(J) IF J=1 THEN GOTO 99 END IF IF J<>0 THEN GOTO 100 END IF END PROGRAM  
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...
#BBC_BASIC
BBC BASIC
HIMEM = PAGE + 8000000 nItems% = 22 maxWeight% = 400   DIM Tag{ivalue%, list%(nItems%-1), lp%} DIM items{(nItems%-1)name$, weight%, ivalue%} FOR item% = 0 TO nItems%-1 READ items{(item%)}.name$, items{(item%)}.weight%, items{(item%)}.ivalue% NEXT   DATA "map", 9, ...
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. ...
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   for /l %%i in (1,1,9999) do ( title Processing - %%i call:kaprekar %%i )   pause>nul exit /b   :kaprekar set num=%1 if %num% leq 0 exit /b set /a num2=%num%*%num%   if %num2% leq 9 ( if %num2%==%num% ( echo %num% exit /b ) else ( exit /b ) )   call:str...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Python
Python
from math import isqrt   def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Quackery
Quackery
[ dip number$ over size - space swap of swap join echo$ ] is recho ( n n --> )   [ 1 & ] is odd ( n --> b )   [ dup dup * * ] is cubed ( n --> n )   [ dup 1 [ 2dup > while + 1 >> 2dup / again ] drop nip ] ...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Raku
Raku
use Lingua::EN::Numbers; sub juggler (Int $n where * > 0) { $n, { $_ +& 1 ?? .³.&isqrt !! .&isqrt } … 1 }   sub isqrt ( \x ) { my ( $X, $q, $r, $t ) = x, 1, 0 ; $q +<= 2 while $q ≤ $X ; while $q > 1 { $q +>= 2; $t = $X - $r - $q; $r +>= 1; if $t ≥ 0 { $X = $t; $r += $q } } $r }   say " ...
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).
#Bracmat
Bracmat
put$(jsn$(get$("input.json",JSN)),"output.JSN,NEW)
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).
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <yajl/yajl_tree.h> #include <yajl/yajl_gen.h>   static void print_callback (void *ctx, const char *str, size_t len) { FILE *f = (FILE *) ctx; fwrite (str, 1, len, f); }   static void check_status (yajl_gen_status status) { if (status != yajl_gen_...
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. ...
#FreeBASIC
FreeBASIC
Screen 12   Dim As Single x, y Dim As Integer buttons, result   Const JoystickID = 0   'This line checks to see if the joystick is ok. If Getjoystick(JoystickID, buttons, x, y) Then Print "Joystick doesn't exist or joystick error." Print !"\nPress any key to continue." Sleep End End If   Do result ...
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. ...
#Go
Go
package main   import ( "fmt" "github.com/nsf/termbox-go" "github.com/simulatedsimian/joystick" "log" "os" "strconv" "time" )   func printAt(x, y int, s string) { for _, r := range s { termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault) x++ } }   func...
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...
#Nim
Nim
type   Point[Dim: static Natural; T: SomeNumber] = array[Dim, T]   KdNode[Dim: static Natural; T: SomeNumber] = ref object x: Point[Dim, T] left, right: KdNode[Dim, T]     func toKdNodes[N, Dim: static Natural; T](a: array[N, array[Dim, T]]): array[N, KdNode[Dim, T]] = ## Create an array of KdNodes from a...
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...
#Phix
Phix
-- demo\rosetta\kd_tree.exw with javascript_semantics enum X,LEFT,RIGHT -- (keeping the IDX on each node too would not be a bad idea..) -- (the code below deduces it from the (unbalanced) tree depth) sequence kd_nodes -- nb probably not best coding style function sqdist(sequence p,q) re...
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...
#C.23
C#
using System; using System.Collections.Generic;   namespace prog { class MainClass { const int N = 8;   readonly static int[,] moves = { {+1,-2},{+2,-1},{+2,+1},{+1,+2}, {-1,+2},{-2,+1},{-2,-1},{-1,-2} }; struct ListMoves { public int x, y; public ListMoves( int _x, int _...
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...
#CoffeeScript
CoffeeScript
knuth_shuffle = (a) -> n = a.length while n > 1 r = Math.floor(n * Math.random()) n -= 1 [a[n], a[r]] = [a[r], a[n]] a   counts = "1,2,3": 0 "1,3,2": 0 "2,1,3": 0 "2,3,1": 0 "3,1,2": 0 "3,2,1": 0   for i in [1..100000] counts[knuth_shuffle([ 1, 2, 3 ]).join(",")] += 1   for key, val of c...
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...
#Java
Java
  import java.util.Random;   public class KMeansWithKpp{ // Variables Needed public Point[] points; public Point[] centroids; Random rand; public int n; public int k;   // hide default constructor private KMeansWithKpp(){ }   KMeansWithKpp(Point[] p, int clusters){ points = p; n = p.length; ...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Find_Magnitude { data$={8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 1/23/4567 EdgeCase1 6 1/24/4567 EdgeCase2 6.0 1/25/4567 EdgeCase3 6.1 } Open "data.txt" for output as F Print #F, data$; Close...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Import["data.txt", "Table"] // Select[Last /* GreaterThan[6]]
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...
#Nim
Nim
import strscans   for line in "data.txt".lines: var date, name: string var magnitude: float if scanf(line, "$+ $s$+ $s$f", date, name, magnitude): if magnitude > 6: echo line # else wrong line: ignore.
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...
#Perl
Perl
perl -n -e '/(\S+)\s*$/ and $1 > 6 and print' data.txt