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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make do test := <<1, 2>> io.put_string ("Initial: ") across test as t loop io.put_string (t.item.out + " ") end test := shuffle (test) io.new_line io.put_string ("Shuffled: ") across test as t loop ...
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...
#Racket
Racket
  #lang racket (require racket/dict math/distributions)   ;; Divides the set of points into k clusters ;; using the standard k-means clustering algorithm (define (k-means data k #:initialization (init k-means++)) (define (iteration centroids) (map centroid (clusterize data centroids))) (fixed-poin...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#JavaScript
JavaScript
  var maxIterations = 450, minX = -.5, maxX = .5, minY = -.5, maxY = .5, wid, hei, ctx, jsX = 0.285, jsY = 0.01;   function remap( x, t1, t2, s1, s2 ) { var f = ( x - t1 ) / ( t2 - t1 ), g = f * ( s2 - s1 ) + s1; return g; } function getColor( c ) { var r, g, b, p = c / 32, l = ~~( ...
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Prolog
Prolog
:- use_module(library(simplex)).   % tuples (name, Explantion, Value, weights, volume). knapsack :- L =[( panacea, 'Incredible healing properties', 3000, 0.3, 0.025), ( ichor, 'Vampires blood', 1800, 0.2, 0.015), ( gold , 'Shiney shiney', 2500, 2.0, 0.002)],   gen_state(S0), l...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Wren
Wren
import "io" for Stdin, Stdout   Stdin.isRaw = true // input is neither echoed nor buffered in this mode   System.print("Press Y or N") Stdout.flush()   var byte while ((byte = Stdin.readByte()) && !"YNyn".bytes.contains(byte)) {} var yn = String.fromByte(byte) System.print(yn)   Stdin.isRaw = false
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations loop [OpenI(1); \flush any pending keystroke case ChIn(1) of \get keystroke ^Y,^y: Text(0, "yes"); ^N,^n: Text(0, "no"); $1B: quit \Esc key terminates program other ChOut(0, 7\b...
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...
#PureBasic
PureBasic
Structure item name.s weight.f ;units are kilograms (kg) Value.f vDensity.f ;the density of the value, i.e. value/weight, and yes I made up the term ;) EndStructure   #maxWeight = 15 Global itemCount = 0 ;this will be increased as needed to match actual count Global Dim items.item(itemCount)   Procedure addIt...
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...
#Tcl
Tcl
# The list of items to consider, as list of lists set items { {map 9 150 1} {compass 13 35 1} {water 153 200 2} {sandwich 50 60 2} {glucose 15 60 2} {tin 68 45 3} {banana 27 60 3} {apple 39 40 3} {cheese 23 30 1} {beer 52 10 3} {{suntan cream} 11 70 1} ...
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...
#Lingo
Lingo
on foo abort() end   on bar () foo() put "This will never be printed" end
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...
#Logtalk
Logtalk
-- Forward jump goto skip_print print "won't print" ::skip_print::   -- Backward jump ::loop:: print "infinite loop" goto loop   -- Labels follow the same scoping rules as local variables, but with no equivalent of upvalues goto next do ::next:: -- not visible to above goto print "won't print" end ::next:: -- 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...
#Dart
Dart
List solveKnapsack(items, maxWeight) { int MIN_VALUE=-100; int N = items.length; // number of items int W = maxWeight; // maximum weight of knapsack   List profit = new List(N+1); List weight = new List(N+1);   // generate random instance, items 1..N for(int n = 1; n<=N; n++) { profit[n] = items[n-1]...
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. ...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function map kaprekarp (n) ... $ m=n*n; $ p=10; $ repeat $ i=floor(m/p); $ j=mod(m,p); $ if j==0 then return 0; endif; $ if i+j==n then return 1; endif; $ p=p*10; $ until p>m; $ end; $ return 0; $endfunction >nonzeros(kaprekarp(1:100000)) [ 1 9 45 55 99 297 703 999 2223 2728 4879 5...
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. ...
#F.23
F#
  // Count digits in number let digits x = let rec digits' p x = if 10.**p > x then p else digits' (p + 1.) x digits' 1. x     // Is n a Kaprekar number? let isKaprekar n = // Reference: http://oeis.org/A006886 // Positive numbers n such that n=q+r // And n^2=q*10^m+r, // for some 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).
#F.23
F#
  open Newtonsoft.Json type Person = {ID: int; Name:string} let xs = [{ID = 1; Name = "First"} ; { ID = 2; Name = "Second"}]   let json = JsonConvert.SerializeObject(xs) json |> printfn "%s"   let xs1 = JsonConvert.DeserializeObject<Person list>(json) xs1 |> List.iter(fun x -> printfn "%i  %s" x.ID x.Name)  
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).
#Factor
Factor
  USING: json.writer json.reader ;   SYMBOL: foo   ! Load a JSON string into a data structure "[[\"foo\",1],[\"bar\",[10,\"apples\"]]]" json> foo set     ! Create a new data structure and serialize into JSON { { "blue" { "ocean" "water" } } >json  
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...
#FreeBASIC
FreeBASIC
  Dim Shared As Integer tamano, xc, yc, nm Dim As Integer f, qm, nmov, n = 0 Dim As String posini   Cls : Color 11 Input "Tamaño tablero: ", tamano Input "Posicion inicial: ", posini   Dim As Integer x = Asc(Mid(posini,1,1))-96 Dim As Integer y = Val(Mid(posini,2,1)) Dim Shared As Integer tablero(tamano,tamano), dx(8)...
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...
#Elena
Elena
import system'routines; import extensions;   const int MAX = 10;   extension randomOp { randomize() { var max := self.Length;   for(int i := 0, i < max, i += 1) { var j := randomGenerator.eval(i,max);   self.exchange(i,j) };   ^ self } }   publ...
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...
#Raku
Raku
sub postfix:«-means++»(Int $K) { return sub (@data) { my @means = @data.pick; until @means == $K { my @cumulD2 = [\+] @data.map: -> $x { min @means.map: { abs($x - $_)**2 } } my $rand = rand * @cumulD2[*-1]; @means.push: @data[ ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#jq
jq
# Example values: # $re : -0.8 # $im : 0.156 {} | range(-100; 101; 10) as $v | (( range (-280; 281; 10) as $h | .x = $h / 200 | .y = $v / 100 | .plot = "#" | .i = 0 | until (.i == 50 or .plot == "."; .i += 1 | .z_real = ((.x * .x) - (.y * .y) + $re) | .z_imag = ((.x * .y * 2) ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Julia
Julia
  function iter(z,c) n = 0 while (abs2(z)<4) z = z^2+c ; n+=1 end return n end   coord(i,j,w,h,a,b) = 2*a*(i-1)/(w-1) - a + im * (2*b*(j-1)/(h-1) - b)   palette(n) = string(min(3n,255)," ", min(n,255)," ", 0);   julia(c) = (w,h,a,b,i,j) -> palette(iter(coord(i,j,w,h,a,b), c))   writeppm(f; width=600,height=300,a...
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...
#PureBasic
PureBasic
Define.f TotalWeight, TotalVolyme Define.i maxPanacea, maxIchor, maxGold, maxValue Define.i i, j ,k Dim n.i(2)   Enumeration #Panacea #Ichor #Gold #Sack #Current EndEnumeration   Structure Bounty value.i weight.f volyme.f EndStructure   Dim Item.Bounty(4) CopyMemory(?panacea,@Item(#Panacea),SizeOf(Boun...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Z80_Assembly
Z80 Assembly
wait_for_key_input: call &BB06 ;bios call, waits until key is pressed, returns key's ASCII code into A and %11011111 ;converts to upper case cp 'Y' jp z,User_Chose_Yes cp 'N' jp z,User_Chose_No jp wait_for_key_input   User_Chose_Yes: ;your code for what happens when the user types "Y" goes here ret...
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...
#Python
Python
# NAME, WEIGHT, VALUE (for this weight) 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), ...
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...
#Ursala
Ursala
#import std #import flo #import lin   items = # name: (weight,value,limit)   < '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), 's...
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...
#Lua
Lua
-- Forward jump goto skip_print print "won't print" ::skip_print::   -- Backward jump ::loop:: print "infinite loop" goto loop   -- Labels follow the same scoping rules as local variables, but with no equivalent of upvalues goto next do ::next:: -- not visible to above goto print "won't print" end ::next:: -- 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...
#EasyLang
EasyLang
name$[] = [ "map" "compass" "water" "sandwich" "glucose" "tin" "banana" "apple" "cheese" "beer" "suntan cream" "camera" "t-shirt" "trousers" "umbrella" "waterproof trousers" "waterproof overclothes" "note-case" "sunglasses" "towel" "socks" "book" ] weight[] = [ 9 13 153 50 15 68 27 39 23 52 11 32 24 48 73 42 43 22 7 18...
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. ...
#Factor
Factor
USING: io kernel lists lists.lazy locals math math.functions math.ranges prettyprint sequences ;   :: kaprekar? ( n -- ? ) n sq :> sqr 1 lfrom [ 10 swap ^ ] lmap-lazy [ n > ] lfilter [ sqr swap mod n < ] lwhile list>array [ 1 - sqr n - swap mod zero? ] any? n 1 = or ;   1,000,000 [1,b] [...
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. ...
#Forth
Forth
: square ( n - n^2) dup * ;   \ Return nonzero if n is a Kaprekar number for tens, where tens is a \ nonzero power of base. : is-kaprekar? ( tens n n^2 - t) rot /mod over >r + = r> and ;   \ If n is a Kaprekar number, return is the power of base for which it \ is Kaprekar. If n is not a Kaprekar number, re...
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).
#Fantom
Fantom
  using util   class Json { public static Void main () { Str input := """{"blue": [1, 2], "ocean": "water"}""" Map jsonObj := JsonInStream(input.in).readJson   echo ("Value for 'blue' is: " + jsonObj["blue"]) jsonObj["ocean"] = ["water":["cold", "blue"]] Map ocean := jsonObj["ocean"] echo ("...
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).
#Forth
Forth
https://github.com/DouglasBHoffman/FMS2
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
C----------------------------------------------------------------------- C C Find Knight’s Tours. C C Using Warnsdorff’s heuristic, find multiple solutions. C Optionally accept only closed tours. C C This program is migrated from my implementation for ATS/Postiats. C Arrays with dimension 1:64 take ...
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...
#Elixir
Elixir
defmodule Knuth do def shuffle( inputs ) do n = length( inputs ) {[], acc} = Enum.reduce( n..1, {inputs, []}, &random_move/2 ) acc end   defp random_move( n, {inputs, acc} ) do item = Enum.at( inputs, :rand.uniform(n)-1 ) {List.delete( inputs, item ), [item | acc]} end end   seq = Enum.to_li...
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...
#Rust
Rust
extern crate csv; extern crate getopts; extern crate gnuplot; extern crate nalgebra; extern crate num; extern crate rand; extern crate rustc_serialize; extern crate test;   use getopts::Options; use gnuplot::{Axes2D, AxesCommon, Color, Figure, Fix, PointSize, PointSymbol}; use nalgebra::{DVector, Iterable}; use rand::{...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Kotlin
Kotlin
  import java.awt.* import java.awt.image.BufferedImage import javax.swing.JFrame import javax.swing.JPanel   class JuliaPanel : JPanel() { init { preferredSize = Dimension(800, 600) background = Color.white }   private val maxIterations = 300 private val zoom = 1 private val moveX =...
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...
#Python
Python
# Define consts weights <- c(panacea=0.3, ichor=0.2, gold=2.0) volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) values <- c(panacea=3000, ichor=1800, gold=2500) sack.weight <- 25 sack.volume <- 0.25 max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes))   # Some utility functions getTotalValue <- functi...
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...
#R
R
# Define consts weights <- c(panacea=0.3, ichor=0.2, gold=2.0) volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) values <- c(panacea=3000, ichor=1800, gold=2500) sack.weight <- 25 sack.volume <- 0.25 max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes))   # Some utility functions getTotalValue <- functi...
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...
#R
R
  knapsack<- function(Value, Weight, Objects, Capacity){ Fraction = rep(0, length(Value)) Cost = Value/Weight #print(Cost) W = Weight[order(Cost, decreasing = TRUE)] Obs = Objects[order(Cost, decreasing = TRUE)] Val = Value[order(Cost, decreasing = TRUE)] #print(W) RemainCap = Capacity i = 1 n = len...
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...
#Wren
Wren
import "/fmt" for Fmt   class Item { construct new(name, weight, value, count) { _name = name _weight = weight _value = value _count = count }   name { _name } weight { _weight } value { _value } count { _count } }   var items = [ Item.new("map", 9...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Module Alfa { 10 Rem this code is like basic 20 Let K%=1 30 Let A=2 40 Print "Begin" 50 On K% Gosub 110 60 If A=2 then 520 70 For I=1 to 10 80 if i>5 then exit for 120 90 Gosub 110 ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
goto mylabel;
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...
#EchoLisp
EchoLisp
  (require 'struct) (require 'hash) (require 'sql)   (define H (make-hash)) (define T (make-table (struct goodies (name poids valeur )))) (define-syntax-rule (name i) (table-xref T i 0)) (define-syntax-rule (poids i) (table-xref T i 1)) (define-syntax-rule (valeur i) (table-xref T i 2))   ;; make an unique hash-key fr...
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. ...
#Fortran
Fortran
program Karpekar_Numbers implicit none   integer, parameter :: i64 = selected_int_kind(18) integer :: count   call karpekar(10000_i64, .true.) write(*,*) call karpekar(1000000_i64, .false.)   contains   subroutine karpekar(n, printnums)   integer(i64), intent(in) :: n logical, intent(in) :: printnums ...
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).
#Fortran
Fortran
{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" }, { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ] }
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).
#FunL
FunL
println( eval('{ "foo": 1, "bar": [10, "apples"] }') )
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...
#Fortran
Fortran
C----------------------------------------------------------------------- C C Find Knight’s Tours. C C Using Warnsdorff’s heuristic, find multiple solutions. C Optionally accept only closed tours. C C This program is migrated from my implementation for ATS/Postiats. C Arrays with dimension 1:64 take ...
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...
#Erlang
Erlang
  -module( knuth_shuffle ).   -export( [list/1] ).   list( Inputs ) -> N = erlang:length( Inputs ), {[], Acc} = lists:foldl( fun random_move/2, {Inputs, []}, lists:reverse(lists:seq(1, N)) ), Acc.       random_move( N, {Inputs, Acc} ) -> Item = lists:nth( random:uniform(N), Inputs ), {lists:delete(Item, Inputs), [...
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...
#Scheme
Scheme
  (import (scheme base) ; headers for R7RS Scheme (scheme file) (scheme inexact) (scheme write) (srfi 1 lists) (srfi 27 random-bits))   ;; calculate euclidean distance between points, any dimension (define (euclidean-distance pt1 pt2) (sqrt (apply + (map (lambda (x y) (square (...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Lua
Lua
local cmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "$", "@" } for y = -1.0, 1.0, 0.05 do for x = -1.5, 1.5, 0.025 do local zr, zi, i = x, y, 0 while i < 100 do zr, zi = zr*zr - zi*zi - 0.79, zr * zi * 2 + 0.15 if (zr*zr + zi*zi > 4) then break else i = i + 1 end end io.write(c...
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...
#Racket
Racket
  #lang racket   (struct item (name explanation value weight volume) #:prefab)   (define items (list (item "panacea (vials of)" "Incredible healing properties" 3000 0.3 0.025) (item "ichor (ampules of)" "Vampires blood" 1800 0.2 0.015) (item "gold (bars)" "Shiney shiney" ...
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...
#Raku
Raku
class KnapsackItem { has $.volume; has $.weight; has $.value; has $.name;   method new($volume,$weight,$value,$name) { self.bless(:$volume, :$weight, :$value, :$name) } };   my KnapsackItem $panacea .= new: 0.025, 0.3, 3000, "panacea"; my KnapsackItem $ichor .= new: 0.015, 0.2, 1800, "ichor"; my Knaps...
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...
#Racket
Racket
#lang racket (define shop-inventory '((beef 3.8 36) (pork 5.4 43) (ham 3.6 90) (greaves 2.4 45) (flitch 4.0 30) (brawn 2.5 56) (welt 3.7 67) (salami 3.0 95) (sausage 5.9 98)))     (define (continuous-knapsack shop sack sack-capacity sack-total-value)  ;; solved by lo...
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...
#zkl
zkl
fcn addItem(old,[(nm,w,v,c)]){ // old:list:(cost of:,(name,#,...)) [1..c].reduce(fcn(list,i,nm,w,v,old){ wi,left,right:=w*i,list[0,wi],list[wi,*]; new:=old.apply('wrap([(val,itms)]){ T(val + v*i,itms.append(nm,i)) }); left.extend(right.zipWith( // inc fcn([(v1,_)]a,[(v2,_)]b){ v1>v2 and a or...
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...
#MBS
MBS
goto mylabel;
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
БП XX
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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make local knapsack: KNAPSACKZEROONE do create knapsack.make (400) knapsack.add_item (create {ITEM}.make ("", 0, 0)) knapsack.add_item (create {ITEM}.make ("map", 9, 150)) knapsack.add_item (create {ITEM}.make ("compass", 13, 3...
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. ...
#FreeBASIC
FreeBASIC
' version 04-12-2016 ' compile with: fbc -s console   ' define true and false for older versions #Ifndef TRUE #Define FALSE 0 #Define TRUE Not FALSE #EndIf   #Define max 1000000 ' maximum for number to be tested   Function kaprekar(n As ULong) As ULong   If n = 1 Then Return TRUE   Dim As ULong x, p1, p2 ...
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).
#Go
Go
package main   import "encoding/json" import "fmt"   func main() { var data interface{} err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data) if err == nil { fmt.Println(data) } else { fmt.Println(err) }   sample := map[string]interface{}{ "blue": []int...
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).
#Gosu
Gosu
  gw.lang.reflect.json.Json#fromJson( String json ) : javax.script.Bindings  
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   // input, 0-based start position const startRow = 0 const startCol = 0   func main() { rand.Seed(time.Now().Unix()) for !knightTour() { } }   var moves = []struct{ dr, dc int }{ {2, 1}, {2, -1}, {1, 2}, {1, -2}, {-1, 2}, ...
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...
#ERRE
ERRE
PROGRAM KNUTH_SHUFFLE   CONST CARDS%=52   DIM PACK%[CARDS%]   BEGIN RANDOMIZE(TIMER) FOR I%=1 TO CARDS% DO PACK%[I%]=I% END FOR FOR N%=CARDS% TO 2 STEP -1 DO SWAP(PACK%[N%],PACK%[1+INT(N%*RND(1))]) END FOR FOR I%=1 TO CARDS% DO PRINT(PACK%[I%];) END FOR PRINT END PROGRAM  
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...
#SequenceL
SequenceL
  import <Utilities/Sequence.sl>; import <Utilities/Random.sl>; import <Utilities/Math.sl>; import <Utilities/Conversion.sl>;   Point ::= (x : float, y : float); Pair<T1, T2> ::= (first : T1, second : T2);   W := 400; H := 400;   // ------------ Utilities -------------- distance(a, b) := (a.x-b.x)^2 + (a.y-b.y)^2;   ne...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
JuliaSetPoints[-0.77 + 0.22 I, "ClosenessTolerance" -> 0.01]
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Nim
Nim
import lenientops import imageman   const W = 800 H = 600 Zoom = 1 MaxIter = 255 MoveX = 0 MoveY = 0 Cx = -0.7 Cy = 0.27015   var colors: array[256, ColorRGBU] for n in byte.low..byte.high: colors[n] = ColorRGBU [n shr 5 * 36, (n shr 3 and 7) * 36, (n and 3) * 85]   var image = initImage[ColorRGBU](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...
#REXX
REXX
/*REXX program solves the knapsack/unbounded problem: highest value, weight, and volume.*/   /* value weight volume */ maxPanacea= 0 /* ═══════ ══════ ══════ */ maxIchor = 0; panacea.$ = 3000  ; ...
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...
#Raku
Raku
class KnapsackItem { has $.name; has $.weight is rw; has $.price is rw; has $.ppw;   method new (Str $n, Rat $w, Int $p) { self.bless(:name($n), :weight($w), :price($p), :ppw($w/$p)) }   method cut-maybe ($max-weight) { return False if $max-weight > $.weight; $.price = $max-weight / $.ppw; ...
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...
#MUMPS
MUMPS
 ;Go to a label within the program file Goto Label  ;Go to a line below a label Goto Label+lines  ;Go to a different file Goto ^Routine  ;Go to a label within a different file Goto Label^Routine  ;and with offset Goto Label+2^Routine  ;  ;The next two goto commands will both return error M45 in ANSI MUMPS. NoNo F...
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...
#Neko
Neko
$print("start\n") $goto(skip) $print("Jumped over") skip: $print("end\n")
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...
#Elixir
Elixir
defmodule Knapsack do def solve([], _total_weight, item_acc, value_acc, weight_acc), do: {item_acc, value_acc, weight_acc} def solve([{_item, item_weight, _item_value} | t], total_weight, item_acc, value_acc, weight_acc) when item_weight > total_weight, do: so...
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. ...
#GAP
GAP
IsKaprekar := function(n) local a, b, p, q; if n = 1 then return true; fi; q := n*n; p := 10; while p < q do a := RemInt(q, p); b := QuoInt(q, p); if a > 0 and a + b = n then return true; fi; p := p*10; od; return false; end;   Filtered([1 .. 10000], IsKaprekar); # [ 1, 9, 45, 55, 99, 297, 703, 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. ...
#Go
Go
package main   import ( "fmt" "strconv" )   func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 }   nn, power := n*n, uint64(1) for power <= nn { power *= base order++ }   power /= base order-- for ; power > 1; pow...
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).
#Groovy
Groovy
def slurper = new groovy.json.JsonSlurper() def result = slurper.parseText(''' { "people":[ {"name":{"family":"Flintstone","given":"Frederick"},"age":35,"relationships":{"wife":"people[1]","child":"people[4]"}}, {"name":{"family":"Flintstone","given":"Wilma"},"age":32,"relationships":{"husband":"peo...
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).
#Halon
Halon
$data = json_decode(''{ "foo": 1, "bar": [10, "apples"] }'');   $sample = ["blue" => [1, 2], "ocean" => "water"]; $jsonstring = json_encode($sample, ["pretty_print" => true]);
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...
#Haskell
Haskell
import Data.Bifunctor (bimap) import Data.Char (chr, ord) import Data.List (intercalate, minimumBy, sort, (\\)) import Data.Ord (comparing) import Control.Monad (join)   ---------------------- KNIGHT'S TOUR ---------------------   type Square = (Int, Int)   knightTour :: [Square] -> [Square] knightTour moves | null p...
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...
#Euphoria
Euphoria
sequence cards cards = repeat(0,52) integer card,temp   puts(1,"Before:\n") for i = 1 to 52 do cards[i] = i printf(1,"%d ",cards[i]) end for   for i = 52 to 1 by -1 do card = rand(i) if card != i then temp = cards[card] cards[card] = cards[i] cards[i] = temp end if end for   ...
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...
#Tcl
Tcl
package require Tcl 8.5 package require math::constants math::constants::constants pi proc tcl::mathfunc::randf m {expr {$m * rand()}}   proc genXY {count radius} { global pi for {set i 0} {$i < $count} {incr i} { set ang [expr {randf(2 * $pi)}] set r [expr {randf($radius)}] lappend pt [list [expr {$r*cos($a...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Perl
Perl
use Imager;   my($w, $h, $zoom) = (800, 600, 1); my $img = Imager->new(xsize => $w, ysize => $h, channels => 3);   my $maxIter = 255; my ($cX, $cY) = (-0.7, 0.27015); my ($moveX, $moveY) = (0, 0);   my $color = Imager::Color->new('#000000');   foreach my $x (0 .. $w - 1) { foreach my $y (0 .. $h - 1) { my $...
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...
#Ruby
Ruby
KnapsackItem = Struct.new(:volume, :weight, :value) panacea = KnapsackItem.new(0.025, 0.3, 3000) ichor = KnapsackItem.new(0.015, 0.2, 1800) gold = KnapsackItem.new(0.002, 2.0, 2500) maximum = KnapsackItem.new(0.25, 25, 0)   max_items = {} for item in [panacea, ichor, gold] max_items[item] = [(maximum.volume/it...
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...
#REXX
REXX
/*REXX pgm solves the continuous burglar's knapsack problem; items with weight and value*/ @.= /*═══════ name weight value ══════*/ @.1 = 'flitch 4 30 ' @.2 = 'beef 3.8 36 ' @.3 = 'pork 5.4 43 ' ...
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...
#Nim
Nim
  block outer: for i in 0..1000: for j in 0..1000: if i + j == 3: break outer
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...
#Oforth
Oforth
  ; recursion: (let loop ((n 10)) (unless (= n 0) (loop (- n 1))))   ; continuation (call/cc (lambda (break) (let loop ((n 10)) (if (= n 0) (break 0)) (loop (- n 1)))))   (print "ok.")  
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...
#Emacs_Lisp
Emacs Lisp
  (defun ks (max-w items) (let ((cache (make-vector (1+ (length items)) nil))) (dotimes (n (1+ (length items))) (setf (aref cache n) (make-hash-table :test 'eql))) (defun ks-emb (spc items) (let ((slot (gethash spc (aref cache (length items))))) (cond ((null items) (list 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. ...
#Groovy
Groovy
class Kaprekar { private static String[] splitAt(String str, int idx) { String[] ans = new String[2] ans[0] = str.substring(0, idx) if (ans[0] == "") ans[0] = "0" //parsing "" throws an exception ans[1] = str.substring(idx) return ans }   static void main(String[] arg...
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).
#Harbour
Harbour
LOCAL arr hb_jsonDecode( '[101,[26,"Test1"],18,false]', @arr )
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).
#Haskell
Haskell
  {-# LANGUAGE OverloadedStrings #-}   import Data.Aeson import Data.Attoparsec (parseOnly) import Data.Text import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.ByteString.Char8 as S   testdoc = object [ "foo" .= (1 :: Int), "bar" .= ([1.3, 1.6, 1.9] :: [Double]), "baz" .= ("some st...
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...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) ShowTour(KnightsTour(Board(8))) end   procedure KnightsTour(B,sq,tbrk,debug) #: Warnsdorff’s algorithm   /B := Board(8) # create 8x8 board if none given /sq := ?B.files || ?B.ranks # random initial position (default) sq2fr(sq,B) ...
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...
#F.23
F#
open System   let FisherYatesShuffle (initialList : array<'a>) = // ' let availableFlags = Array.init initialList.Length (fun i -> (i, true)) // Which items are available and their indices let rnd = new Random() let nextI...
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...
#Wren
Wren
import "random" for Random import "/dynamic" for Struct import "/fmt" for Fmt   var Point = Struct.create("Point", ["x", "y", "group"])   var r = Random.new() var hugeVal = Num.infinity   var RAND_MAX = Num.maxSafeInteger var PTS = 100000 var K = 11 var W = 400 var H = 400   var rand = Fn.new { r.int(RAND_MAX) } var ra...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Phix
Phix
-- -- demo\rosetta\Julia_set.exw -- ========================== -- -- Interactive gui (zoom/pan incomplete). -- --with javascript_semantics -- not quite yet: without js -- [DEV] IupValuator, IupImageRGB include pGUI.e constant title = "Julia set" Ihandle dlg, cxv, cxl, cyv, cyl, ispin, pspin, clrzn, label, bb, redra...
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...
#SAS
SAS
data one; wtpanacea=0.3; wtichor=0.2; wtgold=2.0; volpanacea=0.025; volichor=0.015; volgold=0.002; valpanacea=3000; valichor=1800; valgold=2500; maxwt=25; maxvol=0.25;   /* we can prune the possible selections */ maxpanacea = floor(min(maxwt/wtpanacea, maxvol/volpanacea)); maxichor = floor(...
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...
#Ruby
Ruby
items = [ [:beef , 3.8, 36], [:pork , 5.4, 43], [:ham , 3.6, 90], [:greaves, 2.4, 45], [:flitch , 4.0, 30], [:brawn , 2.5, 56], [:welt , 3.7, 67], [:salami , 3.0, 95], [:sausage, 5.9, 98] ].sort_by{|item, weight, price| -price / w...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Ol
Ol
  ; recursion: (let loop ((n 10)) (unless (= n 0) (loop (- n 1))))   ; continuation (call/cc (lambda (break) (let loop ((n 10)) (if (= n 0) (break 0)) (loop (- n 1)))))   (print "ok.")  
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...
#Erlang
Erlang
    -module(knapsack_0_1).   -export([go/0, solve/5]).   -define(STUFF, [{"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, ...
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. ...
#Haskell
Haskell
import Text.Printf (printf) import Data.Maybe (mapMaybe) import Numeric (showIntAtBase)   kaprekars :: Integer -> Integer -> [(Integer, Integer, Integer)] kaprekars base top = (1, 0, 1) : mapMaybe kap (filter res [2 .. top]) where res x = x * (x - 1) `mod` (base - 1) == 0 kap n = getSplit $ takeWh...
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).
#Hoon
Hoon
:-  %say |= [^ [in=@tas ~] ~] :-  %noun =+ obj=(need (poja in))  :: try parse to json =+ typ=$:(name=@tas age=@ud)  :: datastructure =+ spec=(ot name/so age/ni ~):jo  :: parsing spec  ?.  ?=([%o *] obj)  :...
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).
#J
J
NB. character classes: NB. 0: whitespace NB. 1: " NB. 2: \ NB. 3: [ ] , { } : NB. 4: ordinary classes=.3<. '"\[],{}:' (#@[ |&>: i.) a. classes=.0 (I.a.e.' ',CRLF,TAB)} (]+4*0=])classes   words=:(0;(0 10#:10*".;._2]0 :0);classes)&;: NB. states: 0.0 1.1 2.1 3.1 4.1 NB. 0 whitespace 1.0 5.0 6.0 1...
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...
#J
J
NB. knight moves for each square of a (y,y) board kmoves=: monad define t=. (>,{;~i.y) +"1/ _2]\2 1 2 _1 1 2 1 _2 _1 2 _1 _2 _2 1 _2 _1 (*./"1 t e. i.y) <@#"1 y#.t )   ktourw=: monad define M=. >kmoves y p=. k=. 0 b=. 1 $~ *:y for. i.<:*:y do. b=. 0 k}b p=. p,k=. ((i.<./) +/"1 b{~j{M){j=. ({&b # ]) k{M end....
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...
#Factor
Factor
: randomize ( seq -- seq ) dup length [ dup 1 > ] [ [ iota random ] [ 1 - ] bi [ pick exchange ] keep ] while drop ;
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...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   def N = 30000; \number of points def K = 6; \number of clusters int Px(N), Py(N), Pc(N), \coordinates of points and their cluster Cx(K), Cy(K); \coordinates of centroid of cluster     func Centroid; ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#PHP
PHP
  set_time_limit(300); header("Content-Type: image/png");   class Julia {   static private $started = false;   public static function start() { if (!self::$started) { self::$started = true; new self; } }   const AXIS_REAL = 0; const AXIS_IMAGINARY = 1; const C = [-0.75, 0.1]; const RADII = [1, 0....
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...
#Scala
Scala
import scala.annotation.tailrec   object UnboundedKnapsack extends App { private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25)) private val items = Seq(Item("panacea", 3000, 0.3, 0.025), Item("ichor", 1800, 0.2, 0.015), Item("gold", 2500, 2.0, 0.002))   @tailrec private def packer(notPacked: ...