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/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...
#Run_BASIC
Run BASIC
dim name$(9) dim wgt(9) dim price(9) dim tak$(100)   name$(1) = "beef"  : wgt(1) = 3.8 : price(1) = 36 name$(2) = "pork"  : wgt(2) = 5.4 : price(2) = 43 name$(3) = "ham"  : wgt(3) = 3.6 : price(3) = 90 name$(4) = "greaves"  : wgt(4) = 2.4 : price(4) = 45 name$(5) = "flitch"  : wgt(5) = 4.0 : price(5...
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...
#PARI.2FGP
PARI/GP
sub outer { print "In outer, calling inner:\n"; inner(); OUTER: print "at label OUTER\n"; }   sub inner { print "In inner\n";   goto SKIP; # goto same block level print "This should be skipped\n"; SKIP: print "at label SKIP\n";   goto OUTER; # goto whatever OUTER label there...
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...
#Euler_Math_Toolbox
Euler Math Toolbox
  >items=["map","compass","water","sandwich","glucose", ... > "tin","banana","apple","cheese","beer","suntan creame", ... > "camera","t-shirt","trousers","umbrella","waterproof trousers", ... > "waterproof overclothes","note-case","sunglasses", ... > "towel","socks","book"]; >ws = [9,13,153,50,15,68,27,39,23,52,11,...
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. ...
#Icon_and_Unicon
Icon and Unicon
procedure is_kaprekar(n) #: return n if n is a kaprekar number if ( n = 1 ) | ( n^2 ? ( n = move(1 to *&subject-1) + (0 ~= tab(0)) | fail )) then return n end   procedure main() every write(is_kaprekar(1 to 10000)) # primary goal every (count := 0, is_kaprekar(1 to 999999), count +:= 1) ...
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).
#Java_2
Java
import com.google.gson.Gson;   public class JsonExample {   public static void main(String[] args) { Gson gson = new Gson(); String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }";   MyJsonObject obj = gson.fromJson(json, MyJsonObject.class);   System.out.println(obj.getFoo());   for(String bar : obj...
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...
#Java
Java
import java.util.*;   public class KnightsTour { private final static int base = 12; private final static int[][] moves = {{1,-2},{2,-1},{2,1},{1,2},{-1,2}, {-2,1},{-2,-1},{-1,-2}}; private static int[][] grid; private static int total;   public static void main(String[] args) { grid...
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...
#Fantom
Fantom
class Main { static Void knuthShuffle (List array) { ((array.size-1)..1).each |Int i| { r := Int.random(0..i) array.swap (i, r) } }   public static Void main () { List a := [1,2,3,4,5] knuthShuffle (a) echo (a)   List b := ["apples", "oranges", "pears", "bananas"] k...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Processing
Processing
  float cX = -0.7; float cY = 0.27015; float zx, zy; float maxIter = 300;   void setup() { size(640, 480); }   void draw() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { zx = 1.5 * (x - width / 2) / (0.5 * width); zy = (y - height / 2) / (0.5 * height); float i = maxIte...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: bounty is new struct var integer: value is 0; var float: weight is 0.0; var float: volume is 0.0; end struct;   const func bounty: bounty (in integer: value, in float: weight, in float: volume) is func result var bounty: bountyVal is bou...
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...
#Rust
Rust
fn main() { let items: [(&str, f32, u8); 9] = [ ("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), ]; let ...
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...
#Perl
Perl
sub outer { print "In outer, calling inner:\n"; inner(); OUTER: print "at label OUTER\n"; }   sub inner { print "In inner\n";   goto SKIP; # goto same block level print "This should be skipped\n"; SKIP: print "at label SKIP\n";   goto OUTER; # goto whatever OUTER label there...
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...
#F.23
F#
  //Solve Knapsack 0-1 using A* algorithm //Nigel Galloway, August 3rd., 2018 let knapStar items maxW= let l=List.length items let p=System.Collections.Generic.SortedSet<float*int*float*float*list<int>>() //H*; level; value of items taken so far; weight so far p.Add (0.0,0,0.0,0.0,[])|>ignore let H items maxW=l...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#J
J
kapbase=: 0,. [ ^ 1 + [: i. 1 + [ <.@^. >.&1 isKap=: 1 e. ] ((0 < {:"1@]) *. [ = +/"1@]) kapbase #: *:@]
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. ...
#Java
Java
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; //parsing "" throws an exception ans[1] = str.substring(idx); return ans; }   public static ...
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).
#JavaScript
JavaScript
var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');   var sample = { "blue": [1,2], "ocean": "water" }; var json_string = JSON.stringify(sample);
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).
#jq
jq
.
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...
#JavaScript
JavaScript
  class KnightTour { constructor() { this.width = 856; this.height = 856; this.cellCount = 8; this.size = 0; this.knightPiece = "\u2658"; this.knightPos = { x: 0, y: 0 }; this.ctx = null; this.step = this.width / this.cellCount; this.lastTime = 0; this.wait; this.delay; this.success; ...
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...
#Forth
Forth
include random.fs   : shuffle ( deck size -- ) 2 swap do dup i random cells + over @ over @ swap rot  ! over ! cell+ -1 +loop drop ;   : .array 0 do dup @ . cell+ loop drop ;   create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,   deck 10 2dup shuffle .array
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Python
Python
from PIL import Image   if __name__ == "__main__": w, h, zoom = 800,600,1 bitmap = Image.new("RGB", (w, h), "white") pix = bitmap.load()   cX, cY = -0.7, 0.27015 moveX, moveY = 0.0, 0.0 maxIter = 255   for x in range(w): for y in range(h): zx = 1.5*(x - w/2)/(0.5*zoom*w) + moveX zy = 1.0*(y - h/2)/(0.5*z...
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...
#Sidef
Sidef
struct KnapsackItem { Number volume, Number weight, Number value, String name, }   var items = [ KnapsackItem(25, 3, 3000, "panacea") KnapsackItem(15, 2, 1800, "ichor" ) KnapsackItem( 2, 20, 2500, "gold" ) ]   var ( max_weight = 250, max_vol = 250, vsc = 1000, wsc = 10 )...
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...
#SAS
SAS
/* create SAS data set */ data mydata; input item $ weight value; datalines; 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 ;   /* call OPTMODEL procedure in SAS/OR */ proc optmodel; /* declare se...
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...
#Phix
Phix
#ilASM{ jmp :%somelabel } ... #ilASM{ :%somelabel }
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...
#PicoLisp
PicoLisp
(de foo (N) (prinl "This is 'foo'") (printsp N) (or (=0 (dec 'N)) (run (cddr foo))) )
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...
#Factor
Factor
USING: accessors arrays fry io kernel locals make math math.order math.parser math.ranges sequences sorting ; IN: rosetta.knappsack.0-1   TUPLE: item name weight value ;   CONSTANT: items { T{ item f "map" 9 150 } T{ item f "compass" 13 35 } T{ item f "water" 153 200 } T{ item f "san...
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. ...
#JavaScript
JavaScript
function isKaprekar( n, bs ) { if ( n < 1 ) return false if ( n == 1 ) return true bs = bs || 10 var s = (n * n).toString(bs) for (var i=1, e=s.length; i<e; i+=1) { var a = parseInt(s.substr(0, i), bs) var b = parseInt(s.substr(i), bs) if (b && a + b == n) return true } return false }
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).
#Jsish
Jsish
prompt$ jsish Jsish interactive: see 'help [cmd]' # var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }'); variable # data { bar:[ 10, "apples" ], foo:1 }   # var sample = { blue: [1,2], ocean: "water" }; variable # sample { blue:[ 1, 2 ], ocean:"water" }   # puts(JSON.stringify(sample)) { "blue":[ 1, 2 ], "ocea...
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).
#Julia
Julia
# Pkg.add("JSON") ... an external library http://docs.julialang.org/en/latest/packages/packagelist/ using JSON   sample = Dict() sample["blue"] = [1, 2] sample["ocean"] = "water"   @show sample jsonstring = json(sample) @show jsonobj = JSON.parse(jsonstring)   @assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}...
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...
#Julia
Julia
using .Hidato # Note that the . here means to look locally for the module rather than in the libraries   const chessboard = """ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 """   const knightmoves = [[-2, -1], [-2, 1], [-1,...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Fortran
Fortran
program Knuth_Shuffle implicit none   integer, parameter :: reps = 1000000 integer :: i, n integer, dimension(10) :: a, bins = 0, initial = (/ (n, n=1,10) /)   do i = 1, reps a = initial call Shuffle(a) where (a == initial) bins = bins + 1 ! skew tester end do write(*, "(10(i8))") bins ! print...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Racket
Racket
  ;; Based on Mandelbrot code (GPL) from: ;; https://github.com/hebr3/Mandelbrot-Set-Racket/blob/master/Mandelbrot.v6.rkt ;; Julia set algoithm (and coloring) from: ;; http://lodev.org/cgtutor/juliamandelbrot.html ;; HSV code (GPL) based on: ;; https://github.com/takikawa/pict-utils/blob/master/pict-utils/hsv.rkt ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Raku
Raku
use Image::PNG::Portable;   my ($w, $h) = 800, 600; my $out = Image::PNG::Portable.new: :width($w), :height($h);   my $maxIter = 255; my $c = -0.7 + 0.27015i;   julia($out);   $out.write: 'Julia-set-perl6.png';   sub julia ( $png ) { ^$w .race.map: -> $x { for ^$h -> $y { my $z = Complex.new(($x...
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...
#Tcl
Tcl
#!/usr/bin/env tclsh proc main argv { array set value {panacea 3000 ichor 1800 gold 2500} array set weight {panacea 0.3 ichor 0.2 gold 2.0 max 25} array set volume {panacea 0.025 ichor 0.015 gold 0.002 max 0.25}   foreach i {panacea ichor gold} { set max($i) [expr {min(int($volume(max)/...
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...
#Scala
Scala
import scala.annotation.tailrec   object ContinousKnapsackForRobber extends App { val MaxWeight = 15.0 val items = Seq( Item("Beef", 3.8, 3600), Item("Pork", 5.4, 4300), Item("Ham", 3.6, 9000), Item("Greaves", 2.4, 4500), Item("Flitch", 4.0, 3000), Item("Brawn", 2.5, 5600), ...
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...
#PL.2FI
PL/I
on conversion goto restart;
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...
#PL.2FSQL
PL/SQL
DECLARE i number := 5; divide_by_zero EXCEPTION; PRAGMA exception_init(divide_by_zero, -20000); BEGIN DBMS_OUTPUT.put_line( 'startLoop' ); <<startLoop>> BEGIN if i = 0 then raise divide_by_zero; end if; DBMS_OUTPUT.put_line( 100/i ); ...
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...
#Forth
Forth
  \ Rosetta Code Knapp-sack 0-1 problem. Tested under GForth 0.7.3. \ 22 items. On current processors a set fits nicely in one CELL (32 or 64 bits). \ Brute force approach: for every possible set of 22 items, \ check for admissible solution then for optimal set.   : offs HERE over - ; 400 VALUE WLIMIT ...
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. ...
#jq
jq
# Is the input integer a Kaprekar integer? def is_kaprekar: # The helper function acts like a loop: # input is [n, number, str] # where n is the position to be considered next, # number is the integer under consideration, # and str is the string representing number*number def _try: .[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. ...
#Julia
Julia
function iskaprekar(n::Integer) n == 1 && return true test(a, b) = n == a + b && b ≠ 0 str = string(n^2) any(test(parse(Int, str[1:i]), parse(Int, str[i+1:end])) for i = 1:length(str)-1) end   @show filter(iskaprekar, 1:10000) @show count(iskaprekar, 1:10000)
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).
#Kotlin
Kotlin
// version 1.2.21   data class JsonObject(val foo: Int, val bar: Array<String>)   data class JsonObject2(val ocean: String, val blue: Array<Int>)   fun main(args: Array<String>) { // JSON to object val data: JsonObject = JSON.parse("""{ "foo": 1, "bar": ["10", "apples"] }""") println(JSON.stringify(data))  ...
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...
#Kotlin
Kotlin
data class Square(val x : Int, val y : Int)   val board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) }) val axisMoves = arrayOf(1, 2, -1, -2)   fun <T> allPairs(a: Array<T>) = a.flatMap { i -> a.map { j -> Pair(i, j) } }   fun knightMoves(s : Square) : List<Square> { val moves = allPairs(axisMoves).filter{ Math....
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...
#FreeBASIC
FreeBASIC
' version 22-10-2016 ' compile with: fbc -s console ' for boundry checks on array's compile with: fbc -s console -exx   ' sort from lower bound to the highter bound ' array's can have subscript range from -2147483648 to +2147483647   Sub knuth_down(a() As Long)   Dim As Long lb = LBound(a) Dim As ULong n = UBou...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#REXX
REXX
/*REXX program displays an ASCII plot (character plot) of a Julia set. */ parse arg real imag fine . /*obtain optional arguments from the CL*/ if real=='' | real=="," then real= -0.8 /*Not specified? Then use the default.*/ if imag=='' | imag=="," then imag= 0.156 ...
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...
#Ursala
Ursala
#import nat #import flo   vol = iprod/<0.025,0.015,0.002>+ float* val = iprod/<3000.,1800.,2500.>+ float* wgt = iprod/<0.3,0.2,2.0>+ float*   packings = ~&lrlrNCCPCS ~&K0=> iota* <11,17,13>   solutions = fleq$^rS&hl |=&l ^(val,~&)* (fleq\25.+ wgt)*~ (fleq\0.25+ vol)*~ packings   #cast %nmL   human_readable = ~&p/*<'pan...
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...
#Sidef
Sidef
var 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 {|a,b| b[2]/b[1] <=> a[2]/a[1] }   var...
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...
#PowerShell
PowerShell
  :myLabel while (<condition>) { <statement list>}  
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...
#FreeBASIC
FreeBASIC
#define Tabu = Chr(9) Dim As Integer i, A, P, V, N Dim As Integer MejorArticulo, MejorValor = 0 Type Knapsack articulo As String*22 peso As Integer valor As Integer End Type Dim item(1 To 22) As Knapsack => { _ ("map ", 9, 150), ("compass ", 13, 35), _ ("water ...
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. ...
#Kotlin
Kotlin
import java.lang.Long.parseLong import java.lang.Long.toString   fun String.splitAt(idx: Int): Array<String> { val ans = arrayOf(substring(0, idx), substring(idx)) if (ans.first() == "") ans[0] = "0" // parsing "" throws an exception return ans }   fun Long.getKaprekarParts(sqrStr: String, base: Int): Arra...
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).
#Lasso
Lasso
// Javascript objects are represented by maps in Lasso local(mymap = map( 'success' = true, 'numeric' = 11, 'string' = 'Eleven' ))   json_serialize(#mymap) // {"numeric": 11,"string": "Eleven","success": true} '<br />'   // Javascript arrays are represented by arrays local(opendays = array( 'Monday', 'Tuesday' )) ...
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).
#LFE
LFE
  (: jiffy encode (list 1 2 3 '"apple" 'true 3.14))  
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...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 input "Board size: ",size 30 input "Start position: ",a$ 40 x=asc(mid$(a$,1,1))-96 50 y=val(mid$(a$,2,1)) 60 dim play(size,size) 70 for q=1 to 8 80 read dx(q),dy(q) 90 next 100 data 2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1 110 pen 0:paper 1 120 for q=1 to size 130 locate 3*q+1,24-size 140 print c...
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...
#Frink
Frink
  a = [1,2,3] a.shuffle[]  
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Ring
Ring
  # Project : Julia Set   load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("Julia set") setgeometry(100,100,500,400) label1 = new qlabel(win1) { setgeometry(10,10,400,400) ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Ruby
Ruby
def julia(c_real, c_imag) puts Complex(c_real, c_imag) -1.0.step(1.0, 0.04) do |v| puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join end end   def judge(c_real, c_imag, x, y) 50.times do z_real = (x * x - y * y) + c_real z_imag = x * y * 2 + c_imag return " " if z_real**2 > 10...
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...
#Visual_Basic
Visual Basic
Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function Sub Main() Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5 Dim P&, I&, G&, A&, M, Cur(Value To Volume) Dim S As New Collection: S.Add Array(0) '<- init Solutions-Coll. Const SackW = 25, SackV = 0.25 Dim Panacea: Pana...
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...
#Tcl
Tcl
package require Tcl 8.5   # Uses the trivial greedy algorithm proc continuousKnapsack {items massLimit} { # Add in the unit prices set idx -1 foreach item $items { lassign $item name mass value lappend item [expr {$value / $mass}] lset items [incr idx] $item }   # Sort by unit prices set item...
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...
#PureBasic
PureBasic
OnErrorGoto(?ErrorHandler) OpenConsole() Gosub label4 Goto label3   label1: Print("eins ") Return   label2: Print("zwei ") Return   label3: Print("drei ")   label4: While i<3 i+1 Gosub label1 Gosub label2 Wend Print("- ") i+1 If i<=4 : Return : EndIf x.i=Val(Input()) : y=1/x Input() End   ErrorHandler: PrintN(Er...
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...
#FutureBasic
FutureBasic
window 1, @"Knapsack Problem", (0,0,480,270)   _maxWeight = 400   void local fn FillKnapsack long totalWeight = 0, totalValue = 0, itemWeight, unusedWeight CFDictionaryRef item, extraItem = NULL SortDescriptorRef sd CFMutableArrayRef packedItems   CFArrayRef items = @[ @{@"item":@"map", ...
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. ...
#Liberty_BASIC
Liberty BASIC
    For i = 1 To 10000 '1000000 - Changing to one million takes a long time to complete!!!! Kaprekar = isKaprekar(i) If Kaprekar Then numKaprekar = (numKaprekar + 1) : Print Kaprekar Next i   Print numKaprekar End   Function isKaprekar(num) If num < 1 Then isKaprekar = 0 : Exit Function If num = 1 The...
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).
#Lingo
Lingo
//-------------------------------------- // Simple (unsafe) JSON decoder based on eval() // @param {string} json // @return {any} //-------------------------------------- function json_decode (json){ var o; eval('o='+json); return _json_decode_val(o); }   function _json_decode_val (o){ if (o==null) return undef...
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...
#Lua
Lua
N = 8   moves = { {1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2} }   function Move_Allowed( board, x, y ) if board[x][y] >= 8 then return false end   local new_x, new_y = x + moves[board[x][y]+1][1], y + moves[board[x][y]+1][2] if new_x >= 1 and new_x <= N and new_y >= 1 and new_y <= N and 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...
#FunL
FunL
def shuffle( a ) = res = array( a ) n = a.length()   for i <- 0:n r = rnd( i:n ) res(i), res(r) = res(r), res(i)   res.toList()
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Rust
Rust
extern crate image;   use image::{ImageBuffer, Pixel, Rgb};   fn main() { // 4 : 3 ratio is nice let width = 8000; let height = 6000;   let mut img = ImageBuffer::new(width as u32, height as u32);   // constants to tweak for appearance let cx = -0.9; let cy = 0.27015; let iterations = 11...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Scala
Scala
import java.awt._ import java.awt.image.BufferedImage   import javax.swing._   object JuliaSet extends App { SwingUtilities.invokeLater(() => new JFrame("Julia Set") {   class JuliaSet() extends JPanel { private val (maxIter, zoom) = (300, 1)   override def paintComponent(gg: Graphics): Unit...
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...
#Wren
Wren
import "/fmt" for Fmt   class Item { construct new(name, value, weight, volume) { _name = name _value = value _weight = weight _volume = volume }   name { _name } value { _value } weight { _weight } volume { _volume } }   var items = [ Item.new("panac...
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...
#Ursala
Ursala
#import flo #import lin   items = # name: (weight,price)   < 'beef ': (3.8,36.0), 'pork ': (5.4,43.0), 'ham ': (3.6,90.0), 'greaves': (2.4,45.0), 'flitch ': (4.0,30.0), 'brawn ': (2.5,56.0), 'welt ': (3.7,67.0), 'salami ': (3.0,95.0), 'sausage': (5.9,98.0)>   system = # a function t...
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...
#Python
Python
  # Example 2: Restarting a loop: from goto import goto, label label .start for i in range(1, 4): print i if i == 2: try: output = message except NameError: print "Oops - forgot to define 'message'! Start again." message = "Hello world" goto .star...
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...
#QBasic
QBasic
  PRINT "First line." GOSUB sub1 PRINT "Fifth line." GOTO Ending   sub1: PRINT "Second line." GOSUB sub2 PRINT "Fourth line." RETURN   Ending: PRINT "We're just about done..." GOTO Finished   sub2: PRINT "Third line." RETURN   Finished: PRINT "... with goto and gosub, thankfully." END
http://rosettacode.org/wiki/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...
#Go
Go
package main   import "fmt"   type item struct { string w, v int }   var wants = []item{ {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"be...
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. ...
#Lua
Lua
-- Return length of an integer without string conversion function numLength (n) local length = 0 repeat n = math.floor(n / 10) length = length + 1 until n == 0 return length end   -- Return a boolean indicating whether n is a Kaprekar number function isKaprekar (n) if n == 1 then ret...
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).
#Lua
Lua
local json = require("json")   local json_data = [=[[ 42, 3.14159, [ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ], { "H": 1, "He": 2, "X": null, "Li": 3 }, null, true, false ]]=]   print("Original JSON: " .. json_data) local data = json.decode(json_data) json.util.printValue(data, ...
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...
#M2000_Interpreter
M2000 Interpreter
  Function KnightTour$(StartW=1, StartH=1){ def boolean swapH, swapV=True if startW<=4 then swapH=true: StartW=8+1-StartW if startH>4 then swapV=False: StartH=8+1-StartH Let final=8*8, last=final-1, HighValue=final+1 Dim Board(1 to 8, 1 to 8), Moves(1 to 8, 1 to 8)=HighValue f=stack:=1,2,3,4,5,6...
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...
#Gambas
Gambas
Public Sub Main() Dim iTotal As Integer = 40 Dim iCount, iRand1, iRand2 As Integer Dim iArray As New Integer[]   For iCount = 0 To iTotal iArray.add(iCount) Next   Print "Original = "; For iCount = 0 To iArray.Max If iCount = iArray.max Then Print iArray[iCount]; Else Print iArray[iCount] & ","; Next   For iCount =...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Sidef
Sidef
require('Imager')   var (w, h) = (640, 480) var img = %s'Imager'.new(xsize => w, ysize => h, channels => 3)   var maxIter = 50 var c = Complex(-0.388, 0.613)   var color = %s'Imager::Color'.new('#000000')   for x,y in (^w ~X ^h) { var i = maxIter var z = Complex((x - w/2) / w * 3, (y - h/2) / h * 2) while (...
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...
#zkl
zkl
panacea:=T(3000, 0.3, 0.025); // (value,weight,volume) ichor  :=T(1800, 0.2, 0.015); gold  :=T(2500, 2.0, 0.002); sack  :=T( 0, 25.0, 0.250); const VAL=0, W=1, VOL=2;   maxes:=T(panacea,ichor,gold) .apply('wrap(t){ (sack[W]/t[W]).min(sack[VOL]/t[VOL]).toInt().walker() }); best:=Utils.Helpers.cprod3(maxes.xp...
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...
#Vlang
Vlang
struct Item { item string weight f64 price f64 }   fn main(){ mut left := 15.0 mut items := [ Item{'beef', 3.8, 36}, Item{'pork', 5.4, 43}, Item{'ham', 3.6, 90}, Item{'greaves', 2.4, 45}, Item{'flitch', 4.0, 30}, Item{'brawn', 2.5, 56}, Item{'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...
#QB64
QB64
  ' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic ' here a GOTO demo of loops FOR-NEXT and WHILE-WEND   Dim S As String, Q As Integer Randomize Timer 0: Locate 1, 1: Print "jump demostration" Print "Press J to jump to FOR NEXT emulator or" Print "L to jump to WHILE WEND emulator or" Print "Q for quitting"...
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...
#Quackery
Quackery
[ ]'[ ]do[ ' ]else[ swap of ]do[ ] is jump-into ( n --> )   5 jump-into [ 0 echo 1 echo done ( 0 1 2 3 4 offsets of each item ) ( 5 6 7 8 9 from start of nest ) 2 echo 3 echo again ]
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...
#Groovy
Groovy
def totalWeight = { list -> list*.weight.sum() } def totalValue = { list -> list*.value.sum() }   def knapsack01bf = { possibleItems -> possibleItems.subsequences().findAll{ ss -> def w = totalWeight(ss) 350 < w && w < 401 }.max(totalValue) }
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. ...
#Maple
Maple
  isKaprekar := proc(n::posint) local holder, square, num_of_digits, k, left, right; holder := true; if n = 1 then holder := true; else holder := false; square := n^2; num_of_digits := length(n^2); for k to num_of_digits do left := floor(square/10^k); right := irem(square, 10^k); if left + right...
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. ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
KaprekaQ[1] = True; KaprekaQ[n_Integer] := Block[{data = IntegerDigits[n^2], last = False, i = 1}, While[i < Length[data] && FromDigits[data[[i + 1 ;;]]] =!= 0 && Not[last], last = FromDigits[data[[;; i]]] + FromDigits[data[[i + 1 ;;]]] == n; i++]; last]; Select[Range[10000], KaprekaQ] Length[Select[Range[100...
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).
#M2000_Interpreter
M2000 Interpreter
  MODULE A { \\ Process data in json format   \\ We can load from external file with Inline "libName" \\ or multiple files Inline "file1" && "file2" \\ but here we have the library in a module Inline Code Lib1 \\ So now we make a Parser object (a group type in M2000) Parser=Par...
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).
#Maple
Maple
> JSON:-ParseString("[{\"tree\": \"maple\", \"count\": 21}]"); [table(["tree" = "maple", "count" = 21])] > JSON:-ToString( [table(["tree" = "maple", "count" = 21])] ); "[{\"count\": 21, \"tree\": \"maple\"}]"
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...
#m4
m4
divert(-1)   ----------------------------------------------------------------------   This is free and unencumbered software released into the public domain.   Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, c...
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...
#GAP
GAP
# Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same. ShuffleAlt := function(a) local i, j, n, t; n := Length(a); for i in [n, n - 1 .. 2] do j := Random(1, i); t := a[i]; a[i] := a[j]; a[j] := t; od; return a; end; ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   var MaxIters = 300 var Zoom = 1 var MoveX = 0 var MoveY = 0 var CX = -0.7 var CY = 0.27015   class JuliaSet { construct new(width, height) { Window.title = "Julia Set" Window.resize(width, height) Canvas.resize(width, height) ...
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...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Math import "/sort" for Sort   class Item { construct new(name, weight, value) { _name = name _weight = weight _value = value }   name { _name } weight { _weight } value { _value } }   var items = [ Item.new("beef", 3.8, 3...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Racket
Racket
#lang racket (define (never-divides-by-zero return) (displayln "I'm here") (return "Leaving") (displayln "Never going to reach this") (/ 1 0))   (call/cc never-divides-by-zero)   ; outputs: ; I'm here ; "Leaving" (because that's what the function returns)  
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...
#Relation
Relation
:foo #19 &n:inc \ju...... #21 ;
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...
#Haskell
Haskell
inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160), ("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40), ("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30), ("tshirt",24,15), ("trousers",48,10), ("umbrella",73,40), ("trousers",42,70), ("overclothes",43,7...
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. ...
#Maxima
Maxima
kaprekarp(n) := block( [p, q, a, b], if n = 1 then true else ( q: n * n, p: 10, catch( while p < q do ( [a, b]: divide(q, p), if b > 0 and a + b = n then throw(true), p: 10 * p ), false ) ) )$   sublist(makelist(i, i, 1, 10^...
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#ML
ML
local val base = 10; fun kaprekar (num, numSquared, numDiv, numRem, power) where (base ^ power >= numSquared) = ()   | (num, numSquared, numDiv, numRem, power) where ((numDiv = 0) or (numRem = 0))= kaprekar (num, numSquared, numSquared div (base ^ power ), numSquared rem (base ^ power), po...
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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"] ExportString[data, "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).
#MATLAB_.2F_Octave
MATLAB / Octave
>> jsondecode('{ "foo": 1, "bar": [10, "apples"] }') ans = struct with fields:   foo: 1 bar: {2×1 cell} >> jsonencode(ans) ans = {"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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
knightsTourMoves[start_] := Module[{ vertexLabels = (# -> ToString@c[[Quotient[# - 1, 8] + 1]] <> ToString[Mod[# - 1, 8] + 1]) & /@ Range[64], knightsGraph, hamiltonianCycle, end}, knightsGraph = KnightTourGraph[i, i, VertexLabels -> vertexLabels, ImagePadding -> 15]; hamiltonianCycle = ((FindH...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() { var a [20]int for i := range a { a[i] = i } fmt.Println(a)   rand.Seed(time.Now().UnixNano()) for i := len(a) - 1; i >= 1; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } fmt.Prin...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#zkl
zkl
fcn juliaSet{ w,h,zoom:=800,600, 1; bitmap:=PPM(w,h,0xFF|FF|FF); // White background   cX,cY:=-0.7, 0.27015; moveX,moveY:=0.0, 0.0; maxIter:=255;   foreach x,y in (w,h){ zx:=1.5*(x - w/2)/(0.5*zoom*w) + moveX; zy:=1.0*(y - h/2)/(0.5*zoom*h) + moveY; i:=maxIter; while(zx*zx + z...
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...
#XPL0
XPL0
int Name, Price, I, BestItem; real Weight, Best, ItemWt, TotalWt; def Items = 9; real PricePerWt(Items); int Taken(Items); include c:\cxpl\codes;   [Name:= ["beef","pork","ham","greaves","flitch","brawn","welt","salami","sausage"]; Weight:= [ 3.8, 5.4, 3.6, 2.4, 4.0, 2.5, 3.7, 3.0, ...
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...
#Retro
Retro
:foo #19 &n:inc \ju...... #21 ;
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...
#Raku
Raku
outer-loop: loop { inner-loop: loop { # NYI # goto inner-loop if rand > 0.5; # Hard goto next inner-loop if rand > 0.5; # Next loop iteration redo inner-loop if rand > 0.5; # Re-execute block last outer-loop if rand > 0.5; # Exit the loop ENTER { s...
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...
#Icon_and_Unicon
Icon and Unicon
link printf   global wants # items wanted for knapsack   procedure main(A) # kanpsack 0-1 if !A == ("--trace"|"-t") then &trace := -1 # trace everything (debug) if !A == ("--memoize"|"-m") then m :=: Memo_m # hook (swap) procedure   printf("Knapsack-0-1: with maximum weight allowed=%d....