code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
_, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
gc.FlushInput()
} | 681Keyboard input/Flush the keyboard buffer
| 0go
| ykp64 |
package main
import "fmt"
type Item struct {
name string
weight, value, qty int
}
var items = []Item{
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", 50, 60, 2},
{"glucose", 15, 60, 2},
{"tin", 68, 45, 3},
{"banana", 27, 60, 3},
{"apple", 39, 40, 3},
{"cheese", 23, 30, 1},
{"beer", 52, 10, 3},
{"suntancream", 11, 70, 1},
{"camera", 32, 30, 1},
{"T-shirt", 24, 15, 2},
{"trousers", 48, 10, 2},
{"umbrella", 73, 40, 1},
{"w-trousers", 42, 70, 1},
{"w-overclothes", 43, 75, 1},
{"note-case", 22, 80, 1},
{"sunglasses", 7, 20, 1},
{"towel", 18, 12, 2},
{"socks", 4, 50, 1},
{"book", 30, 10, 2},
}
type Chooser struct {
Items []Item
cache map[key]solution
}
type key struct {
w, p int
}
type solution struct {
v, w int
qty []int
}
func (c Chooser) Choose(limit int) (w, v int, qty []int) {
c.cache = make(map[key]solution)
s := c.rchoose(limit, len(c.Items)-1)
c.cache = nil | 678Knapsack problem/Bounded
| 0go
| 5qiul |
import Control.Concurrent (threadDelay)
import Control.Monad (when)
import System.IO (hFlush, stdout)
import System.Posix
termFlush :: Fd -> IO ()
termFlush fd = do
isTerm <- queryTerminal fd
when isTerm $ discardData fd InputQueue
main :: IO ()
main = do
putStrLn "Type some stuff...\n"
threadDelay $ 3 * 1000000
putStrLn "\n\nOk, stop typing!\n"
threadDelay $ 2 * 1000000
termFlush stdInput
putStr "\n\nType a line of text, ending with a newline: "
hFlush stdout
line <- getLine
putStrLn $ "You typed: " ++ line
termFlush stdInput | 681Keyboard input/Flush the keyboard buffer
| 8haskell
| hnfju |
package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the%c!\n", k)
s.Refresh()
s.GetChar()
} | 676Keyboard input/Obtain a Y or N response
| 0go
| bf9kh |
def totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() }
def totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }
def knapsackBounded = { possibleItems ->
def n = possibleItems.size()
def m = (0..n).collect{ i -> (0..400).collect{ w -> []} }
(1..400).each { w ->
(1..n).each { i ->
def item = possibleItems[i-1]
def wi = item.weight, pi = item.pieces
def bi = [w.intdiv(wi),pi].min()
m[i][w] = (0..bi).collect{ count ->
m[i-1][w - wi * count] + [[item:item, count:count]]
}.max(totalValue).findAll{ it.count }
}
}
m[n][400]
} | 678Knapsack problem/Bounded
| 7groovy
| c1q9i |
null | 681Keyboard input/Flush the keyboard buffer
| 11kotlin
| c1e98 |
inv = [("map",9,150,1), ("compass",13,35,1), ("water",153,200,2), ("sandwich",50,60,2),
("glucose",15,60,2), ("tin",68,45,3), ("banana",27,60,3), ("apple",39,40,3),
("cheese",23,30,1), ("beer",52,10,3), ("cream",11,70,1), ("camera",32,30,1),
("tshirt",24,15,2), ("trousers",48,10,2), ("umbrella",73,40,1), ("wtrousers",42,70,1),
("woverclothes",43,75,1), ("notecase",22,80,1), ("sunglasses",7,20,1), ("towel",18,12,2),
("socks",4,50,1), ("book",30,10,2)]
knapsack = foldr addItem (repeat (0,[])) where
addItem (name,w,v,c) old = foldr inc old [1..c] where
inc i list = left ++ zipWith max right new where
(left, right) = splitAt (w * i) list
new = map (\(val,itms)->(val + v * i, (name,i):itms)) old
main = print $ (knapsack inv) !! 400 | 678Knapsack problem/Bounded
| 8haskell
| xmvw4 |
package main
import (
"log"
"time"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
gc.Cursor(0)
s.Move(20, 0)
s.Print("Key check in ")
for i := 3; i >= 1; i-- {
s.MovePrint(20, 13, i)
s.Refresh()
time.Sleep(500 * time.Millisecond)
} | 680Keyboard input/Keypress check
| 0go
| 4so52 |
import System.IO
hFlushInput :: Handle -> IO ()
hFlushInput hdl = do
r <- hReady hdl
if r then do
c <- hGetChar hdl
hFlushInput hdl
else
return ()
yorn :: IO Char
yorn = do
c <- getChar
if c == 'Y' || c == 'N' then return c
else if c == 'y' then return 'Y'
else if c == 'n' then return 'N'
else yorn
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
putStr "Press Y or N to continue: "
hSetBuffering stdin NoBuffering
hSetEcho stdin False
hFlushInput stdin
answer <- yorn
putStrLn [answer] | 676Keyboard input/Obtain a Y or N response
| 8haskell
| d4bn4 |
Shoes.app do
@info = para
keypress do |k|
@info.replace
end
end | 675Keyboard macros
| 14ruby
| d4pns |
import Control.Concurrent
import Control.Monad
import Data.Maybe
import System.IO
main = do
c <- newEmptyMVar
hSetBuffering stdin NoBuffering
forkIO $ do
a <- getChar
putMVar c a
putStrLn $ "\nChar '" ++ [a] ++
"' read and stored in MVar"
wait c
where wait c = do
a <- tryTakeMVar c
if isJust a then return ()
else putStrLn "Awaiting char.." >>
threadDelay 500000 >> wait c | 680Keyboard input/Keypress check
| 8haskell
| q92x9 |
use Term::ReadKey;
ReadMode 'restore';
use Term::ReadKey;
ReadMode 'cbreak';
while (defined ReadKey -1) {
}
ReadMode 'restore'; | 681Keyboard input/Flush the keyboard buffer
| 2perl
| xmcw8 |
import java.awt.event.{KeyAdapter, KeyEvent}
import javax.swing.{JFrame, JLabel, WindowConstants}
object KeyboardMacroDemo extends App {
val directions = "<html><b>Ctrl-S</b> to show frame title<br>" + "<b>Ctrl-H</b> to hide it</html>"
new JFrame {
add(new JLabel(directions))
addKeyListener(new KeyAdapter() {
override def keyReleased(e: KeyEvent): Unit = {
if (e.isControlDown && e.getKeyCode == KeyEvent.VK_S) setTitle("Hello there")
else if (e.isControlDown && e.getKeyCode == KeyEvent.VK_H) setTitle("")
}
})
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setVisible(true)
}
} | 675Keyboard macros
| 16scala
| 3jwzy |
package hu.pj.alg.test;
import hu.pj.alg.BoundedKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class BoundedKnapsackForTourists {
public BoundedKnapsackForTourists() {
BoundedKnapsack bok = new BoundedKnapsack(400); | 678Knapsack problem/Bounded
| 9java
| bfyk3 |
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
Test() {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Test f = new Test();
f.setFocusable(true);
f.setVisible(true);
});
}
} | 680Keyboard input/Keypress check
| 9java
| pt6b3 |
let thePressedKey;
function handleKey(evt) {
thePressedKey = evt;
console.log(thePressedKey);
}
document.addEventListener('keydown', handleKey); | 680Keyboard input/Keypress check
| 10javascript
| xmlw9 |
def flush_input():
try:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch()
except ImportError:
import sys, termios
termios.tcflush(sys.stdin, termios.TCIOFLUSH) | 681Keyboard input/Flush the keyboard buffer
| 3python
| q9lxi |
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
var wait_key = async function() {
return await new Promise(function(resolve,reject) {
var key_listen = function(str,key) {
process.stdin.removeListener('keypress', key_listen);
resolve(str);
}
process.stdin.on('keypress', key_listen);
});
}
var done = function() {
process.exit();
}
var go = async function() {
do {
console.log('Press any key...');
var key = await wait_key();
console.log("Key pressed is",key);
await new Promise(function(resolve) { setTimeout(resolve,1000); });
} while(key != 'y');
done();
}
go(); | 676Keyboard input/Obtain a Y or N response
| 10javascript
| n5kiy |
<html><head><title></title></head><body></body></html>
<script type="text/javascript">
var data= [
{name: 'map', weight: 9, value:150, pieces:1},
{name: 'compass', weight: 13, value: 35, pieces:1},
{name: 'water', weight:153, value:200, pieces:2},
{name: 'sandwich', weight: 50, value: 60, pieces:2},
{name: 'glucose', weight: 15, value: 60, pieces:2},
{name: 'tin', weight: 68, value: 45, pieces:3},
{name: 'banana', weight: 27, value: 60, pieces:3},
{name: 'apple', weight: 39, value: 40, pieces:3},
{name: 'cheese', weight: 23, value: 30, pieces:1},
{name: 'beer', weight: 52, value: 10, pieces:3},
{name: 'suntan, cream', weight: 11, value: 70, pieces:1},
{name: 'camera', weight: 32, value: 30, pieces:1},
{name: 'T-shirt', weight: 24, value: 15, pieces:2},
{name: 'trousers', weight: 48, value: 10, pieces:2},
{name: 'umbrella', weight: 73, value: 40, pieces:1},
{name: 'waterproof, trousers', weight: 42, value: 70, pieces:1},
{name: 'waterproof, overclothes',weight: 43, value: 75, pieces:1},
{name: 'note-case', weight: 22, value: 80, pieces:1},
{name: 'sunglasses', weight: 7, value: 20, pieces:1},
{name: 'towel', weight: 18, value: 12, pieces:2},
{name: 'socks', weight: 4, value: 50, pieces:1},
{name: 'book', weight: 30, value: 10, pieces:2}
];
function findBestPack() {
var m= [[0]]; | 678Knapsack problem/Bounded
| 10javascript
| wy2e2 |
null | 680Keyboard input/Keypress check
| 11kotlin
| 7odr4 |
package main
import (
"fmt"
"sort"
)
type item struct {
item string
weight float64
price float64
}
type items []item
var all = items{
{"beef", 3.8, 36},
{"pork", 5.4, 43},
{"ham", 3.6, 90},
{"greaves", 2.4, 45},
{"flitch", 4.0, 30},
{"brawn", 2.5, 56},
{"welt", 3.7, 67},
{"salami", 3.0, 95},
{"sausage", 5.9, 98},
} | 677Knapsack problem/Continuous
| 0go
| n5hi1 |
null | 676Keyboard input/Obtain a Y or N response
| 11kotlin
| a3213 |
import static java.math.RoundingMode.*
def knapsackCont = { list, maxWeight = 15.0 ->
list.sort{ it.weight / it.value }
def remainder = maxWeight
List sack = []
for (item in list) {
if (item.weight < remainder) {
sack << [name: item.name, weight: item.weight,
value: (item.value as BigDecimal).setScale(2, HALF_UP)]
} else {
sack << [name: item.name, weight: remainder,
value: (item.value * remainder / item.weight).setScale(2, HALF_UP)]
break
}
remainder -= item.weight
}
sack
} | 677Knapsack problem/Continuous
| 7groovy
| sc4q1 |
require 'io/console'
$stdin.iflush | 681Keyboard input/Flush the keyboard buffer
| 14ruby
| 0lvsu |
def flush() { out.flush() } | 681Keyboard input/Flush the keyboard buffer
| 16scala
| n5gic |
package main
import "fmt"
type Item struct {
Name string
Value int
Weight, Volume float64
}
type Result struct {
Counts []int
Sum int
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func Knapsack(items []Item, weight, volume float64) (best Result) {
if len(items) == 0 {
return
}
n := len(items) - 1
maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
for count := 0; count <= maxCount; count++ {
sol := Knapsack(items[:n],
weight-float64(count)*items[n].Weight,
volume-float64(count)*items[n].Volume)
sol.Sum += items[n].Value * count
if sol.Sum > best.Sum {
sol.Counts = append(sol.Counts, count)
best = sol
}
}
return
}
func main() {
items := []Item{
{"Panacea", 3000, 0.3, 0.025},
{"Ichor", 1800, 0.2, 0.015},
{"Gold", 2500, 2.0, 0.002},
}
var sumCount, sumValue int
var sumWeight, sumVolume float64
result := Knapsack(items, 25, 0.25)
for i := range result.Counts {
fmt.Printf("%-8s x%3d -> Weight:%4.1f Volume:%5.3f Value:%6d\n",
items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])
sumCount += result.Counts[i]
sumValue += items[i].Value * result.Counts[i]
sumWeight += items[i].Weight * float64(result.Counts[i])
sumVolume += items[i].Volume * float64(result.Counts[i])
}
fmt.Printf("TOTAL (%3d items) Weight:%4.1f Volume:%5.3f Value:%6d\n",
sumCount, sumWeight, sumVolume, sumValue)
} | 679Knapsack problem/Unbounded
| 0go
| vw02m |
import Data.List (sortBy)
import Data.Ord (comparing)
import Text.Printf (printf)
import Control.Monad (forM_)
import Data.Ratio (numerator, denominator)
maxWgt :: Rational
maxWgt = 15
data Bounty = Bounty
{ itemName :: String
, itemVal, itemWgt :: Rational
}
items :: [Bounty]
items =
[ Bounty "beef" 36 3.8
, Bounty "pork" 43 5.4
, Bounty "ham" 90 3.6
, Bounty "greaves" 45 2.4
, Bounty "flitch" 30 4.0
, Bounty "brawn" 56 2.5
, Bounty "welt" 67 3.7
, Bounty "salami" 95 3.0
, Bounty "sausage" 98 5.9
]
solution :: [(Rational, Bounty)]
solution = g maxWgt $ sortBy (flip $ comparing f) items
where
g room (b@(Bounty _ _ w):bs) =
if w < room
then (w, b): g (room - w) bs
else [(room, b)]
f (Bounty _ v w) = v / w
main :: IO ()
main = do
forM_ solution $ \(w, b) -> printf "%s kg of%s\n" (mixedNum w) (itemName b)
(printf "Total value:%s\n" . mixedNum . sum) $ f <$> solution
where
f (w, Bounty _ v wtot) = v * (w / wtot)
mixedNum q =
if b == 0
then show a
else printf "%d%d/%d" a (numerator b) (denominator b)
where
a = floor q
b = q - toEnum a | 677Knapsack problem/Continuous
| 8haskell
| uxiv2 |
null | 678Knapsack problem/Bounded
| 11kotlin
| r8fgo |
while read line
do
[[ ${line
done < data.txt | 682Kernighans large earthquake problem
| 4bash
| d4gnp |
def totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() }
def totalVolume = { list -> list.collect{ it.item.volume * it.count }.sum() }
def totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }
def knapsackUnbounded = { possibleItems, BigDecimal weightMax, BigDecimal volumeMax ->
def n = possibleItems.size()
def wm = weightMax.unscaledValue()
def vm = volumeMax.unscaledValue()
def m = (0..n).collect{ i -> (0..wm).collect{ w -> (0..vm).collect{ v -> [] } } }
(1..wm).each { w ->
(1..vm).each { v ->
(1..n).each { i ->
def item = possibleItems[i-1]
def wi = item.weight.unscaledValue()
def vi = item.volume.unscaledValue()
def bi = [w.intdiv(wi),v.intdiv(vi)].min()
m[i][w][v] = (0..bi).collect{ count ->
m[i-1][w - wi * count][v - vi * count] + [[item:item, count:count]]
}.max(totalValue).findAll{ it.count }
}
}
}
m[n][wm][vm]
} | 679Knapsack problem/Unbounded
| 7groovy
| mbey5 |
use strict;
use warnings;
use Term::ReadKey;
ReadMode 4;
my $key;
until(defined($key = ReadKey(-1))){
sleep 1;
}
print "got key '$key'\n";
ReadMode('restore'); | 680Keyboard input/Keypress check
| 2perl
| fgjd7 |
int main() {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
char *lw, *lt;
fp = fopen(, );
if (fp == NULL) {
printf();
exit(1);
}
printf();
while ((read = getline(&line, &len, fp)) != EOF) {
if (read < 2) continue;
lw = strrchr(line, ' ');
lt = strrchr(line, '\t');
if (!lw && !lt) continue;
if (lt > lw) lw = lt;
if (atof(lw + 1) > 6.0) printf(, line);
}
fclose(fp);
if (line) free(line);
return 0;
} | 682Kernighans large earthquake problem
| 5c
| tr7f4 |
import Data.List (maximumBy)
import Data.Ord (comparing)
(maxWgt, maxVol) = (25, 0.25)
items =
[Bounty "panacea" 3000 0.3 0.025,
Bounty "ichor" 1800 0.2 0.015,
Bounty "gold" 2500 2.0 0.002]
data Bounty = Bounty
{itemName :: String,
itemVal :: Int,
itemWgt, itemVol :: Double}
names = map itemName items
vals = map itemVal items
wgts = map itemWgt items
vols = map itemVol items
dotProduct :: (Num a, Integral b) => [a] -> [b] -> a
dotProduct factors = sum . zipWith (*) factors . map fromIntegral
options :: [[Int]]
options = filter fits $ mapM f items
where f (Bounty _ _ w v) = [0 .. m]
where m = floor $ min (maxWgt / w) (maxVol / v)
fits opt = dotProduct wgts opt <= maxWgt &&
dotProduct vols opt <= maxVol
showOpt :: [Int] -> String
showOpt opt = concat (zipWith showItem names opt) ++
"total weight: " ++ show (dotProduct wgts opt) ++
"\ntotal volume: " ++ show (dotProduct vols opt) ++
"\ntotal value: " ++ show (dotProduct vals opt) ++ "\n"
where showItem name num = name ++ ": " ++ show num ++ "\n"
main = putStr $ showOpt $ best options
where best = maximumBy $ comparing $ dotProduct vals | 679Knapsack problem/Unbounded
| 8haskell
| e6cai |
struct kd_node_t{
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
inline double
dist(struct kd_node_t *a, struct kd_node_t *b, int dim)
{
double t, d = 0;
while (dim--) {
t = a->x[dim] - b->x[dim];
d += t * t;
}
return d;
}
inline void swap(struct kd_node_t *x, struct kd_node_t *y) {
double tmp[MAX_DIM];
memcpy(tmp, x->x, sizeof(tmp));
memcpy(x->x, y->x, sizeof(tmp));
memcpy(y->x, tmp, sizeof(tmp));
}
struct kd_node_t*
find_median(struct kd_node_t *start, struct kd_node_t *end, int idx)
{
if (end <= start) return NULL;
if (end == start + 1)
return start;
struct kd_node_t *p, *store, *md = start + (end - start) / 2;
double pivot;
while (1) {
pivot = md->x[idx];
swap(md, end - 1);
for (store = p = start; p < end; p++) {
if (p->x[idx] < pivot) {
if (p != store)
swap(p, store);
store++;
}
}
swap(store, end - 1);
if (store->x[idx] == md->x[idx])
return md;
if (store > md) end = store;
else start = store;
}
}
struct kd_node_t*
make_tree(struct kd_node_t *t, int len, int i, int dim)
{
struct kd_node_t *n;
if (!len) return 0;
if ((n = find_median(t, t + len, i))) {
i = (i + 1) % dim;
n->left = make_tree(t, n - t, i, dim);
n->right = make_tree(n + 1, t + len - (n + 1), i, dim);
}
return n;
}
int visited;
void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim,
struct kd_node_t **best, double *best_dist)
{
double d, dx, dx2;
if (!root) return;
d = dist(root, nd, dim);
dx = root->x[i] - nd->x[i];
dx2 = dx * dx;
visited ++;
if (!*best || d < *best_dist) {
*best_dist = d;
*best = root;
}
if (!*best_dist) return;
if (++i >= dim) i = 0;
nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist);
if (dx2 >= *best_dist) return;
nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist);
}
int main(void)
{
int i;
struct kd_node_t wp[] = {
{{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
};
struct kd_node_t testNode = {{9, 2}};
struct kd_node_t *root, *found, *million;
double best_dist;
root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 2, &found, &best_dist);
printf(
,
testNode.x[0], testNode.x[1],
found->x[0], found->x[1], sqrt(best_dist), visited);
million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t));
srand(time(0));
for (i = 0; i < N; i++) rand_pt(million[i]);
root = make_tree(million, N, 0, 3);
rand_pt(testNode);
visited = 0;
found = 0;
nearest(root, &testNode, 0, 3, &found, &best_dist);
printf(
,
testNode.x[0], testNode.x[1], testNode.x[2],
found->x[0], found->x[1], found->x[2],
sqrt(best_dist), visited);
int sum = 0, test_runs = 100000;
for (i = 0; i < test_runs; i++) {
found = 0;
visited = 0;
rand_pt(testNode);
nearest(root, &testNode, 0, 3, &found, &best_dist);
sum += visited;
}
printf(
,
sum, test_runs, sum/(double)test_runs);
return 0;
} | 683K-d tree
| 5c
| 2eelo |
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
except ImportError:
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def keypress():
global char
char = getch()
def main():
global char
char = None
_thread.start_new_thread(keypress, ())
while True:
if char is not None:
try:
print( + char.decode('utf-8'))
except UnicodeDecodeError:
print()
char = None
_thread.start_new_thread(keypress, ())
if char == 'q' or char == '\x1b':
exit()
char = None
print()
time.sleep(1)
if __name__ == :
main() | 680Keyboard input/Keypress check
| 3python
| trhfw |
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); | 677Knapsack problem/Continuous
| 9java
| mbxym |
if (x > 0) goto positive;
else goto negative;
positive:
printf(); goto both;
negative:
printf();
both:
... | 684Jump anywhere
| 5c
| ptfby |
typedef struct {
double x;
double y;
int group;
} POINT;
POINT * gen_xy(int num_pts, double radius)
{
int i;
double ang, r;
POINT * pts;
pts = (POINT*) malloc(sizeof(POINT) * num_pts);
for ( i = 0; i < num_pts; i++ ) {
ang = 2.0 * M_PI * rand() / (RAND_MAX - 1.);
r = radius * rand() / (RAND_MAX - 1.);
pts[i].x = r * cos(ang);
pts[i].y = r * sin(ang);
}
return pts;
}
double dist2(POINT * a, POINT * b)
{
double x = a->x - b->x;
double y = a->y - b->y;
return x*x + y*y;
}
int nearest(POINT * pt, POINT * cent, int n_cluster)
{
int i, clusterIndex;
double d, min_d;
min_d = HUGE_VAL;
clusterIndex = pt->group;
for (i = 0; i < n_cluster; i++) {
d = dist2(¢[i], pt);
if ( d < min_d ) {
min_d = d;
clusterIndex = i;
}
}
return clusterIndex;
}
double nearestDistance(POINT * pt, POINT * cent, int n_cluster)
{
int i;
double d, min_d;
min_d = HUGE_VAL;
for (i = 0; i < n_cluster; i++) {
d = dist2(¢[i], pt);
if ( d < min_d ) {
min_d = d;
}
}
return min_d;
}
int bisectionSearch(double *x, int n, double v)
{
int il, ir, i;
if (n < 1) {
return 0;
}
if (v < x[0]) {
return 0;
}
else if (v > x[n-1]) {
return n - 1;
}
il = 0;
ir = n - 1;
i = (il + ir) / 2;
while ( i != il ) {
if (x[i] <= v) {
il = i;
} else {
ir = i;
}
i = (il + ir) / 2;
}
if (x[i] <= v)
i = ir;
return i;
}
void kppAllinger(POINT * pts, int num_pts, POINT * centroids,
int num_clusters)
{
int j;
int selectedIndex;
int cluster;
double sum;
double d;
double random;
double * cumulativeDistances;
double * shortestDistance;
cumulativeDistances = (double*) malloc(sizeof(double) * num_pts);
shortestDistance = (double*) malloc(sizeof(double) * num_pts);
selectedIndex = rand() % num_pts;
centroids[0] = pts[ selectedIndex ];
for (j = 0; j < num_pts; ++j)
shortestDistance[j] = HUGE_VAL;
for (cluster = 1; cluster < num_clusters; cluster++) {
for ( j = 0; j < num_pts; j++ ) {
d = dist2(&pts[j], ¢roids[cluster-1] );
if (d < shortestDistance[j])
shortestDistance[j] = d;
}
sum = 0.0;
for (j = 0; j < num_pts; j++) {
sum += shortestDistance[j];
cumulativeDistances[j] = sum;
}
random = (float) rand() / (float) RAND_MAX * sum;
selectedIndex = bisectionSearch(cumulativeDistances, num_pts, random);
centroids[cluster] = pts[selectedIndex];
}
for (j = 0; j < num_pts; j++)
pts[j].group = nearest(&pts[j], centroids, num_clusters);
free(shortestDistance);
free(cumulativeDistances);
return;
}
void kpp(POINT * pts, int num_pts, POINT * centroids,
int num_clusters)
{
int j;
int cluster;
double sum;
double * distances;
distances = (double*) malloc(sizeof(double) * num_pts);
centroids[0] = pts[ rand() % num_pts ];
for (cluster = 1; cluster < num_clusters; cluster++) {
sum = 0.0;
for ( j = 0; j < num_pts; j++ ) {
distances[j] =
nearestDistance(&pts[j], centroids, cluster);
sum += distances[j];
}
sum = sum * rand() / (RAND_MAX - 1);
for (j = 0; j < num_pts; j++ ) {
sum -= distances[j];
if ( sum <= 0)
{
centroids[cluster] = pts[j];
break;
}
}
}
for (j = 0; j < num_pts; j++)
pts[j].group = nearest(&pts[j], centroids, num_clusters);
free(distances);
return;
}
POINT * lloyd(POINT * pts, int num_pts, int num_clusters, int maxTimes)
{
int i, clusterIndex;
int changes;
int acceptable = num_pts / 1000;
if (num_clusters == 1 || num_pts <= 0 || num_clusters > num_pts )
return 0;
POINT * centroids = (POINT *)malloc(sizeof(POINT) * num_clusters);
if ( maxTimes < 1 )
maxTimes = 1;
kppAllinger(pts, num_pts, centroids, num_clusters);
do {
for ( i = 0; i < num_clusters; i++ ) {
centroids[i].group = 0;
centroids[i].x = 0;
centroids[i].y = 0;
}
for (i = 0; i < num_pts; i++) {
clusterIndex = pts[i].group;
centroids[clusterIndex].group++;
centroids[clusterIndex].x += pts[i].x;
centroids[clusterIndex].y += pts[i].y;
}
for ( i = 0; i < num_clusters; i++ ) {
centroids[i].x /= centroids[i].group;
centroids[i].y /= centroids[i].group;
}
changes = 0;
for ( i = 0; i < num_pts; i++ ) {
clusterIndex = nearest(&pts[i], centroids, num_clusters);
if (clusterIndex != pts[i].group) {
pts[i].group = clusterIndex;
changes++;
}
}
maxTimes--;
} while ((changes > acceptable) && (maxTimes > 0));
for ( i = 0; i < num_clusters; i++ )
centroids[i].group = i;
return centroids;
}
void print_eps(POINT * pts, int num_pts, POINT * centroids, int num_clusters)
{
int i, j;
double min_x, max_x, min_y, max_y, scale, cx, cy;
double *colors = (double *) malloc(sizeof(double) * num_clusters * 3);
for (i = 0; i < num_clusters; i++) {
colors[3*i + 0] = (3 * (i + 1) % 11)/11.;
colors[3*i + 1] = (7 * i % 11)/11.;
colors[3*i + 2] = (9 * i % 11)/11.;
}
max_x = max_y = - HUGE_VAL;
min_x = min_y = HUGE_VAL;
for (j = 0; j < num_pts; j++) {
if (max_x < pts[j].x) max_x = pts[j].x;
if (min_x > pts[j].x) min_x = pts[j].x;
if (max_y < pts[j].y) max_y = pts[j].y;
if (min_y > pts[j].y) min_y = pts[j].y;
}
scale = W / (max_x - min_x);
if (scale > H / (max_y - min_y))
scale = H / (max_y - min_y);
cx = (max_x + min_x) / 2;
cy = (max_y + min_y) / 2;
printf(, W + 10, H + 10);
printf(
);
for (i = 0; i < num_clusters; i++) {
printf(,
colors[3*i], colors[3*i + 1], colors[3*i + 2]);
for (j = 0; j < num_pts; j++) {
if (pts[j].group != i) continue;
printf(,
(pts[j].x - cx) * scale + W / 2,
(pts[j].y - cy) * scale + H / 2);
}
printf(,
(centroids[i].x - cx) * scale + W / 2,
(centroids[i].y - cy) * scale + H / 2);
}
printf();
free(colors);
return;
}
int main()
{
int num_pts = NUMBER_OF_POINTS;
int num_clusters = NUMBER_OF_CLUSTERS;
int maxTimes = MAXIMUM_ITERATIONS;
double radius = RADIUS;
POINT * pts;
POINT * centroids;
pts = gen_xy(num_pts, radius);
centroids = lloyd(pts, num_pts, num_clusters, maxTimes);
print_eps(pts, num_pts, centroids, num_clusters);
free(pts);
free(centroids);
return 0;
} | 685K-means++ clustering
| 5c
| wy3ec |
int rrand(int m)
{
return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}
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--);
memcpy(temp, BYTE(obj) + n*size, size);
memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
memcpy(BYTE(obj) + k*size, temp, size);
}
free(temp);
} | 686Knuth shuffle
| 5c
| c1k9c |
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("gold" , 2500, 2.0, 0.002)
};
protected final int n = items.length; | 679Knapsack problem/Unbounded
| 9java
| hnzjm |
begin
check = STDIN.read_nonblock(1)
rescue IO::WaitReadable
check = false
end
puts check if check | 680Keyboard input/Keypress check
| 14ruby
| 3jbz7 |
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()
System.exit(0)
}
else
println(keyCode)
}
})
}
object KeypressCheck extends App {
println("Press any key to see its code or 'enter' to quit\n")
SwingUtilities.invokeLater(() => {
def foo() = {
val f = new KeypressCheck
f.setFocusable(true)
f.setVisible(true)
f.setSize(200, 200)
f.setEnabled(true)
}
foo()
})
} | 680Keyboard input/Keypress check
| 16scala
| 9pem5 |
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, i, item, val;
for (i = 0; i < items.length; i += 1) {
item = items[i];
item.max = Math.min(
Math.floor(knapsack.weight / item.weight),
Math.floor(knapsack.volume / item.volume)
);
}
for (g = 0; g <= gold.max; g += 1) {
for (p = 0; p <= panacea.max; p += 1) {
for (i = 0; i <= ichor.max; i += 1) {
if (i * ichor.weight + g * gold.weight + p * panacea.weight > knapsack.weight) {
continue;
}
if (i * ichor.volume + g * gold.volume + p * panacea.volume > knapsack.volume) {
continue;
}
val = i * ichor.value + g * gold.value + p * panacea.value;
if (val > max_val) {
solutions = [];
max_val = val;
}
if (val === max_val) {
solutions.push([g, p, i]);
}
}
}
}
document.write("maximum value: " + max_val + '<br>');
for (i = 0; i < solutions.length; i += 1) {
item = solutions[i];
document.write("(gold: " + item[0] + ", panacea: " + item[1] + ", ichor: " + item[2] + ")<br>");
}
output:
<pre>maximum value: 54500
(gold: 11, panacea: 0, ichor: 15)
(gold: 11, panacea: 3, ichor: 10)
(gold: 11, panacea: 6, ichor: 5)
(gold: 11, panacea: 9, ichor: 0)</pre> | 679Knapsack problem/Unbounded
| 10javascript
| a3910 |
null | 677Knapsack problem/Continuous
| 11kotlin
| trpf0 |
null | 683K-d tree
| 0go
| q99xz |
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 := bufio.NewScanner(f)
for input.Scan() {
line := input.Text()
fields := strings.Fields(line)
mag, err := strconv.ParseFloat(fields[2], 64)
if err != nil {
fmt.Println("Unable to parse magnitude of an earthquake")
return
}
if mag > 6.0 {
fmt.Println(line)
}
}
} | 682Kernighans large earthquake problem
| 0go
| hndjq |
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) {
println(it)
}
}
}
} | 682Kernighans large earthquake problem
| 7groovy
| 4s05f |
package main
import (
"fmt"
"log" | 687Juggler sequence
| 0go
| xmzwf |
import System.Random
import Data.List (sortBy, genericLength, minimumBy)
import Data.Ord (comparing)
type DimensionalAccessors a b = [a -> b]
data Tree a = Node a (Tree a) (Tree a)
| Empty
instance Show a => Show (Tree a) where
show Empty = "Empty"
show (Node value left right) =
"(" ++ show value ++ " " ++ show left ++ " " ++ show right ++ ")"
data KDTree a b = KDTree (DimensionalAccessors a b) (Tree a)
instance Show a => Show (KDTree a b) where
show (KDTree _ tree) = "KDTree " ++ show tree
sqrDist :: Num b => DimensionalAccessors a b -> a -> a -> b
sqrDist dims a b = sum $ map square $ zipWith (-) a' b'
where
a' = map ($ a) dims
b' = map ($ b) dims
square :: Num a => a -> a
square = (^ 2)
insert :: Ord b => KDTree a b -> a -> KDTree a b
insert (KDTree dims tree) value = KDTree dims $ ins (cycle dims) tree
where
ins _ Empty = Node value Empty Empty
ins (d:ds) (Node split left right) =
if d value < d split
then Node split (ins ds left) right
else Node split left (ins ds right)
empty :: DimensionalAccessors a b -> KDTree a b
empty dims = KDTree dims Empty
singleton :: Ord b => DimensionalAccessors a b -> a -> KDTree a b
singleton dims value = insert (empty dims) value
fromList :: Ord b => DimensionalAccessors a b -> [a] -> KDTree a b
fromList dims values = KDTree dims $ fList (cycle dims) values
where
fList _ [] = Empty
fList (d:ds) values =
let sorted = sortBy (comparing d) values
(lower, higher) = splitAt (genericLength sorted `div` 2) sorted
in case higher of
[] -> Empty
median:rest -> Node median (fList ds lower) (fList ds rest)
fromListLinear :: Ord b => DimensionalAccessors a b -> [a] -> KDTree a b
fromListLinear dims values = foldl insert (empty dims) values
nearest :: (Ord b, Num b, Integral c) => KDTree a b -> a -> (Maybe a, c)
nearest (KDTree dims tree) value = near (cycle dims) tree
where
dist = sqrDist dims
near _ Empty = (Nothing, 1)
near _ (Node split Empty Empty) = (Just split, 1)
near (d:ds) (Node split left right) =
let dimdist x y = square (d x - d y)
splitDist = dist value split
hyperPlaneDist = dimdist value split
bestLeft = near ds left
bestRight = near ds right
((maybeThisBest, thisCount), (maybeOtherBest, otherCount)) =
if d value < d split
then (bestLeft, bestRight)
else (bestRight, bestLeft)
in case maybeThisBest of
Nothing ->
let count = 1 + thisCount + otherCount
in case maybeOtherBest of
Nothing -> (Just split, count)
Just otherBest ->
if dist value otherBest < splitDist
then (maybeOtherBest, count)
else (Just split, count)
Just thisBest ->
let thisBestDist = dist value thisBest
best =
if splitDist < thisBestDist
then split
else thisBest
bestDist = dist value best
in
if bestDist < hyperPlaneDist
then (Just best, 1 + thisCount)
else
let count = 1 + thisCount + otherCount
in case maybeOtherBest of
Nothing -> (Just best, count)
Just otherBest ->
if bestDist < dist value otherBest
then (Just best, count)
else (maybeOtherBest, count)
tuple2D :: [(a, a) -> a]
tuple2D = [fst, snd]
tuple3D :: [(a, a, a) -> a]
tuple3D = [d1, d2, d3]
where
d1 (a, _, _) = a
d2 (_, b, _) = b
d3 (_, _, c) = c
instance (Random a, Random b, Random c) => Random (a, b, c) where
random gen =
let (vA, genA) = random gen
(vB, genB) = random genA
(vC, genC) = random genB
in ((vA, vB, vC), genC)
randomR ((lA, lB, lC), (hA, hB, hC)) gen =
let (vA, genA) = randomR (lA, hA) gen
(vB, genB) = randomR (lB, hB) genA
(vC, genC) = randomR (lC, hC) genB
in ((vA, vB, vC), genC)
printResults :: (Show a, Show b, Show c, Floating c) =>
a -> (Maybe a, b) -> DimensionalAccessors a c -> IO ()
printResults point result dims = do
let (nearest, visited) = result
case nearest of
Nothing -> putStrLn "Could not find nearest."
Just value -> do
let dist = sqrt $ sqrDist dims point value
putStrLn $ "Point: " ++ show point
putStrLn $ "Nearest: " ++ show value
putStrLn $ "Distance: " ++ show dist
putStrLn $ "Visited: " ++ show visited
putStrLn ""
linearNearest :: (Ord b, Num b) => DimensionalAccessors a b -> a -> [a] -> Maybe a
linearNearest _ _ [] = Nothing
linearNearest dims value xs = Just $ minimumBy (comparing $ sqrDist dims value) xs
main :: IO ()
main = do
let wikiValues :: [(Double, Double)]
wikiValues = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
wikiTree = fromList tuple2D wikiValues
wikiSearch = (9, 2)
wikiNearest = nearest wikiTree wikiSearch
putStrLn "Wikipedia example:"
printResults wikiSearch wikiNearest tuple2D
let stdGen = mkStdGen 0
randRange :: ((Double, Double, Double), (Double, Double, Double))
randRange = ((0, 0, 0), (1000, 1000, 1000))
(randSearch, stdGenB) = randomR randRange stdGen
randValues = take 1000 $ randomRs randRange stdGenB
randTree = fromList tuple3D randValues
randNearest = nearest randTree randSearch
randNearestLinear = linearNearest tuple3D randSearch randValues
putStrLn "1000 random 3D points on the range of [0, 1000):"
printResults randSearch randNearest tuple3D
putStrLn "Confirm naive nearest:"
print randNearestLinear | 683K-d tree
| 8haskell
| mbbyf |
(defn shuffle [vect]
(reduce (fn [v i] (let [r (rand-int i)]
(assoc v i (v r) r (v i))))
vect (range (dec (count vect)) 1 -1))) | 686Knuth shuffle
| 6clojure
| 5qeuz |
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"math/rand"
"os"
"time"
)
type r2 struct {
x, y float64
}
type r2c struct {
r2
c int | 685K-means++ clustering
| 0go
| c1b9g |
import qualified Data.ByteString.Lazy.Char8 as C
main :: IO ()
main = do
cs <- C.readFile "data.txt"
mapM_ print $
C.lines cs >>=
(\x ->
[ x
| 6 < (read (last (C.unpack <$> C.words x)) :: Float) ]) | 682Kernighans large earthquake problem
| 8haskell
| iu5or |
use strict;
my $raw = <<'TABLE';
map 9 150 1
compass 13 35 1
water 153 200 2
sandwich 50 60 2
glucose 15 60 2
tin 68 45 3
banana 27 60 3
apple 39 40 3
cheese 23 30 1
beer 52 10 1
suntancream 11 70 1
camera 32 30 1
T-shirt 24 15 2
trousers 48 10 2
umbrella 73 40 1
w_trousers 42 70 1
w_overcoat 43 75 1
note-case 22 80 1
sunglasses 7 20 1
towel 18 12 2
socks 4 50 1
book 30 10 2
TABLE
my @items;
for (split "\n", $raw) {
my @x = split /\s+/;
push @items, {
name => $x[0],
weight => $x[1],
value => $x[2],
quant => $x[3],
}
}
my $max_weight = 400;
my %cache;
sub pick {
my ($weight, $pos) = @_;
if ($pos < 0 or $weight <= 0) {
return 0, 0, []
}
@{ $cache{$weight, $pos} //= [do{
my $item = $items[$pos];
my ($bv, $bi, $bw, $bp) = (0, 0, 0, []);
for my $i (0 .. $item->{quant}) {
last if $i * $item->{weight} > $weight;
my ($v, $w, $p) = pick($weight - $i * $item->{weight}, $pos - 1);
next if ($v += $i * $item->{value}) <= $bv;
($bv, $bi, $bw, $bp) = ($v, $i, $w, $p);
}
my @picked = ( @$bp, $bi );
$bv, $bw + $bi * $item->{weight}, \@picked
}]}
}
my ($v, $w, $p) = pick($max_weight, $
for (0 .. $
if ($p->[$_] > 0) {
print "$p->[$_] of $items[$_]{name}\n";
}
}
print "Value: $v; Weight: $w\n"; | 678Knapsack problem/Bounded
| 2perl
| d4hnw |
import Text.Printf
import Data.List
juggler :: Integer -> [Integer]
juggler = takeWhile (> 1) . iterate (\x -> if odd x
then isqrt (x*x*x)
else isqrt x)
task :: Integer -> IO ()
task n = printf s n (length ns + 1) (i :: Int) (showMax m)
where
ns = juggler n
(m, i) = maximum $ zip ns [0..]
s = "n =%d length =%d maximal value at =%d (%s)\n"
showMax n = let s = show n
in if n > 10^100
then show (length s) ++ " digits"
else show n
main = do
mapM_ task [20..39]
putStrLn "\nTough guys\n"
mapM_ task [ 113, 173, 193, 2183, 11229, 15065, 15845, 30817 ] | 687Juggler sequence
| 8haskell
| ykr66 |
module KMeans where
import Control.Applicative
import Control.Monad.Random
import Data.List (minimumBy, genericLength, transpose)
import Data.Ord (comparing)
import qualified Data.Map.Strict as M
type Vec = [Float]
type Cluster = [Vec]
kMeansIteration :: [Vec] -> [Vec] -> [Cluster]
kMeansIteration pts = clusterize . fixPoint iteration
where
iteration = map centroid . clusterize
clusterize centroids = M.elems $ foldr add m0 pts
where add x = M.insertWith (++) (centroids `nearestTo` x) [x]
m0 = M.unions $ map (`M.singleton` []) centroids
nearestTo :: [Vec] -> Vec -> Vec
nearestTo pts x = minimumBy (comparing (distance x)) pts
distance :: Vec -> Vec -> Float
distance a b = sum $ map (^2) $ zipWith (-) a b
centroid :: [Vec] -> Vec
centroid = map mean . transpose
where mean pts = sum pts / genericLength pts
fixPoint :: Eq a => (a -> a) -> a -> a
fixPoint f x = if x == fx then x else fixPoint f fx where fx = f x
kMeans :: MonadRandom m => Int -> [Vec] -> m [Cluster]
kMeans n pts = kMeansIteration pts <$> take n <$> randomElements pts
kMeansPP :: MonadRandom m => Int -> [Vec] -> m [Cluster]
kMeansPP n pts = kMeansIteration pts <$> centroids
where centroids = iterate (>>= nextCentroid) x0 !! (n-1)
x0 = take 1 <$> randomElements pts
nextCentroid cs = (: cs) <$> fromList (map (weight cs) pts)
weight cs x = (x, toRational $ distance x (cs `nearestTo` x))
randomElements :: MonadRandom m => [a] -> m [a]
randomElements pts = map (pts !!) <$> getRandomRs (0, length pts)
instance (RandomGen g, Monoid m) => Monoid (Rand g m) where
mempty = pure mempty
mappend = liftA2 mappend
mkCluster n s m = take n . transpose <$> mapM randomsAround m
where randomsAround x0 = map (\x -> x0+s*atanh x) <$> getRandomRs (-1,1) | 685K-means++ clustering
| 8haskell
| ptdbt |
import java.io.BufferedReader;
import java.io.FileReader;
public class KernighansLargeEarthquakeProblem {
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt")); ) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("\\s+");
double magnitude = Double.parseDouble(split[2]);
if ( magnitude > 6 ) {
System.out.println(inLine);
}
}
}
}
} | 682Kernighans large earthquake problem
| 9java
| xm9wy |
const fs = require("fs");
const readline = require("readline");
const args = process.argv.slice(2);
if (!args.length) {
console.error("must supply file name");
process.exit(1);
}
const fname = args[0];
const readInterface = readline.createInterface({
input: fs.createReadStream(fname),
console: false,
});
readInterface.on("line", (line) => {
const fields = line.split(/\s+/);
if (+fields[fields.length - 1] > 6) {
console.log(line);
}
}); | 682Kernighans large earthquake problem
| 10javascript
| ovu86 |
<executable name> <width of graphics window> <height of graphics window> <real part of complex number> <imag part of complex number> <limiting radius> <Number of iterations to be tested> | 688Julia set
| 5c
| z7utx |
null | 679Knapsack problem/Unbounded
| 11kotlin
| 4si57 |
use Term::ReadKey;
ReadMode 4;
my $key = '';
while($key !~ /(Y|N)/i) {
1 while defined ReadKey -1;
print "Type Y/N: ";
$key = ReadKey 0;
print "$key\n";
}
ReadMode 0;
print "\nYou typed: $key\n"; | 676Keyboard input/Obtain a Y or N response
| 2perl
| 9psmn |
void clear() {
for(int n = 0;n < 10; n++) {
printf();
}
}
int main() {
clear();
system();
printf(HOME);
printf();
char c = 1;
while(c) {
c = getc(stdin);
clear();
switch (c)
{
case 'a':
printf(LEFT);
break;
case 'd':
printf(RIGHT);
break;
case 'w':
printf(UP);
break;
case 's':
printf(DOWN);
break;
case ' ':
c = 0;
break;
default:
printf(HOME);
};
printf();
}
system();
system();
return 1;
} | 689Joystick position
| 5c
| 6h532 |
import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
} | 683K-d tree
| 9java
| fggdv |
items = { ["panaea"] = { ["value"] = 3000, ["weight"] = 0.3, ["volume"] = 0.025 },
["ichor"] = { ["value"] = 1800, ["weight"] = 0.2, ["volume"] = 0.015 },
["gold"] = { ["value"] = 2500, ["weight"] = 2.0, ["volume"] = 0.002 }
}
max_weight = 25
max_volume = 0.25
max_num_items = {}
for i in pairs( items ) do
max_num_items[i] = math.floor( math.min( max_weight / items[i].weight, max_volume / items[i].volume ) )
end
best = { ["value"] = 0.0, ["weight"] = 0.0, ["volume"] = 0.0 }
best_amounts = {}
for i = 1, max_num_items["panaea"] do
for j = 1, max_num_items["ichor"] do
for k = 1, max_num_items["gold"] do
current = { ["value"] = i*items["panaea"]["value"] + j*items["ichor"]["value"] + k*items["gold"]["value"],
["weight"] = i*items["panaea"]["weight"] + j*items["ichor"]["weight"] + k*items["gold"]["weight"],
["volume"] = i*items["panaea"]["volume"] + j*items["ichor"]["volume"] + k*items["gold"]["volume"]
}
if current.value > best.value and current.weight <= max_weight and current.volume <= max_volume then
best = { ["value"] = current.value, ["weight"] = current.weight, ["volume"] = current.volume }
best_amounts = { ["panaea"] = i, ["ichor"] = j, ["gold"] = k }
end
end
end
end
print( "Maximum value:", best.value )
for k, v in pairs( best_amounts ) do
print( k, v )
end | 679Knapsack problem/Unbounded
| 1lua
| g0n4j |
use strict;
use warnings;
use Math::BigInt lib => 'GMP';
print " n l(n) i(n) h(n) or d(n)\n";
print " ------- ---- ---- ------------\n";
for my $i ( 20 .. 39,
113, 173, 193, 2183, 11229, 15065, 15845, 30817,
48443, 275485, 1267909, 2264915, 5812827,
7110201
)
{
my $max = my $n = Math::BigInt->new($i);
my $at = my $count = 0;
while( $n > 1 )
{
$n = sqrt( $n & 1 ? $n ** 3 : $n );
$count++;
$n > $max and ($max, $at) = ($n, $count);
}
if( length $max < 27 )
{
printf "%8d %4d %3d %s\n", $i, $count, $at, $max;
}
else
{
printf "%8d %4d %3d d(n) =%d digits\n", $i, $count, $at, length $max;
}
} | 687Juggler sequence
| 2perl
| 5qau2 |
null | 683K-d tree
| 11kotlin
| 8220q |
typedef unsigned char cell;
int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 };
int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };
void init_board(int w, int h, cell **a, cell **b)
{
int i, j, k, x, y, p = w + 4, q = h + 4;
a[0] = (cell*)(a + q);
b[0] = a[0] + 2;
for (i = 1; i < q; i++) {
a[i] = a[i-1] + p;
b[i] = a[i] + 2;
}
memset(a[0], 255, p * q);
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
for (k = 0; k < 8; k++) {
x = j + dx[k], y = i + dy[k];
if (b[i+2][j] == 255) b[i+2][j] = 0;
b[i+2][j] += x >= 0 && x < w && y >= 0 && y < h;
}
}
}
}
int walk_board(int w, int h, int x, int y, cell **b)
{
int i, nx, ny, least;
int steps = 0;
printf(EEEEE, y + 1, 1 + 2 * x);
while (1) {
b[y][x] = 255;
for (i = 0; i < 8; i++)
b[ y + dy[i] ][ x + dx[i] ]--;
least = 255;
for (i = 0; i < 8; i++) {
if (b[ y + dy[i] ][ x + dx[i] ] < least) {
nx = x + dx[i];
ny = y + dy[i];
least = b[ny][nx];
}
}
if (least > 7) {
printf(E, h + 2);
return steps == w * h - 1;
}
if (steps++) printf(E, y + 1, 1 + 2 * x);
x = nx, y = ny;
printf(EEE, y + 1, 1 + 2 * x);
fflush(stdout);
usleep(120000);
}
}
int solve(int w, int h)
{
int x = 0, y = 0;
cell **a, **b;
a = malloc((w + 4) * (h + 4) + sizeof(cell*) * (h + 4));
b = malloc((h + 4) * sizeof(cell*));
while (1) {
init_board(w, h, a, b);
if (walk_board(w, h, x, y, b + 2)) {
printf();
return 1;
}
if (++x >= w) x = 0, y++;
if (y >= h) {
printf();
return 0;
}
printf();
getchar();
}
}
int main(int c, char **v)
{
int w, h;
if (c < 2 || (w = atoi(v[1])) <= 0) w = 8;
if (c < 3 || (h = atoi(v[2])) <= 0) h = w;
solve(w, h);
return 0;
} | 690Knight's tour
| 5c
| la7cy |
null | 682Kernighans large earthquake problem
| 11kotlin
| ptzb6 |
null | 682Kernighans large earthquake problem
| 1lua
| 1z3po |
from math import isqrt
def juggler(k, countdig=True, maxiters=1000):
m, maxj, maxjpos = k, k, 0
for i in range(1, maxiters):
m = isqrt(m) if m% 2 == 0 else isqrt(m * m * m)
if m >= maxj:
maxj, maxjpos = m, i
if m == 1:
print(f)
return i
print()
print()
for k in range(20, 40):
juggler(k, False)
for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
juggler(k) | 687Juggler sequence
| 3python
| 4se5k |
static void print_callback (void *ctx, const char *str, size_t len)
{
FILE *f = (FILE *) ctx;
fwrite (str, 1, len, f);
}
static void check_status (yajl_gen_status status)
{
if (status != yajl_gen_status_ok)
{
fprintf (stderr, , (int) status);
exit (EXIT_FAILURE);
}
}
static void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)
{
size_t i;
switch (val->type)
{
case yajl_t_string:
check_status (yajl_gen_string (gen,
(const unsigned char *) val->u.string,
strlen (val->u.string)));
break;
case yajl_t_number:
if (parse_numbers && YAJL_IS_INTEGER (val))
check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));
else if (parse_numbers && YAJL_IS_DOUBLE (val))
check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));
else
check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),
strlen (YAJL_GET_NUMBER (val))));
break;
case yajl_t_object:
check_status (yajl_gen_map_open (gen));
for (i = 0 ; i < val->u.object.len ; i++)
{
check_status (yajl_gen_string (gen,
(const unsigned char *) val->u.object.keys[i],
strlen (val->u.object.keys[i])));
serialize_value (gen, val->u.object.values[i], parse_numbers);
}
check_status (yajl_gen_map_close (gen));
break;
case yajl_t_array:
check_status (yajl_gen_array_open (gen));
for (i = 0 ; i < val->u.array.len ; i++)
serialize_value (gen, val->u.array.values[i], parse_numbers);
check_status (yajl_gen_array_close (gen));
break;
case yajl_t_true:
check_status (yajl_gen_bool (gen, 1));
break;
case yajl_t_false:
check_status (yajl_gen_bool (gen, 0));
break;
case yajl_t_null:
check_status (yajl_gen_null (gen));
break;
default:
fprintf (stderr, , (int) val->type);
exit (EXIT_FAILURE);
}
}
static void print_tree (FILE *f, yajl_val tree, int parse_numbers)
{
yajl_gen gen;
gen = yajl_gen_alloc (NULL);
if (! gen)
{
fprintf (stderr, );
exit (EXIT_FAILURE);
}
if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1) ||
0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1) ||
0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))
{
fprintf (stderr, );
exit (EXIT_FAILURE);
}
serialize_value (gen, tree, parse_numbers);
yajl_gen_free (gen);
}
int main (int argc, char **argv)
{
char err_buf[200];
const char *json =
pi\large number\
an array\foo\;
yajl_val tree;
tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));
if (! tree)
{
fprintf (stderr, , err_buf);
return EXIT_FAILURE;
}
printf ();
print_tree (stdout, tree, 0);
printf ();
print_tree (stdout, tree, 1);
yajl_tree_free (tree);
return EXIT_SUCCESS;
} | 691JSON
| 5c
| 7oarg |
package main
import (
"fmt"
"github.com/nsf/termbox-go"
"github.com/simulatedsimian/joystick"
"log"
"os"
"strconv"
"time"
)
func printAt(x, y int, s string) {
for _, r := range s {
termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)
x++
}
}
func readJoystick(js joystick.Joystick, hidden bool) {
jinfo, err := js.Read()
check(err)
w, h := termbox.Size()
tbcd := termbox.ColorDefault
termbox.Clear(tbcd, tbcd)
printAt(1, h-1, "q - quit")
if hidden {
printAt(11, h-1, "s - show buttons:")
} else {
bs := ""
printAt(11, h-1, "h - hide buttons:")
for button := 0; button < js.ButtonCount(); button++ {
if jinfo.Buttons&(1<<uint32(button)) != 0 { | 689Joystick position
| 0go
| pt8bg |
import java.util.Random;
public class KMeansWithKpp{ | 685K-means++ clustering
| 9java
| r8sg0 |
perl -n -e '/(\S+)\s*$/ and $1 > 6 and print' data.txt | 682Kernighans large earthquake problem
| 2perl
| ykb6u |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print
while True:
char = getch()
if char.lower() in (, ):
print char
break | 676Keyboard input/Obtain a Y or N response
| 3python
| c109q |
import qualified Graphics.UI.GLFW as GLFW
import Graphics.Win32.Key
import Control.Monad.RWS.Strict (liftIO)
main = do
liftIO $ do
_ <- GLFW.init
GLFW.pollEvents
(jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1
putStrLn $ (show jxrot) ++ " " ++ (show jyrot)
w <- getAsyncKeyState 27
if (w<1) then main else do
GLFW.terminate
return ()
getJoystickDirections:: GLFW.Joystick -> IO (Double, Double)
getJoystickDirections js = do
maxes <- GLFW.getJoystickAxes js
return $ case maxes of
(Just (x:y:_)) -> (-y, x)
_ -> ( 0, 0) | 689Joystick position
| 8haskell
| fgld1 |
from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = (, , , )
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = (, )
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = (, )
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset)
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1)% len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple(, )
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float(), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float())
def show_nearest(k, heading, kd, p):
print(heading + )
print(, p)
n = find_nearest(k, kd, p)
print(, n.nearest)
print(, sqrt(n.dist_sqd))
print(, n.nodes_visited, )
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == :
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, , kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: .join(map(str, parts))
show_nearest(2, text(, N,
,
t1-t0, ),
kd2, random_point(3)) | 683K-d tree
| 3python
| g004h |
define(function () {
"use strict";
function distanceSquared(p, q) {
const d = p.length; | 685K-means++ clustering
| 10javascript
| bfnki |
<?php
if ( ! isset( $argv[1] ) )
die( 'Data file name required' );
if ( ! $fh = fopen( $argv[1], 'r' ) )
die ( 'Cannot open file: ' . $argv[1] );
while ( list( $date, $loc, $mag ) = fscanf( $fh, ) ) {
if ( $mag > 6 ) {
printf( , $date, $loc, $mag );
}
}
fclose( $fh ); | 682Kernighans large earthquake problem
| 12php
| a3612 |
from itertools import groupby
from collections import namedtuple
def anyvalidcomb(items, maxwt, val=0, wt=0):
' All combinations below the maxwt '
if not items:
yield [], val, wt
else:
this, *items = items
for n in range(this.number + 1):
w = wt + n * this.weight
if w > maxwt:
break
v = val + n * this.value
this_comb = [this] * n
for comb, value, weight in anyvalidcomb(items, maxwt, v, w):
yield this_comb + comb, value, weight
maxwt = 400
COMB, VAL, WT = range(3)
Item = namedtuple('Items', 'name weight value number')
items = [ Item(*x) for x in
(
(, 9, 150, 1),
(, 13, 35, 1),
(, 153, 200, 3),
(, 50, 60, 2),
(, 15, 60, 2),
(, 68, 45, 3),
(, 27, 60, 3),
(, 39, 40, 3),
(, 23, 30, 1),
(, 52, 10, 3),
(, 11, 70, 1),
(, 32, 30, 1),
(, 24, 15, 2),
(, 48, 10, 2),
(, 73, 40, 1),
(, 42, 70, 1),
(, 43, 75, 1),
(, 22, 80, 1),
(, 7, 20, 1),
(, 18, 12, 2),
(, 4, 50, 1),
(, 30, 10, 2),
) ]
bagged = max( anyvalidcomb(items, maxwt), key=lambda c: (c[VAL], -c[WT]))
print(% len(bagged[COMB]))
print('\n\t'.join('%i off:%s'% (len(list(grp)), item.name) for item, grp in groupby(sorted(bagged[COMB]))))
print(% bagged[1:]) | 678Knapsack problem/Bounded
| 3python
| fgkde |
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{, 9, 150},
{, 13, 35},
{, 153, 200},
{, 50, 160},
{, 15, 60},
{, 68, 45},
{, 27, 60},
{, 39, 40},
{, 23, 30},
{, 52, 10},
{, 11, 70},
{, 32, 30},
{, 24, 15},
{, 48, 10},
{, 73, 40},
{, 42, 70},
{, 43, 75},
{, 22, 80},
{, 7, 20},
{, 18, 12},
{, 4, 50},
{, 30, 10},
};
int *knapsack (item_t *items, int n, int w) {
int i, j, a, b, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
if (items[i - 1].weight > j) {
m[i][j] = m[i - 1][j];
}
else {
a = m[i - 1][j];
b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
m[i][j] = a > b ? a : b;
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
if (m[i][j] > m[i - 1][j]) {
s[i - 1] = 1;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, n, tw = 0, tv = 0, *s;
n = sizeof (items) / sizeof (item_t);
s = knapsack(items, n, 400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf(, items[i].name, items[i].weight, items[i].value);
tw += items[i].weight;
tv += items[i].value;
}
}
printf(, , tw, tv);
return 0;
} | 692Knapsack problem/0-1
| 5c
| fgmd3 |
def juggler(k) = k.even?? Integer.sqrt(k): Integer.sqrt(k*k*k)
(20..39).chain([113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915]).each do |k|
k1 = k
l = h = i = 0
until k == 1 do
h, i = k, l if k > h
l += 1
k = juggler(k)
end
if k1 < 40 then
puts
else
puts
end
end | 687Juggler sequence
| 14ruby
| r8xgs |
library(tidyverse)
library(rvest)
task_html= read_html("http://rosettacode.org/wiki/Knapsack_problem/Bounded")
task_table= html_nodes(html, "table")[[1]]%>%
html_table(table, header= T, trim= T)%>%
set_names(c("items", "weight", "value", "pieces"))%>%
filter(items!= "knapsack")%>%
mutate(weight= as.numeric(weight),
value= as.numeric(value),
pieces= as.numeric(pieces)) | 678Knapsack problem/Bounded
| 13r
| ovr84 |
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf();
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf(, ++cnt, i);
base = 17;
printf(, base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf(, ++cnt, i);
printf(); print_num(i, base);
printf(); print_num(i * i, base);
printf(); print_num(i * i / tens, base);
printf(); print_num(i * i % tens, base);
printf();
}
return 0;
} | 693Kaprekar numbers
| 5c
| 0ldst |
(use 'clojure.data.json)
(def json-map (read-json "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"))
(pr-str json-map)
(pprint-json json-map) | 691JSON
| 6clojure
| ptsbd |
use std::cmp::Ordering;
use std::cmp::Ordering::Less;
use std::ops::Sub;
use std::time::Instant;
use rand::prelude::*;
#[derive(Clone, PartialEq, Debug)]
struct Point {
pub coords: Vec<f32>,
}
impl<'a, 'b> Sub<&'b Point> for &'a Point {
type Output = Point;
fn sub(self, rhs: &Point) -> Point {
assert_eq!(self.coords.len(), rhs.coords.len());
Point {
coords: self
.coords
.iter()
.zip(rhs.coords.iter())
.map(|(&x, &y)| x - y)
.collect(),
}
}
}
impl Point {
fn norm_sq(&self) -> f32 {
self.coords.iter().map(|n| n * n).sum()
}
}
struct KDTreeNode {
point: Point,
dim: usize, | 683K-d tree
| 15rust
| jii72 |
object KDTree {
import Numeric._ | 683K-d tree
| 16scala
| bffk6 |
(defn isin? [x li]
(not= [] (filter #(= x %) li)))
(defn options [movements pmoves n]
(let [x (first (last movements)) y (second (last movements))
op (vec (map #(vector (+ x (first %)) (+ y (second %))) pmoves))
vop (filter #(and (>= (first %) 0) (>= (last %) 0)) op)
vop1 (filter #(and (< (first %) n) (< (last %) n)) vop)]
(vec (filter #(not (isin? % movements)) vop1))))
(defn next-move [movements pmoves n]
(let [op (options movements pmoves n)
sp (map #(vector % (count (options (conj movements %) pmoves n))) op)
m (apply min (map last sp))]
(first (rand-nth (filter #(= m (last %)) sp)))))
(defn jumps [n pos]
(let [movements (vector pos)
pmoves [[1 2] [1 -2] [2 1] [2 -1]
[-1 2] [-1 -2] [-2 -1] [-2 1]]]
(loop [mov movements x 1]
(if (= x (* n n))
mov
(let [np (next-move mov pmoves n)]
(recur (conj mov np) (inc x))))))) | 690Knight's tour
| 6clojure
| 4sp5o |
python -c '
with open() as f:
for ln in f:
if float(ln.strip().split()[2]) > 6:
print(ln.strip())' | 682Kernighans large earthquake problem
| 3python
| mbpyh |
def yesno
begin
system()
str = STDIN.getc
ensure
system()
end
if str ==
return true
elsif str ==
return false
else
raise
end
end | 676Keyboard input/Obtain a Y or N response
| 14ruby
| 2eolw |
my @items = sort { $b->[2]/$b->[1] <=> $a->[2]/$a->[1] }
(
[qw'beef 3.8 36'],
[qw'pork 5.4 43'],
[qw'ham 3.6 90'],
[qw'greaves 2.4 45'],
[qw'flitch 4.0 30'],
[qw'brawn 2.5 56'],
[qw'welt 3.7 67'],
[qw'salami 3.0 95'],
[qw'sausage 5.9 98'],
);
my ($limit, $value) = (15, 0);
print "item fraction weight value\n";
for (@items) {
my $ratio = $_->[1] > $limit ? $limit/$_->[1] : 1;
print "$_->[0]\t";
$value += $_->[2] * $ratio;
$limit -= $_->[1];
if ($ratio == 1) {
print " all\t$_->[1]\t$_->[2]\n";
} else {
printf "%5.3f %s %8.3f\n", $ratio, $_->[1] * $ratio, $_->[2] * $ratio;
last;
}
}
print "-" x 40, "\ntotal value: $value\n"; | 677Knapsack problem/Continuous
| 2perl
| kdyhc |
null | 685K-means++ clustering
| 11kotlin
| vwa21 |
null | 676Keyboard input/Obtain a Y or N response
| 15rust
| vwi2t |
package main
import "fmt"
func main() {
outer:
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
if i + j == 4 { continue outer }
if i + j == 5 { break outer }
fmt.Println(i + j)
}
}
k := 3
if k == 3 { goto later }
fmt.Println(k) | 684Jump anywhere
| 0go
| 6hj3p |
local function load_data(npoints, radius) | 685K-means++ clustering
| 1lua
| uxevl |
ruby -nae data.txt | 682Kernighans large earthquake problem
| 14ruby
| c1a9k |
fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::io::{BufRead, BufReader};
for line in BufReader::new(std::fs::OpenOptions::new().read(true).open("data.txt")?).lines() {
let line = line?;
let magnitude = line
.split_whitespace()
.nth(2)
.and_then(|it| it.parse::<f32>().ok())
.ok_or_else(|| format!("Could not parse scale: {}", line))?;
if magnitude > 6.0 {
println!("{}", line);
}
}
Ok(())
} | 682Kernighans large earthquake problem
| 15rust
| laecc |
scala.io.Source.fromFile("data.txt").getLines
.map("\\s+".r.split(_))
.filter(_(2).toDouble > 6.0)
.map(_.mkString("\t"))
.foreach(println) | 682Kernighans large earthquake problem
| 16scala
| uxqv8 |
println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.") | 676Keyboard input/Obtain a Y or N response
| 16scala
| 4sf50 |
$data = [
[
'name'=>'beef',
'weight'=>3.8,
'cost'=>36,
],
[
'name'=>'pork',
'weight'=>5.4,
'cost'=>43,
],
[
'name'=>'ham',
'weight'=>3.6,
'cost'=>90,
],
[
'name'=>'greaves',
'weight'=>2.4,
'cost'=>45,
],
[
'name'=>'flitch',
'weight'=>4.0,
'cost'=>30,
],
[
'name'=>'brawn',
'weight'=>2.5,
'cost'=>56,
],
[
'name'=>'welt',
'weight'=>3.7,
'cost'=>67,
],
[
'name'=>'salami',
'weight'=>3.0,
'cost'=>95,
],
[
'name'=>'sausage',
'weight'=>5.9,
'cost'=>98,
],
];
uasort($data, function($a, $b) {
return ($b['cost']/$b['weight']) <=> ($a['cost']/$a['weight']);
});
$limit = 15;
foreach ($data as $item):
if ($limit >= $item['weight']):
echo ;
else:
echo ;
break;
endif;
$limit -= $item['weight'];
endforeach; | 677Knapsack problem/Continuous
| 12php
| 3jazq |
import Control.Monad.Cont
data LabelT r m = LabelT (ContT r m ())
label :: ContT r m (LabelT r m)
label = callCC subprog
where subprog lbl = let l = LabelT (lbl l) in return l
goto :: LabelT r m -> ContT r m b
goto (LabelT l) = const undefined <$> l
runProgram :: Monad m => ContT r m r -> m r
runProgram program = runContT program return | 684Jump anywhere
| 8haskell
| jio7g |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.