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/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Plain_English
Plain English
To run: Start up. Handle any events. Shut down.   To handle any events: Deque an event. If the event is nil, exit. Handle the event. Repeat.   To handle an event: If the event's kind is "key down", handle the event (key down).   To handle an event (key down): Put the event's key into a key. Write "" then the key to the...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#PowerShell
PowerShell
if ($Host.UI.RawUI.KeyAvailable) { $key = $Host.UI.RawUI.ReadKey() }
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#PureBasic
PureBasic
k$ = Inkey()
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Python
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function   import tty, termios import sys if sys.version_info.major < 3: import thread as _thread else: import _thread import time     try: from msvcrt import getch # try to import Window...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#C.23
C#
using System; using System.IO; using System.Linq; using System.Collections.Generic;   public class Program { static void Main() { foreach (var earthquake in LargeEarthquakes("data.txt", 6)) Console.WriteLine(string.Join(" ", earthquake)); }   static IEnumerable<string[]> LargeEarthquakes...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#C.2B.2B
C++
// Randizo was here! #include <iostream> #include <fstream> #include <string> using namespace std;   int main() { ifstream file("../include/earthquake.txt");   int count_quake = 0; int column = 1; string value; double size_quake; string row = "";     while(file >> value) { if(col...
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...
#HicEst
HicEst
CHARACTER list*1000   NN = ALIAS($Panacea, $Ichor, $Gold, wSack, wPanacea, wIchor, wGold, vSack, vPanacea, vIchor, vGold) NN = (3000, 1800, 2500, 25, 0.3, 0.2, 2.0, 0.25, 0.025, 0.015, 0.002) maxItems = ALIAS(maxPanacea, maxIchor, maxGold) maxItems = ( MIN( wSack/wPanacea, vSack/vPanacea),...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Microsoft_Small_Basic
Microsoft Small Basic
'From: 'Andy Oneill, 2-6-2015, "Small Basic: Key Input, '" TechNet, https://social.technet.microsoft.com/wiki/contents/articles/29850.small-basic-key-input.aspx, accessed 3-19-2018 GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWi...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#MiniScript
MiniScript
// flush the keyboard while key.available key.get end while   // and now prompt and wait for Y or N print "Press Y or N:" k = "" while k != "Y" and k != "N" k = key.get.upper end while print "You pressed: " + k
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...
#Java
Java
  package hu.pj.alg.test;   import hu.pj.alg.ContinuousKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*;   public class ContinousKnapsackForRobber { final private double tolerance = 0.0005;   public ContinousKnapsackForRobber() { ContinuousKnapsack cok = new ContinuousKnapsack(15)...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#zkl
zkl
fcn ccnt(textInBitBucket){ letters:=["a".."z"].pump(List().write,0); // array of 26 zeros textInBitBucket.howza(0).pump(Void,'wrap(c){ // pump text as ints if(97<=c<=122) c-=97; else if(65<=c<=90) c-=65; else return(Void.Skip); letters[c]+=1 }); sum:=letters.sum(); println(sum,"...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#MiniZinc
MiniZinc
  %Solve Knapsack Problem Bounded. Nigel Galloway, Octoer 12th., 2020. enum Items={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}; array[Items] of int: weight =[9,13,153,50,1...
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#C
C
if (x > 0) goto positive; else goto negative;   positive: printf("pos\n"); goto both;   negative: printf("neg\n");   both: ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector>   /** * Class for representing a point. coordinate_type must be a numeric type. */ template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions...
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...
#ALGOL_68
ALGOL 68
# Non-recursive Knight's Tour with Warnsdorff's algorithm # # If there are multiple choices, backtrack if the first choice doesn't # # find a solution #   # the size of the board # INT board size = 8...
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Brat
Brat
shuffle = { a | (a.length - 1).to 1 { i | random_index = random(0, i) temp = a[i] a[i] = a[random_index] a[random_index] = temp }   a }   p shuffle [1 2 3 4 5 6 7]
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Racket
Racket
  #lang racket (define-syntax-rule (with-raw body ...) (let ([saved #f]) (define (stty x) (system (~a "stty " x)) (void)) (dynamic-wind (λ() (set! saved (with-output-to-string (λ() (stty "-g")))) (stty "raw -echo opost")) (λ() body ...) (λ() (stty sav...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Raku
Raku
use Term::ReadKey;   react { whenever key-pressed(:!echo) { given .fc { when 'q' { done } default { .uniname.say } } } }
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#C
C
# define NUMBER_OF_POINTS 100000 # define NUMBER_OF_CLUSTERS 11 # define MAXIMUM_ITERATIONS 100 # define RADIUS 10.0     #include <stdio.h> #include <stdlib.h> #include <math.h>     typedef struct { double x; double y; int group; } POINT;     /*------------------------------------------------------- gen_xy   Th...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Cixl
Cixl
  use: cx;   'data.txt' `r fopen lines { let: (time place mag) @@s split ..; let: (m1 m2) $mag @. split &int map ..; $m1 6 >= $m2 0 > and {[$time @@s $place @@s $mag] say} if } for  
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#COBOL
COBOL
  *> *> Kernighan large earthquake problem *> Tectonics: cobc -xj kernighan-earth-quakes.cob *> quakes.txt with the 3 sample lines *> ./kernighan-earth-quakes *> >>SOURCE FORMAT IS FREE identification division. program-id. quakes.   e...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Ada
Ada
with Ada.Numerics.Generic_Complex_Types;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Palettes; with SDL.Events.Events;   procedure Julia_Set is   Width  : constant := 1_200; Height  : constant := 900;   type Real is new Float; package Complex_Real is new Ada...
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...
#J
J
mwv=: 25 0.25 prods=: <;. _1 ' panacea: ichor: gold:' hdrs=: <;. _1 ' weight: volume: value:' vls=: 3000 1800 2500 ws=: 0.3 0.2 2.0 vs=: 0.025 0.015 0.002   ip=: +/ .* prtscr=: (1!:2)&2   KS=: 3 : 0 os=. (#:i.@(*/)) mwv >:@<.@<./@:% ws,:vs bo=.os#~(ws,:vs) mwv&(*./@:>)@ip"_ 1 os mo=.bo{~{.\: vls ip"1 bo prtscr &.> ...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#MUMPS
MUMPS
for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   Say 'Please enter Y or N' parse ask c Select when c='Y' Then Say 'YES' when c='N' Then Say 'NO' otherwise Say 'Undecided' End
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#jq
jq
# continuous_knapsack(W) expects the input to be # an array of objects {"name": _, "weight": _, "value": _} # where "value" is the value of the given weight of the object.   def continuous_knapsack(W): map( .price = (if .weight > 0 then (.value/.weight) else 0 end) ) | sort_by( .price ) | reverse | reduce .[] a...
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Zoea
Zoea
  program: letter_frequency input: 'cbcacb' # can be literal value, stdin or file url at runtime derive: [[a,1],[b,2],[c,3]] output: 'a : 1\nb : 2\nc : 3\n'  
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Nim
Nim
# Knapsack. Recursive solution.   import strformat import tables   # Description of an item. type Item = tuple[name: string; weight, value, pieces: int]   # List of available items. const Items: seq[Item] = @[("map", 9, 150, 1), ("compass", 13, 35, 1), ("water", 153...
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...
#C.23
C#
if (x > 0) goto positive; else goto negative;   positive: Console.WriteLine("pos\n"); goto both;   negative: Console.WriteLine("neg\n");   both: ...
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...
#C.2B.2B
C++
#include <iostream> #include <utility>   using namespace std;   int main(void) { cout << "Find a solution to i = 2 * j - 7\n"; pair<int, int> answer; for(int i = 0; true; i++) { for(int j = 0; j < i; j++) { if( i == 2 * j - 7) { // use brute force...
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...
#11l
11l
F totalvalue(comb) V totwt = 0 V totval = 0 L(item, wt, val) comb totwt += wt totval += val R I totwt <= 400 {(totval, -totwt)} E (0, 0)   V items = [ (‘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. ...
#11l
11l
F k(n) V n2 = String(Int64(n) ^ 2) L(i) 0 .< n2.len V a = I i > 0 {Int(n2[0 .< i])} E 0 V b = Int(n2[i ..]) I b != 0 & a + b == n R 1B R 0B   print((1..9999).filter(x -> k(x))) print((1..999999).filter(x -> k(x)).len)
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#11l
11l
F juggler(n) V a = Int64(n) V r_count = 0 V r_max = a V r_maxidx = 0 L a != 1 V f = Float(a) a = Int64(I a [&] 1 == 0 {sqrt(f)} E f * sqrt(f)) r_count++ I a > r_max r_max = a r_maxidx = r_count R (r_count, r_max, r_maxidx)   print(‘n l[n] h[n] i[...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Common_Lisp
Common Lisp
  (in-package cl-user)   (defvar *random-target* (list (float (/ (random 1000) 100)) (float (/ (random 1000) 100)) (float (/ (random 1000) 100))))   (defun distance (n target &key (semi nil)) "distance node to target: returns squared euclidean distance, or squared semi distance if option set" (if ...
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...
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 DECLARE EXTERNAL FUNCTION choosemove 110 ! 120 RANDOMIZE 130 PUBLIC NUMERIC X, Y, TRUE, FALSE 140 LET TRUE = -1 150 LET FALSE = 0 160 ! 170 SET WINDOW 1,512,1,512 180 SET AREA COLOR "black" 190 FOR x=0 TO 512-128 STEP 128 200 FOR y=0 TO 512-128 STEP 128 210 PLOT AREA:x+64,y;x+128,y;x+128,y+64;x+64,y+64 22...
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...
#C
C
#include <stdlib.h> #include <string.h>   int rrand(int m) { return (int)((double)m * ( rand() / (RAND_MAX+1.0) )); }   #define BYTE(X) ((unsigned char *)(X)) void shuffle(void *obj, size_t nmemb, size_t size) { void *temp = malloc(size); size_t n = nmemb; while ( n > 1 ) { size_t k = rrand(n--); memcp...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#REXX
REXX
/*REXX program demonstrates if any key has been presssed. */   ∙ ∙ ∙ somechar=inkey('nowait') ∙ ∙ ∙
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Ring
Ring
  if getchar() see "A key was pressed" + nl else see "No key was pressed" + nl ok  
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Robotic
Robotic
  : "loop" if "KEY_PRESSED" != 0 then "#store" * "Last key pressed: &storedKey&" goto "loop"   : "#store" set "storedKey" to "KEY_PRESSED" goto "#return"  
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#D
D
import std.stdio, std.math, std.random, std.typecons, std.algorithm;   // On Windows this uses the printf from the Microsoft C runtime, // that doesn't handle real type and some of the C99 format // specifiers, but it's faster for bulk printing. extern(C) nothrow int printf(const char*, ...);   struct Point { immut...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Cowgol
Cowgol
include "cowgol.coh"; include "file.coh";   # Process a file line by line interface LineCb(line: [uint8]); sub ForEachLine(fcb: [FCB], cb: LineCb) is var buf: uint8[256]; var ptr := &buf[0];   var length := FCBExt(fcb); while length != 0 loop var ch := FCBGetChar(fcb); [ptr] := ch; ...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#D
D
import std.conv : to; import std.regex : ctRegex, split; import std.stdio : File, writeln;   void main() { auto ctr = ctRegex!"\\s+";   writeln("Those earthquakes with a magnitude > 6.0 are:"); foreach (line; File("data.txt").byLineCopy) { auto parts = split(line, ctr); if (parts[2].to!doubl...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Emacs_Lisp
Emacs Lisp
(with-temp-buffer (insert-file-contents "data.txt") (goto-char (point-min)) (while (not (eobp)) (let* ((line (buffer-substring (line-beginning-position) (line-end-position))) (magn (nth 2 (split-string line "\\s-+")))) (when (> (string-to-number magn) 6.0) ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#ALGOL_68
ALGOL 68
BEGIN REAL c real, c imaginary; STRING real and imaginary := IF argc < 3 THEN "-0.8" ELSE argv( 3 ) FI + " " + IF argc < 4 THEN "0.156" ELSE argv( 4 ) FI + " " ; FILE numbers; ass...
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...
#Java
Java
package hu.pj.alg;   import hu.pj.obj.Item; import java.text.*;   public class UnboundedKnapsack {   protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gol...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Nim
Nim
import strformat import gintro/[glib, gobject, gtk, gio] import gintro/gdk except Window   #---------------------------------------------------------------------------------------------------   proc onKeyPress(window: ApplicationWindow; event: Event; label: Label): bool = var keyval: int if not event.getKeyval(keyv...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#NS-HUBASIC
NS-HUBASIC
10 PRINT "PRESS Y OR N TO CONTINUE." 20 IF INKEY$<>"Y" AND INKEY$<>"N" THEN GOTO 20 30 PRINT "THE RESPONSE WAS ";INKEY$;"."
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...
#Julia
Julia
using Printf   struct KPCSupply{T<:Real} item::String weight::T value::T uvalue::T end function KPCSupply(item::AbstractString, weight::Real, value::Real) w, v = promote(weight, value) KPCSupply(item, w, v, v / w) end   Base.show(io::IO, s::KPCSupply) = print(io, s.item, @sprintf " (%.2f kg, %.2...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#OOCalc
OOCalc
  type KnapSackItem string name,sys dag,value,tag   KnapSackItem it[100]   sys dmax=400 sys items=22   it=>   "map", 9, 150, 0, "compass", 13, 35, 0, "water", 153, 200, 0, "sandwich", 50, 160, 0, "glucose", 15, 60, 0, "tin", 6...
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...
#Clipper
Clipper
IDENTIFICATION DIVISION. PROGRAM-ID. JUMPS-PROGRAM. * Nobody writes like this, of course; but... PROCEDURE DIVISION. * You can jump anywhere you like. START-PARAGRAPH. GO TO AN-ARBITRARY-PARAGRAPH. YET-ANOTHER-PARAGRAPH. ALTER START-PARAGRAPH TO PROCEED TO A-PARAGRAPH-SOMEWHERE. * That's right, folks: we don't ...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#360_Assembly
360 Assembly
* Knapsack problem/0-1 16/02/2017 KNAPSA01 CSECT USING KNAPSA01,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 end of prolog L R0,N n LA R1,1 POWER MH ...
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. ...
#360_Assembly
360 Assembly
* Kaprekar numbers 22/03/ 2017 KAPREKAR CSECT USING KAPREKAR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward S...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Ada
Ada
with Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions;   procedure Juggler is   subtype Number is Long_Long_Integer; type Index_Type is new Natural;   subtype Initial_Values is Number range 20 .. 39;   generic Initial : Number; package Generic_Juggler is procedure Next (Value : ou...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#AppleScript
AppleScript
on juggler(n) script o property sequence : {n} end script   set i to 1 set {max, pos} to {n, i} repeat until (n = 1) set n to n ^ (n mod 2 + 0.5) div 1 set end of o's sequence to n set i to i + 1 if (n > max) then set {max, pos} to {n, i} end repeat   ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#D
D
// Implmentation following pseudocode from // "An introductory tutorial on kd-trees" by Andrew W. Moore, // Carnegie Mellon University, PDF accessed from: // http://www.autonlab.org/autonweb/14665   import std.typecons, std.math, std.algorithm, std.random, std.range, std.traits, core.memory;   /// k-dimensional ...
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...
#ATS
ATS
(* Find Knight’s Tours.   Using Warnsdorff’s heuristic, find multiple solutions. Optionally accept only closed tours.   Compile with: patscc -O3 -DATS_MEMALLOC_GCBDW -o knights_tour knights_tour.dats -lgc   Usage: ./knights_tour [START_POSITION [MAX_TOURS [closed]]] Examples: ./knights_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...
#C.23
C#
public static void KnuthShuffle<T>(T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(i, array.Length); // Don't select from the entire array on subsequent loops T temp = array[i]; array[i] = array[j]; array[j] = temp; } ...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Ruby
Ruby
  begin check = STDIN.read_nonblock(1) rescue IO::WaitReadable check = false end   puts check if check  
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Scala
Scala
import java.awt.event.{KeyAdapter, KeyEvent}   import javax.swing.{JFrame, SwingUtilities}   class KeypressCheck() extends JFrame {   addKeyListener(new KeyAdapter() { override def keyPressed(e: KeyEvent): Unit = { val keyCode = e.getKeyCode if (keyCode == KeyEvent.VK_ENTER) { dispose() ...
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Euler_Math_Toolbox
Euler Math Toolbox
  >type kmeanscluster function kmeanscluster (x: numerical, k: index) n=rows(x); m=cols(x); i=floor((0:k)/k*(n-1))+1; means=zeros(k,m); loop 1 to k; means[#]=sum(x[i[#]:(i[#+1]-1)]')'/(i[#+1]-i[#]); end; j=1:n; loop 1 to n; d=sum((x[#]-means)^2); j[#]=extre...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Factor
Factor
USING: io math math.parser prettyprint sequences splitting ; IN: rosetta-code.kernighan   lines [ "\s" split last string>number 6 > ] filter .
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#FreeBASIC
FreeBASIC
  Dim As Long f f = Freefile Dim As String nomArchivo = "data.txt"   If Open(nomArchivo For Input As #f) Then Print "ERROR: No se pudo abrir " ; nomArchivo Sleep : End End If   Dim As String tok(), lin Do While Not Eof(f) Line Input #f, lin If Val(Right(lin, 3)) > 6 Then Print lin Loop Close #f Sleep  
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Amazing_Hopper
Amazing Hopper
  #!/usr/bin/hopper   #include <hopper.h>   main:   hxres = 500 // horizontal resolution hyres = 500 // vertical resolution   itermax = 100 // maximum iters to do   brk_out = 64 // |z|^2 greater than this is a breakout magnify = 1 // 10 is standard magn...
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...
#JavaScript
JavaScript
var gold = { 'value': 2500, 'weight': 2.0, 'volume': 0.002 }, panacea = { 'value': 3000, 'weight': 0.3, 'volume': 0.025 }, ichor = { 'value': 1800, 'weight': 0.2, 'volume': 0.015 },   items = [gold, panacea, ichor], knapsack = {'weight': 25, 'volume': 0.25}, max_val = 0, solutions = [], g, p...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#OCaml
OCaml
let attrs = Unix.(tcgetattr stdin) let buf = Bytes.create 1   let prompt switch = Unix.(tcsetattr stdin TCSAFLUSH) @@ if switch then { attrs with c_icanon = false } else attrs   let getchar () = let len = Unix.(read stdin) buf 0 1 in if len = 0 then raise End_of_file else Bytes.get buf 0
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Oforth
Oforth
import: console   : YorN | c | System.Console flush doWhile: [ System.Console receiveChar toUpper ->c c 'Y' <> c 'N' <> and ] c ;
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...
#Kotlin
Kotlin
// version 1.1.2   data class Item(val name: String, val weight: Double, val value: Double)   val items = mutableListOf( Item("beef", 3.8, 36.0), Item("pork", 5.4, 43.0), Item("ham", 3.6, 90.0), Item("greaves", 2.4, 45.0), Item("flitch", 4.0, 30.0), Item("brawn", 2.5, 56.0), Item("welt", 3.7...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#OxygenBasic
OxygenBasic
  type KnapSackItem string name,sys dag,value,tag   KnapSackItem it[100]   sys dmax=400 sys items=22   it=>   "map", 9, 150, 0, "compass", 13, 35, 0, "water", 153, 200, 0, "sandwich", 50, 160, 0, "glucose", 15, 60, 0, "tin", 6...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. JUMPS-PROGRAM. * Nobody writes like this, of course; but... PROCEDURE DIVISION. * You can jump anywhere you like. START-PARAGRAPH. GO TO AN-ARBITRARY-PARAGRAPH. YET-ANOTHER-PARAGRAPH. ALTER START-PARAGRAPH TO PROCEED TO A-PARAGRAPH-SOMEWHERE. * That's right, folks: we don't ...
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Unbounded;   procedure Knapsack_01 is package US renames Ada.Strings.Unbounded;   type Item is record Name  : US.Unbounded_String; Weight : Positive; Value  : Positive; Taken  : Boolean; end record;   type Item_Array is array (Positive range <>) 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. ...
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Fixed;   procedure Kaprekar2 is use Ada.Strings.Fixed;   To_Digit : constant String := "0123456789abcdefghijklmnopqrstuvwxyz";   type Int is mod 2 ** 64; subtype Base_Number is Int range 2 .. 36;   From_Digit : constant array (Character) of Int := ('0' => 0, ...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#BQN
BQN
Juggle ← { Step ← ⌊⊢⋆(0.5 + 2|⊢) ¯1‿0‿0 + 3↑{ n‿imax‿max‿term ← 𝕩 𝕊⍟(term≠1) ⟨n+1, (max<term)⊑imax‿n, max⌈term, Step term⟩ } 0‿0‿0‿𝕩 }   >⟨"NLIH"⟩ ∾ (⊢∾Juggle)¨ 20+↕20
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#C.2B.2B
C++
#include <cassert> #include <iomanip> #include <iostream> #include <string>   #include <gmpxx.h>   using big_int = mpz_class;   auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else ...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Go
Go
// Implmentation following pseudocode from "An intoductory tutorial on kd-trees" // by Andrew W. Moore, Carnegie Mellon University, PDF accessed from // http://www.autonlab.org/autonweb/14665 package main   import ( "fmt" "math" "math/rand" "sort" "time" )   // point is a k-dimensional point. type p...
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...
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1 ; Uncomment if Gdip.ahk is not in your standard library ;#Include, Gdip.ahk If !pToken := Gdip_Startup(){ MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system. ExitApp } ; I've added a simple new function here, just to 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...
#C.2B.2B
C++
#include <cstdlib> #include <algorithm> #include <iterator>   template<typename RandomAccessIterator> void knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) { for(unsigned int n = end - begin - 1; n >= 1; --n) { unsigned int k = rand() % (n + 1); if(k != n) { std::iter_swap(begin + k, b...
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Seed7
Seed7
if keypressed(KEYBOARD) then writeln("A key was pressed"); else writeln("No key was pressed"); end if;
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Tcl
Tcl
fconfigure stdin -blocking 0 set ch [read stdin 1] fconfigure stdin -blocking 1   if {$ch eq ""} { # Nothing was read } else { # Got the character $ch }
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#TI-83_BASIC
TI-83 BASIC
  :getKey→G  
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Wee_Basic
Wee Basic
let keycode=0 print 1 "Press any key and its key code will appear." while keycode=0 let keycode=key() wend print 1 keycode end
http://rosettacode.org/wiki/K-means%2B%2B_clustering
K-means++ clustering
K-means++ clustering K-means This data was partitioned into 7 clusters using the K-means algorithm. The task is to implement the K-means++ algorithm. Produce a function which takes two arguments: the number of clusters K, and the dataset to classify. K is a positive integer and the dataset is a list of points in the C...
#Fortran
Fortran
  *********************************************************************** * KMPP - K-Means++ - Traditional data clustering with a special initialization * Public Domain - This program may be used by any person for any purpose. * * Origin: * Hugo Steinhaus, 1956 * * Refer to: * "kmeans++: the advantages of careful...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Go
Go
package main   import ( "bufio" "fmt" "os" "strconv" "strings" )   func main() { f, err := os.Open("data.txt") if err != nil { fmt.Println("Unable to open the file") return } defer f.Close() fmt.Println("Those earthquakes with a magnitude > 6.0 are:\n") input ...
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Groovy
Groovy
import java.util.regex.Pattern   class LargeEarthquake { static void main(String[] args) { def r = Pattern.compile("\\s+") println("Those earthquakes with a magnitude > 6.0 are:\n") def f = new File("data.txt") f.eachLine { it -> if (r.split(it)[2].toDouble() > 6.0) { ...
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#AWK
AWK
  # syntax: GAWK -f JULIA_SET.AWK [real imaginary] BEGIN { c_real = (ARGV[1] != "") ? ARGV[1] : -0.8 c_imaginary = (ARGV[2] != "") ? ARGV[2] : 0.156 printf("%s %s\n",c_real,c_imaginary) for (v=-100; v<=100; v+=10) { for (h=-280; h<=280; h+=10) { x = h / 200 y = v / 100 ...
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...
#jq
jq
def Item($name; $value; $weight; $volume): {$name, $value, $weight, $volume};   def items:[ Item("panacea"; 3000; 0.3; 0.025), Item("ichor"; 1800; 0.2; 0.015), Item("gold"; 2500; 2; 0.002) ];   def array($init): [range(0; .) | $init];   # input: {count, best, bestvalue} def knapsack($i; $value; $weight; $...
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#OpenEdge.2FProgress
OpenEdge/Progress
DEF VAR lanswer AS LOGICAL INITIAL ?.   DO WHILE lanswer = ?: READKEY. IF CHR( LASTKEY ) = "n" OR CHR( LASTKEY ) = "y" THEN lanswer = CHR( LASTKEY ) = "y". END.   MESSAGE lanswer VIEW-AS ALERT-BOX.
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#PARI.2FGP
PARI/GP
Program ObtainYN;   uses crt;   var key: char;   begin write('Your answer? (Y/N): '); repeat key := readkey; until (key in ['Y', 'y', 'N', 'n']); writeln; writeln ('Your answer was: ', key); end.
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#M2000_Interpreter
M2000 Interpreter
  Module Knapsack { Form 60, 40 Cls 5, 0 Pen 14 Class Quick { Private: partition=lambda-> { Read &A(), p, r : i = p-1 : x=A(r) For j=p to r-1 {If .LE(A(j), x) Then i++:Swap A(i),A(j) } : Swap A(i+1), A(r) : Push i+2, i ...
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Oz
Oz
declare %% maps items to tuples of %% Weight(hectogram), Value and available Pieces Problem = knapsack('map':9#150#1 'compass':13#35#1 'water':153#200#2 'sandwich':50#60#2 'glucose':15#60#2 'tin':68#45#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...
#Common_Lisp
Common Lisp
  (tagbody beginning (format t "I am in the beginning~%") (sleep 1) (go end) middle (format t "I am in the middle~%") (sleep 1) (go beginning) end (format t "I am in the end~%") (sleep 1) (go middle))  
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...
#Computer.2Fzero_Assembly
Computer/zero Assembly
LDA goto SUB somewhere ADD somewhereElse STA goto goto: JMP somewhere
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...
#APL
APL
∇ ret←NapSack;sum;b;list;total [1] total←400 [2] list←("map" 9 150)("compass" 13 35)("water" 153 200)("sandwich" 50 160)("glucose" 15 60) ("tin" 68 45)("banana" 27 60)("apple" 39 40)("cheese" 23 30)("beer" 52 10) ("suntan cream" 11 70)("camera" 32 30)("t-shirt" 24 15)("trousers" 48 10) ("umbrella" 73 40)("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. ...
#ALGOL_68
ALGOL 68
# find some Kaprekar numbers #   # returns TRUE if n is a Kaprekar number, FALSE otherwise # PROC is kaprekar = ( INT n )BOOL: IF n < 1 THEN # 0 and -ve numbers are not Kaprekar numbers # FALSE ELIF n = 1 THEN # 1 is defined to be a Kaprekar number ...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#F.23
F#
  // Juggler sequence. Nigel Galloway: August 19th., 2021 let J n=Seq.unfold(fun(n,i,g,l)->if n=1I then None else let e=match n.IsEven with true->Isqrt n |_->Isqrt(n**3) in Some((i,g,l),if e>i then (e,e,l+1,l+1) else (e,i,g,l+1)))(n,n,0,0)|>Seq.last printfn " n l[n] i[n] h[n]\n___________________"; [20I..39I]|>Seq.it...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Factor
Factor
USING: combinators formatting generalizations io kernel math math.extras math.functions.integer-logs math.order math.ranges sequences strings tools.memory.private ;   : next ( m -- n ) dup odd? [ dup dup * * ] when integer-sqrt ;   : new-max ( l i h a -- l i h a ) [ drop dup ] 2dip nip dup ;   : (step) ( l i h ...
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Go
Go
package main   import ( "fmt" "log" //"math/big" big "github.com/ncw/gmp" "rcu" )   var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2)   func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } cou...
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).
#11l
11l
T.serializable Person String firstName, lastName Int age T PhoneNumber String ntype String number [PhoneNumber] phoneNumbers [String] children   Person p   json:to_object(‘ { "firstName": "John", "lastName": "Smith", "age": 27, "phoneNumbers": [ { "ntype": "home", "num...
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Action.21
Action!
BYTE lastStick=[255] BYTE lastTrig=[255]   PROC DrawCross(BYTE s) BYTE size=[5] CARD x BYTE y   IF s>=9 AND s<=11 THEN x=size ELSEIF s>=5 AND s<=7 THEN x=159-size ELSE x=79 FI   IF s=6 OR s=10 OR s=14 THEN y=size ELSEIF s=5 OR s=9 OR s=13 THEN y=79-size ELSE y=39 FI   Plo...
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Haskell
Haskell
import System.Random import Data.List (sortBy, genericLength, minimumBy) import Data.Ord (comparing)   -- A finite list of dimensional accessors tell a KDTree how to get a -- Euclidean dimensional value 'b' out of an arbitrary datum 'a'. type DimensionalAccessors a b = [a -> b]   -- A binary tree structure of 'a'. 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...
#AWK
AWK
  # syntax: GAWK -f KNIGHTS_TOUR.AWK [-v sr=x] [-v sc=x] # # examples: # GAWK -f KNIGHTS_TOUR.AWK (default) # GAWK -f KNIGHTS_TOUR.AWK -v sr=1 -v sc=1 start at top left (default) # GAWK -f KNIGHTS_TOUR.AWK -v sr=1 -v sc=8 start at top right # GAWK -f KNIGHTS_TOUR.AWK -v sr=8 -v sc=8 star...