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/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).
#Scheme
Scheme
  (use json) (define object-example (with-input-from-string "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}" json-read)) (pp object-example) ; this prints #(("foo" . "bar") ("baz" 1 2 3))   (json-write #([foo . bar] [baz 1 2 3] [qux . #((rosetta . code))])) ; this write...
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...
#RATFOR
RATFOR
#----------------------------------------------------------------------- # # Find Knight’s Tours. # # Using Warnsdorff’s heuristic, find multiple solutions. # Optionally accept only closed tours. # # This program is migrated from my implementation for ATS/Postiats. # 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...
#Lasso
Lasso
define staticarray->swap(p1::integer,p2::integer) => { fail_if( #p1 < 1 or #p2 < 1 or #p1 > .size or #p2 > .size, 'invalid parameters' ) #p1 == #p2  ? return   local(tmp) = .get(#p2) .get(#p2) = .get(#p1) .get(#p1) = #tmp } define staticarray->knuthShuffle => { ...
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...
#Nim
Nim
  # Knapsack. Recursive algorithm.   import algorithm import sequtils import tables   # Description of an item. type Item = tuple[name: string; weight, value: int]   # List of available items. const Items: seq[Item] = @[("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. ...
#Run_BASIC
Run BASIC
for i = 1 to 5000 x$ = str$(i * i) if i = 1 then x$ = "10" for j = 1 to len(x$) - 1 if (val(left$(x$,j)) + val(mid$(x$,j+1)) = i and val(mid$(x$,j+1)) <> 0) or i = 1 then print "Kaprekar :";left$(x$,j);" + ";mid$(x$,j+1);" = ";i next j next i
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. ...
#Scala
Scala
object Kaprekar extends App {   def isKaprekar(n: Int, base: Int = 10):Option[Triple[String,String,String]] = { val check: Long => Option[Triple[String,String,String]] = n => { val split: Pair[String, Int] => Pair[String, String] = p => (p._1.slice(0,p._2),p._1.slice(p._2,p._1.size).padTo[Char,String](1,'0'...
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#SenseTalk
SenseTalk
set jsonString to <<{"foo": 10, "bar": [1, 2, 3]}>> put JSONValue(jsonString)   set dataObject to (string_value: "lorem ipsum", int_value: 314, array_value: (2, 4, 6)) put JSONFormat(dataObject)
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).
#Sidef
Sidef
var json = require('JSON').new; var data = json.decode('{"blue": [1, 2], "ocean": "water"}'); say data; data{:ocean} = Hash.new(water => %w[fishy salty]); say json.encode(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...
#REXX
REXX
/*REXX program solves the knight's tour problem for a (general) NxN chessboard.*/ parse arg N sRank sFile . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N=8 /*No boardsize specified? Use default.*/ if sRank=='' | sRank=="," then sRank=N ...
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...
#Liberty_BASIC
Liberty BASIC
'Declared the UpperBound to prevent confusion with lots of 9's floating around.... UpperBound = 9 Dim array(UpperBound)   For i = 0 To UpperBound array(i) = Int(Rnd(1) * 10) Print array(i) Next i   For i = 0 To UpperBound 'set a random value because we will need to use the same value twice randval = Int...
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...
#OCaml
OCaml
let items = [ "map", 9, 150; "compass", 13, 35; "water", 153, 200; "sandwich", 50, 160; "glucose", 15, 60; "tin", 68, 45; "banana", 27, 60; "apple", 39, 40; ...
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. ...
#Scheme
Scheme
; auxiliary functions : range, filter (define (range a b) (let loop ((v '()) (i b)) (if (< i a) v (loop (cons i v) (- i 1)))))   (define (filter p u) (if (equal? u '()) '() (let ((x (car u)) (v (filter p (cdr u)))) (if (p x) (cons x v) v))))   (define (kaprek...
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).
#Smalltalk
Smalltalk
  NeoJSONReader fromString: '{ "foo": 1, "bar": [10, "apples"] }'.  
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).
#Standard_ML
Standard ML
  val Validate = fn jsonstring => let val Valid = fn jsonstring => let val json = String.translate (fn #"\"" => "\\\""|n=>str n ) jsonstring ; val textlength = (String.size json ) + 50 ; val app = " jq -c '.' " val fname = "/tmp/jsonval" ^ (String.extract (Time.toString (Posix.ProcE...
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...
#Ruby
Ruby
class Board Cell = Struct.new(:value, :adj) do def self.end=(end_val) @@end = end_val end   def try(seq_num) self.value = seq_num return true if seq_num==@@end a = [] adj.each_with_index do |cell, n| a << [wdof(cell.adj)*10+n, cell] if cell.value.zero? 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...
#Logo
Logo
to swap :i :j :a localmake "t item :i :a setitem :i :a item :j :a setitem :j :a :t end to shuffle :a for [i [count :a] 2] [swap 1 + random :i :i :a] end   make "a {1 2 3 4 5 6 7 8 9 10} shuffle :a show :a
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...
#Oz
Oz
declare %% maps items to pairs of Weight(hectogram) and Value Problem = knapsack('map':9#150 'compass':13#35 'water':153#200 'sandwich':50#160 'glucose':15#60 'tin':68#45 'banana':27#60 ...
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. ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func bigInteger: kaprekar (in bigInteger: n, in bigInteger: base) is func result var bigInteger: kaprekar is 0_; local var bigInteger: nn is 0_; var bigInteger: r is 0_; var bigInteger: powerOfBase is 1_; begin nn := n ** 2; while p...
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. ...
#Sidef
Sidef
var kapr = Set()   for n in (1..15) { var k = (10**n - 1) k.udivisors.each {|d| var dp = k/d kapr << (dp == 1 ? d : d*invmod(d, dp)) } }   say kapr.grep { .<= 1e4 }.sort   for n in (6 .. 14) { var k = (10**n - 1) printf("Kaprekar numbers <= 10^%2d:  %5d\n", n, kapr.count_by { .<= k }...
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).
#Swift
Swift
import Foundation   let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }" if let jsonData = jsonString.data(using: .utf8) { if let jsonObject: Any = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) { print("Dictionary: \(jsonObject)") } }   let obj = [ "foo": [1, "Orange"], "bar"...
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).
#Tailspin
Tailspin
  // Not all JSON object member keys can be represented, a fallback would need to be implemented // Currently Tailspin only supports integers so for now we leave numbers as strings, as we do for true, false and null   templates hexToInt templates hexDigit <='0'> 0! <='1'> 1! <='2'> 2! <='3'> 3! <='4'> 4! <='5'> 5...
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...
#Rust
Rust
use std::fmt;   const SIZE: usize = 8; const MOVES: [(i32, i32); 8] = [ (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), ];   #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] struct Point { x: i32, y: i32, }   impl Point { fn mov(&self, &(dx, dy):...
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...
#Lua
Lua
function table.shuffle(t) for n = #t, 1, -1 do local k = math.random(n) t[n], t[k] = t[k], t[n] end   return t end   math.randomseed( os.time() ) a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} table.shuffle(a) for i,v in ipairs(a) do print(i,v) 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...
#Pascal
Pascal
  program project1; uses sysutils, classes, math;   const MaxWeight = 400; N = 21;   type TMaxArray = array[0..N, 0..MaxWeight] of integer;   TEquipment = record Description : string; Weight : integer; Value : integer; end;   TEquipmentList = array[1..N] of TEquipment;   var M:TMaxArray; ...
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. ...
#SPL
SPL
kap,n = getkap(1000000) > i, 1..n << kap[i]!<10000 #.output(kap[i]) < #.output(n," Kaprekar numbers < 1000000")   getkap(x)= > k, 1..x n = #.lower(#.log10(k^2))+1 > i, 1..n r = k^2%10^i << r>k >> r=0 l = #.lower(k^2/10^i)  ? r+l=k, kap[#.size(kap,1)+1] = k < < <= kap,#...
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. ...
#Tcl
Tcl
package require Tcl 8.5; # Arbitrary precision arithmetic, for stretch goal only proc kaprekar n { if {$n == 1} {return 1} set s [expr {$n * $n}] for {set i 1} {$i < [string length $s]} {incr i} { scan $s "%${i}d%d" a b if {$b && $n == $a + $b} { return 1 #return [list 1 $a $b] } } 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).
#Tcl
Tcl
package require json set sample {{ "foo": 1, "bar": [10, "apples"] }}   set parsed [json::json2dict $sample] puts $parsed
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).
#TXR
TXR
@(define value (v))@\ @(cases)@\ @(string v)@(or)@(num v)@(or)@(object v)@(or)@\ @(keyword v)@(or)@(array v)@\ @(end)@\ @(end) @(define ws)@/[\n\t ]*/@(end) @(define string (g))@\ @(local s hex)@\ @(ws)@\ "@(coll :gap 0 :vars (s))@\ @(cases)@\ \"@(bind s "&quot;")@(or)@\ \\@(bind s ...
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...
#Scala
Scala
  val b=Seq.tabulate(8,8,8,8)((x,y,z,t)=>(1L<<(x*8+y),1L<<(z*8+t),f"${97+z}%c${49+t}%c",(x-z)*(x-z)+(y-t)*(y-t)==5)).flatten.flatten.flatten.filter(_._4).groupBy(_._1) def f(p:Long,s:Long,v:Any){if(-1L!=s)b(p).foreach(x=>if((s&x._2)==0)f(x._2,s|x._2,v+x._3))else println(v)} f(1,1,"a1")  
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...
#M2000_Interpreter
M2000 Interpreter
  Dim Base 0, A(3) For k=1 to 6 { A(0):=10,20, 30 For i=len(A())-1 to 0 { let j=random(0,i) Swap a(i), a(j) } Print A() }    
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...
#Perl
Perl
my $raw = <<'TABLE'; 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 suntancream 11 70 camera 32 30 T-shirt 24 15 trousers 48 10 umbrella 73 40 waterproof trousers 42 70 waterproof overclothes 43 75 note-case 22 80...
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. ...
#Ursala
Ursala
#import std #import nat   kd("p","r") = ~&ihB+ (~&rr&& ^|E/~& sum)~|^/~& "r"~~*hNCtXS+ cuts\1+ "p"+ product@iiX   #cast %nLnX   t = ^|(~&,length) (iota; :/1+ ~&rFlS+ * ^/~& kd\%np ~&h+ %nP)~~/10000 1000000
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. ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly max As ULong = 1000000   Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True   Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str)   For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 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).
#Vlang
Vlang
import json   struct User { // Adding a [required] attribute will make decoding fail, if that // field is not present in the input. // If a field is not [required], but is missing, it will be assumed // to have its default value, like 0 for numbers, or '' for strings, // and decoding will not fail. name string [r...
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).
#Wren
Wren
import "/json" for JSON   var s = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }" var o = JSON.parse(s) System.print(o)   o = { "blue": [1, 2], "ocean": "water" } s = JSON.stringify(o) System.print(s)
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...
#Scheme
Scheme
  ;;/usr/bin/petite ;;encoding:utf-8 ;;Author:Panda ;;Mail:panbaoxiang@hotmail.com ;;Created Time:Thu 29 Jan 2015 10:18:49 AM CST ;;Description:   ;;size of the chessboard (define X 8) (define Y 8) ;;position is an integer that could be decoded into the x coordinate and y coordinate (define(decode position) (cons (d...
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...
#M4
M4
divert(-1) define(`randSeed',141592653) define(`rand_t',`eval(randSeed^(randSeed>>13))') define(`random', `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`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...
#Phix
Phix
-- demo\rosetta\knapsack0.exw with javascript_semantics bool terminate = false integer attempts = 0 function knapsack(sequence res, goodies, atom points, weight, at=1, sequence chosen={}) atom {?,witem,pitem} = goodies[at] integer n = iff(witem<=weight?1:0) chosen &= n points += n*pitem -- increase ...
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. ...
#Vlang
Vlang
import strconv   fn kaprekar(n u64, base u64) (bool, int) { mut order := 0 if n == 1 { return true, -1 }   nn, mut power := n*n, u64(1) for power <= nn { power *= base order++ }   power /= base order-- for ; power > 1; power /= base { q, r := nn/power,...
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).
#XQuery
XQuery
  let $json := ' { "Astring" : "string-value", "Anumber" : 5.7, "Anull"  : null, "Aarray"  : ["One","Two", 3], "Aobject" : { "key1": "value1", "key2": "value2" }, "Atrue"  : true, "Afalse"  : false } ' let $xml := json-to-xml($local:json) return ( "XPath fn:js...
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...
#SequenceL
SequenceL
  import <Utilities/Sequence.sl>; import <Utilities/Conversion.sl>;   main(args(2)) := let N := stringToInt(args[1]) when size(args) > 0 else 8; M := stringToInt(args[2]) when size(args) > 1 else N; startX := stringToInt(args[3]) when size(args) > 2 else 1; startY := stringToInt(args[4]) when size(args) > 3 e...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
RandomSample[{1, 2, 3, 4, 5, 6}]
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...
#PHP
PHP
######################################################### # 0-1 Knapsack Problem Solve with memoization optimize and index returns # $w = weight of item # $v = value of item # $i = index # $aW = Available Weight # $m = Memo items array # PHP Translation from Python, Memoization, # and index return functionality added 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. ...
#Wortel
Wortel
@let { isKap &n [ @var s +'' *n n @for i til +1/#s 2 [ @vars { fn @+!!s.slice 0 i sn @+!s.slice i } @if =0 sn @break @if =n +fn sn @return [fn sn] ] false ]   ~[  !console.log "Kaprekar numbers below 10000: {!-isKap @to 1TK}"  !console.log "Number of ...
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. ...
#Wren
Wren
import "/fmt" for Fmt, Conv   var kaprekar = Fn.new { |n, base| var order = 0 if (n == 1) return [true, -1] var nn = n * n var power = 1 while (power <= nn) { power = power * base order = order + 1 } power = (power/base).floor order = order - 1 while (power > 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).
#zkl
zkl
a,b:=Import.lib("zklYAJL"); var [const] YAJL=a, toJSON=b; src:= #<<< 0'|{ "pi": 3.14, "large number": 123456789123456791, "an array": [ -1, true, false, null, "foo" ] }|; #<<< obj:=YAJL().write(src).close(); // or obj:=src.pump(YAJL()).close(); // for example, fro...
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...
#Sidef
Sidef
var board = [] var I = 8 var J = 8 var F = (I*J > 99 ? '%3d' : '%2d')   var (i, j) = (I.irand, J.irand)   func from_algebraic(square) { if (var match = square.match(/^([a-z])([0-9])\z/)) { return(I - Num(match[1]), match[0].ord - 'a'.ord) } die "Invalid block square: #{square}" }   func possible...
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...
#MATLAB
MATLAB
function list = knuthShuffle(list)   for i = (numel(list):-1:2)   j = floor(i*rand(1) + 1); %Generate random int between 1 and i   %Swap element i with element j. list([j i]) = list([i j]); end 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...
#Picat
Picat
import mip,util.   go => items(AllItems,MaxTotalWeight), [Items,Weights,Values] = transpose(AllItems),   knapsack_01(Weights,Values,MaxTotalWeight, X,TotalWeight,TotalValues), print_solution(Items,Weights,Values, X,TotalWeight,TotalValues), nl.   % Print the solution print_solution(Items,Weights,Values, X,Tot...
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. ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func Kaprekar(N, B); \Returns 'true' if N is a Kaprekar number in base B int N, B; real N2, D; int Q, R; [N2:= sq(float(N)); \N squared D:= float(B); \(divider) loop [Q:= fix(N2/D - Mod(N2,1.)); \get left pa...
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. ...
#Yabasic
Yabasic
clear screen n = 0 FOR i = 1 TO 999999 IF FNkaprekar(i) THEN n = n + 1 IF i < 100001 PRINT n, ": ", i ENDIF NEXT i PRINT "Total Kaprekar numbers under 1,000,000 = ", n END   sub FNkaprekar(n) LOCAL s, t   s = n^2 t = 10^(INT(LOG(s)) + 1) do t=t/10 IF t<=n break IF s-n = INT(s/t)*(t-1) retur...
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...
#Swift
Swift
public struct CPoint { public var x: Int public var y: Int   public init(x: Int, y: Int) { (self.x, self.y) = (x, y) }   public func move(by: (dx: Int, dy: Int)) -> CPoint { return CPoint(x: self.x + by.dx, y: self.y + by.dy) } }   extension CPoint: Comparable { public static func <(lhs: CPoint, r...
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...
#Maxima
Maxima
/* Maxima has an implementation of Knuth shuffle */ random_permutation([a, b, c]);
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...
#PicoLisp
PicoLisp
(de *Items ("map" 9 150) ("compass" 13 35) ("water" 153 200) ("sandwich" 50 160) ("glucose" 15 60) ("tin" 68 45) ("banana" 27 60) ("apple" 39 40) ("cheese" 23 30) ("beer" 52 10) ("suntan cream" 11 70) ("camera" ...
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. ...
#zkl
zkl
fcn isKaprekarB(n,b=10){ powr:=n*n; r:=l:=0; tens:=b; while(r<n){ r = powr % tens; l = powr / tens; if (r and (l + r == n)) return(True); tens *= b; } return(False); }
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...
#Tcl
Tcl
package require Tcl 8.6; # For object support, which makes coding simpler   oo::class create KnightsTour { variable width height visited   constructor {{w 8} {h 8}} { set width $w set height $h set visited {} }   method ValidMoves {square} { lassign $square c r set moves {} foreach {dx dy} {-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...
#Modula-3
Modula-3
MODULE Shuffle EXPORTS Main;   IMPORT IO, Fmt, Random;   VAR a := ARRAY [0..9] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER) = VAR temp: INTEGER; n: INTEGER := NUMBER(a); BEGIN WITH rand = NEW(Random.Default).init() DO WHILE n > 1 DO WITH k = rand.integer(0...
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...
#Prolog
Prolog
:- use_module(library(clpfd)).   knapsack :- L = [ item(map, 9, 150), item(compass, 13, 35), item(water, 153, 200), item(sandwich, 50, 160), item(glucose, 15, 60), item(tin, 68, 45), ...
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...
#Wren
Wren
class Square { construct new(x, y) { _x = x _y = y }   x { _x } y { _y }   ==(other) { _x == other.x && _y == other.y } }   var board = List.filled(8 * 8, null) for (i in 0...board.count) board[i] = Square.new((i/8).floor + 1, i%8 + 1) var axisMoves = [1, 2, -1, -2]   var allPairs = ...
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...
#MUMPS
MUMPS
Shuffle(items,separator) New ii,item,list,n Set list="",n=0 Set ii="" For Set ii=$Order(items(ii)) Quit:ii="" Do . Set n=n+1,list(n)=items(ii),list=list_$Char(n) . Quit For Quit:list="" Do . Set n=$Random($Length(list))+1 . Set item=list($ASCII(list,n)) . Set $Extract(list,n)="" . Write item,separator . Q...
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...
#PureBasic
PureBasic
Structure item name.s weight.i ;units are dekagrams (dag) Value.i EndStructure   Structure memo Value.i List picked.i() EndStructure   Global itemCount = 0 ;this will be increased as needed to match count Global Dim items.item(itemCount)   Procedure addItem(name.s, weight, Value) If itemCount >= ArraySize(i...
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...
#XPL0
XPL0
int Board(8+2+2, 8+2+2); \board array with borders int LegalX, LegalY; \arrays of legal moves def IntSize=4; \number of bytes in an integer (4 or 2) include c:\cxpl\codes; \intrinsic 'code' declarations     func Try(I, X, Y); ...
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...
#Nemerle
Nemerle
Shuffle[T] (arr : array[T]) : array[T] { def rnd = Random();   foreach (i in [0 .. (arr.Length - 2)]) arr[i] <-> arr[(rnd.Next(i, arr.Length))]; arr }
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...
#QB64
QB64
OPEN "knapsack.txt" FOR OUTPUT AS #1 N=7: L=5: a = 2^(N+1): RANDOMIZE TIMER 'knapsack.bas DANILIN DIM L(N), C(N), j(N), q(a), q$(a), d(a)   FOR m=a-1 TO (a-1)/2 STEP -1: g=m: DO ' cipher 0-1 q$(m)=LTRIM$(STR$(g MOD 2))+q$(m) g=g\2: LOOP UNTIL g=0 q$(m)=MID$(q$(m), 2, LEN(q$(m))) NEXT   FOR i=1 TO N: L(i)=I...
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...
#XSLT
XSLT
  <xsl:package xsl:version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:tour="http://www.seanbdurkin.id.au/tour" name="tour:tours"> <xsl:stylesheet> <xsl:function name="tour:manufacture-square" ...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   import java.util.List   cards = [String - 'hA', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'h10', 'hJ', 'hQ', 'hK' - , 'cA', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'cJ', 'cQ', 'cK' - , 'dA', 'd2', 'd3', '...
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...
#Python
Python
from itertools import combinations   def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) )   def totalvalue(comb): ' Totalise a particular combination of items' to...
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...
#zkl
zkl
// Use Warnsdorff's rule to perform a knights tour of a 8x8 board in // linear time. // See Pohl, Ira (July 1967), // "A method for finding Hamilton paths and Knight's tours" // http://portal.acm.org/citation.cfm?id=363463 // Uses back tracking as a tie breaker (for the few cases in a 8x8 tour) ...
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...
#Nim
Nim
import random randomize()   proc shuffle[T](x: var openArray[T]) = for i in countdown(x.high, 1): let j = rand(i) swap(x[i], x[j])   var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] shuffle(x) echo x
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...
#R
R
  Full_Data<-structure(list(item = c("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"), weigth = c(9, 13, 153...
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface NSMutableArray (KnuthShuffle) - (void)knuthShuffle; @end @implementation NSMutableArray (KnuthShuffle) - (void)knuthShuffle { for (NSUInteger i = self.count-1; i > 0; i--) { NSUInteger j = arc4random_uniform(i+1); [self exchangeObjectAtIndex:i withObjectAtIndex:j...
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...
#Racket
Racket
  #lang racket ; An ITEM a list of three elements: ; a name, a weight, and, a value   ; A SOLUTION to a knapsack01 problems is a list of three elements: ; the total value, the total weight, and, names of the items to bag   (define (add i s) ; add an item i to the solution s (match-define (list in iw iv) i) (mat...
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...
#OCaml
OCaml
let shuffle arr = for n = Array.length arr - 1 downto 1 do let k = Random.int (n + 1) in let temp = arr.(n) in arr.(n) <- arr.(k); arr.(k) <- temp done
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...
#Raku
Raku
my class KnapsackItem { has $.name; has $.weight; has $.unit; }   multi sub pokem ([], $, $v = 0) { $v } multi sub pokem ([$, *@], 0, $v = 0) { $v } multi sub pokem ([$i, *@rest], $w, $v = 0) { my $key = "{+@rest} $w $v"; (state %cache){$key} or do { my @skip = pokem @rest, $w, $v; if $w >=...
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...
#Oforth
Oforth
Indexable method: shuffle | s i l | self asListBuffer ->l self size dup ->s 1- loop: i [ s i - rand i + i l swapValues ] l dup freeze ;
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...
#REXX
REXX
/*REXX program solves a knapsack problem (22 {+1} items with a weight restriction). */ maxWeight=400 /*the maximum weight for the knapsack. */ say 'maximum weight allowed for a knapsack:' commas(maxWeight); say call gen@ /*gene...
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...
#Ol
Ol
  (define (shuffle tp) (let ((items (vm:cast tp (type tp)))) ; make a copy (for-each (lambda (i) (let ((a (ref items i)) (j (+ 1 (rand! i)))) (set-ref! items i (ref items j)) (set-ref! items j a))) (reverse (iota (size items) 1))) items...
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...
#Ruby
Ruby
KnapsackItem = Struct.new(:name, :weight, :value) potential_items = [ KnapsackItem['map', 9, 150], KnapsackItem['compass', 13, 35], KnapsackItem['water', 153, 200], KnapsackItem['sandwich', 50, 160], KnapsackItem['glucose', 15, 60], KnapsackItem['tin', 68, 45], KnapsackItem['banan...
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...
#Oz
Oz
declare proc {Shuffle Arr} Low = {Array.low Arr} High = {Array.high Arr} in for I in High..Low;~1 do J = Low + {OS.rand} mod (I - Low + 1) OldI = Arr.I in Arr.I := Arr.J Arr.J := OldI end end   X = {Tuple.toArray unit(0 1 2 3 4 5 6 7 8 9)} in {Show {Array.toRecord un...
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...
#Rust
Rust
use std::cmp;   struct Item { name: &'static str, weight: usize, value: usize }   fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> { let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1]; for (i, it) in items.iter().enumerate() { for w in 1 .. max_weight + 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...
#PARI.2FGP
PARI/GP
FY(v)={ forstep(n=#v,2,-1, my(i=random(n)+1,t=v[i]); v[i]=v[n]; v[n]=t ); v };   FY(vector(52,i,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...
#SAS
SAS
/* create SAS data set */ data mydata; input item $1-23 weight value; datalines; map 9 150 compass 13 35 water 153 200 sandwich 50 160 glucose 15 60 tin 68 45 banana 27 60 apple ...
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...
#Pascal
Pascal
program Knuth;   const startIdx = -5; max = 11; type tmyData = string[9]; tmylist = array [startIdx..startIdx+max-1] of tmyData;   procedure InitList(var a: tmylist); var i: integer; Begin for i := Low(a) to High(a) do str(i:3,a[i]) end;   procedure shuffleList(var a: tmylist); var i,k : integer; tm...
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...
#Scala
Scala
object Knapsack extends App {   case class Item(name: String, weight: Int, value: Int)   val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}   //===== brute force (caution: increase the heap!) ==================================== val ks01b: List[Item]...
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...
#Perl
Perl
sub shuffle { my @a = @_; foreach my $n (1 .. $#a) { my $k = int rand $n + 1; $k == $n or @a[$k, $n] = @a[$n, $k]; } return @a; }
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...
#Sidef
Sidef
var raw = <<'TABLE' 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 bee...
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...
#Phix
Phix
sequence cards = tagset(52) puts(1,"Before: ") ?cards for i=52 to 1 by -1 do integer r = rand(i) {cards[r],cards[i]} = {cards[i],cards[r]} end for puts(1,"After: ") ?cards puts(1,"Sorted: ") ?sort(cards)
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...
#SQL
SQL
  WITH KnapsackItems (item, [weight], VALUE) AS ( SELECT 'map',9, 150 UNION ALL SELECT 'compass',13, 35 UNION ALL SELECT 'water',153, 200 UNION ALL SELECT 'sandwich',50, 160 UNION ALL SELECT 'glucose',15, 60 UNION ALL SELECT 'tin',68, 45 UNION ALL SELECT 'banana',27, 60 ...
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...
#PHP
PHP
//The Fisher-Yates original Method function yates_shuffle($arr){ $shuffled = Array(); while($arr){ $rnd = array_rand($arr); $shuffled[] = $arr[$rnd]; array_splice($arr, $rnd, 1); } return $shuffled; }   //The modern Durstenfeld-Knuth algorithm function knuth_shuffle(&$arr){ for($i=count($arr)-1;$i>0;$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...
#Swift
Swift
struct KnapsackItem { var name: String var weight: Int var value: Int }   func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] { var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)   for j in 1..<items.count+1 { let item = items[j-1]   for w in 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...
#Picat
Picat
go => _ = random2(), L = 1..10, println(l_before=L), knuth_shuffle(L), println('l_after '=L), nl.   knuth_shuffle(L) => foreach(I in L.len..-1..1) J = random(1,I), Tmp = L[I], L[I] := L[J], L[J] := Tmp 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...
#Tcl
Tcl
# The list of items to consider, as list of lists set items { {map 9 150} {compass 13 35} {water 153 200} {sandwich 50 160} {glucose 15 60} {tin 68 45} {banana 27 60} {apple 39 40} {cheese 23 30} {beer 52 10} {{suntan cream} 11 70} {camera 32 30} ...
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...
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de knuth (Lst) (for (N (length Lst) (>= N 2) (dec N)) (let I (rand 1 N) (xchg (nth Lst N) (nth Lst I)) ) ) )   (let L (range 1 15) (println 'before L) (knuth L) (println 'after L) )
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#11l
11l
F sum(&i, lo, hi, term) V temp = 0.0 i = lo L i <= hi temp += term() i++ R temp   F main() Int i print(sum(&i, 1, 100, () -> 1 / @i))   main()
http://rosettacode.org/wiki/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#11l
11l
F jortsort(sequence) R Array(sequence) == sorted(sequence)   F print_for_seq(seq) print(‘jortsort(#.) is #.’.format(seq, jortsort(seq)))   print_for_seq([1, 2, 4, 3]) print_for_seq([14, 6, 8]) print_for_seq([‘a’, ‘c’]) print_for_seq(‘CVGH’) print_for_seq(‘PQRST’)
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...
#Ursala
Ursala
#import std #import nat #import flo #import lin   #import nat   items = # name: (weight,value)   < '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), '...
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...
#PL.2FI
PL/I
declare T(0:10) fixed binary initial (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); declare (i, j, temp) fixed binary; do i = lbound(T,1) to hbound(T,1); j = min(random() * 12, 11); temp = T(j); T(j) = T(i); T(i) = temp; end;
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Jensen_Device is function Sum ( I : not null access Float; Lo, Hi : Float; F : access function return Float ) return Float is Temp : Float := 0.0; begin I.all := Lo; while I.all <= Hi loop ...
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#ALGOL_60
ALGOL 60
begin integer i; real procedure sum (i, lo, hi, term); value lo, hi; integer i, lo, hi; real term; comment term is passed by-name, and so is i; begin real temp; temp := 0; for i := lo step 1 until hi do temp := temp + term; sum := temp end; comment...
http://rosettacode.org/wiki/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program jortSort64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...