code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
io.write("Goodbye, World!") | 761Hello world/Newline omission
| 1lua
| w3iea |
function(keys,values)
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end | 759Hash from two arrays
| 1lua
| 8c60e |
file main.c | 768GUI enabling/disabling of controls
| 5c
| x6xwu |
func hashJoin<A, B, K: Hashable>(_ first: [(K, A)], _ second: [(K, B)]) -> [(A, K, B)] {
var map = [K: [B]]()
for (key, val) in second {
map[key, default: []].append(val)
}
var res = [(A, K, B)]()
for (key, val) in first {
guard let vals = map[key] else {
continue
}
res += vals.map({ (val, key, $0) })
}
return res
}
let t1 = [
("Jonah", 27),
("Alan", 18),
("Glory", 28),
("Popeye", 18),
("Alan", 28)
]
let t2 = [
("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")
]
print("Age | Character Name | Nemesis")
print("----|----------------|--------")
for (age, name, nemesis) in hashJoin(t1, t2) {
print("\(age) | \(name) | \(nemesis)")
} | 757Hash join
| 17swift
| ol98k |
import java.awt.{Dimension, Insets, Toolkit}
import javax.swing.JFrame
class MaxWindowDims() extends JFrame {
val toolkit: Toolkit = Toolkit.getDefaultToolkit
val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration), toolkit.getScreenSize)
println("Physical screen size: " + screenSize)
System.out.println("Insets: " + insets0)
screenSize.width -= (insets0.left + insets0.right)
screenSize.height -= (insets0.top + insets0.bottom)
System.out.println("Max available: " + screenSize)
}
object MaxWindowDims {
def main(args: Array[String]): Unit = {
new MaxWindowDims
}
} | 765GUI/Maximum window dimensions
| 16scala
| yjc63 |
import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds") | 763Handle a signal
| 17swift
| 1fqpt |
(ns experimentation.core
(:import (javax.swing JOptionPane JFrame JTextArea JButton)
(java.awt FlowLayout)))
(JOptionPane/showMessageDialog nil "Goodbye, World!")
(let [button (JButton. "Goodbye, World!")
window (JFrame. "Goodbye, World!")
text (JTextArea. "Goodbye, World!")]
(doto window
(.setLayout (FlowLayout.))
(.add button)
(.add text)
(.pack)
(.setDefaultCloseOperation (JFrame/EXIT_ON_CLOSE))
(.setVisible true))) | 767Hello world/Graphical
| 6clojure
| 098sj |
package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func processState(i int64, entry *gtk.Entry, ib, db *gtk.Button) {
if i == 0 {
entry.SetSensitive(true)
} else {
entry.SetSensitive(false)
}
if i < 10 {
ib.SetSensitive(true)
} else {
ib.SetSensitive(false)
}
if i > 0 {
db.SetSensitive(true)
} else {
db.SetSensitive(false)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0") | 768GUI enabling/disabling of controls
| 0go
| lplcw |
package main
import "fmt"
type is func() int
func newSum() is {
var ms is
ms = func() int {
ms = newSum()
return ms()
}
var msd, d int
return func() int {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
return msd + d
}
}
func newHarshard() is {
i := 0
sum := newSum()
return func() int {
for i++; i%sum() != 0; i++ {
}
return i
}
}
func main() {
h := newHarshard()
fmt.Print(h())
for i := 1; i < 20; i++ {
fmt.Print(" ", h())
}
fmt.Println()
h = newHarshard()
n := h()
for ; n <= 1000; n = h() {
}
fmt.Println(n)
} | 762Harshad or Niven series
| 0go
| x6iwf |
class HarshadNiven{ public static boolean find(int x)
{
int sum = 0,temp,var;
var = x;
while(x>0)
{
temp = x%10;
sum = sum + temp;
x = x/10;
}
if(var%sum==0) temp = 1;
else temp = 0;
return temp;
}
public static void main(String[] args)
{
int t,i;
t = 0;
for(i=1;t<20;i++)
{
if(find(i))
{
print(i + " ");
t++;
}
}
int x = 0;
int y = 1000;
while(x!=1)
{
if(find(y)) x = 1;
y++;
}
println();
println(y+1);
}
} | 762Harshad or Niven series
| 7groovy
| pdqbo |
import 'package:flutter/material.dart';
main() => runApp( MaterialApp( home: Text( "Goodbye, World!" ) ) ); | 767Hello world/Graphical
| 18dart
| hokjb |
print "Goodbye, World!"; | 761Hello world/Newline omission
| 2perl
| cbg9a |
my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals; | 759Hash from two arrays
| 2perl
| 5wpu2 |
import Data.Char (digitToInt)
harshads :: [Int]
harshads =
let digsum = sum . map digitToInt . show
in filter ((0 ==) . (mod <*> digsum)) [1 ..]
main :: IO ()
main = mapM_ print [take 20 harshads, [(head . filter (> 1000)) harshads]] | 762Harshad or Niven series
| 8haskell
| yjv66 |
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, decButton;
public Interact(){ | 768GUI enabling/disabling of controls
| 9java
| 707rj |
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = ;
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( , bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( , choice );
}while( scanf( , input ) == 1 );
return 0;
} | 769Guess the number/With feedback (player)
| 5c
| y736f |
echo ; | 761Hello world/Newline omission
| 12php
| x6nw5 |
$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values); | 759Hash from two arrays
| 12php
| oly85 |
null | 768GUI enabling/disabling of controls
| 11kotlin
| ueuvc |
file main.c | 770GUI component interaction
| 5c
| v1c2o |
(require '[clojure.string:as str])
(defn guess-game [low high]
(printf "Think of a number between%s and%s.\n (use (h)igh (l)ow (c)orrect)\n" low high)
(loop [guess (/ (inc (- high low)) 2)
[step & more] (next (iterate #(/ % 2) guess))]
(printf "I guess%s\n=> " (Math/round (float guess)))
(flush)
(case (first (str/lower-case (read)))
\h (recur (- guess step) more)
\l (recur (+ guess step) more)
\c (println "Huzzah!")
(do (println "Invalid input.")
(recur guess step))))) | 769Guess the number/With feedback (player)
| 6clojure
| 2pcl1 |
import sys
sys.stdout.write() | 761Hello world/Newline omission
| 3python
| lprcv |
cat("Goodbye, world!") | 761Hello world/Newline omission
| 13r
| yju6h |
public class Harshad{
private static long sumDigits(long n){
long sum = 0;
for(char digit:Long.toString(n).toCharArray()){
sum += Character.digit(digit, 10);
}
return sum;
}
public static void main(String[] args){
for(int count = 0, i = 1; count < 20;i++){
if(i % sumDigits(i) == 0){
System.out.println(i);
count++;
}
}
System.out.println();
for(int i = 1001; ; i++){
if(i % sumDigits(i) == 0){
System.out.println(i);
break;
}
}
}
} | 762Harshad or Niven series
| 9java
| duyn9 |
function isHarshad(n) {
var s = 0;
var n_str = new String(n);
for (var i = 0; i < n_str.length; ++i) {
s += parseInt(n_str.charAt(i));
}
return n % s === 0;
}
var count = 0;
var harshads = [];
for (var n = 1; count < 20; ++n) {
if (isHarshad(n)) {
count++;
harshads.push(n);
}
}
console.log(harshads.join(" "));
var h = 1000;
while (!isHarshad(++h));
console.log(h); | 762Harshad or Niven series
| 10javascript
| 67238 |
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)} | 759Hash from two arrays
| 3python
| 4x15k |
package main
import (
"fmt"
"math"
)
func haversine( float64) float64 {
return .5 * (1 - math.Cos())
}
type pos struct {
float64 | 766Haversine formula
| 0go
| 70hr2 |
print | 761Hello world/Newline omission
| 14ruby
| vaj2n |
fn main () {
print!("Goodbye, World!");
} | 761Hello world/Newline omission
| 15rust
| uehvj |
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
names(values) <- keys
values["Sam Doe"]
names(values)[values==152] | 759Hash from two arrays
| 13r
| 21hlg |
use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
my $value = 0;
my $mw = MainWindow->new;
$mw->title( 'GUI component enable/disable' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
my $entry = $lf->Entry( -width => 10, -textvariable => \$value,
-validate => 'key', -validatecommand => sub {
$_[0] =~ /^\d{1,9}\z/ ? do{setenable($_[0]); 1} : 0
},
)->pack(-fill => 'x', -expand => 1);
my $inc = $mw->Button( -text => 'increment',
-command => sub { $value++; setenable($value) },
)->pack( -side => 'left' );
my $dec = $mw->Button( -text => 'decrement',
-command => sub { $value--; setenable($value) },
)->pack( -side => 'right' );
setenable($value);
MainLoop;
sub setenable
{
$inc and $inc->configure( -state => $_[0] < 10 ? 'normal' : 'disabled' );
$dec and $dec->configure( -state => $_[0] > 0 ? 'normal' : 'disabled' );
$entry and $entry->configure( -state => $_[0] == 0 ? 'normal' : 'disabled' );
} | 768GUI enabling/disabling of controls
| 2perl
| 8c80w |
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};
int happy(int n)
{
int sum = 0, x, nn;
if (n < CACHE) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
x = happy(sum);
if (n < CACHE) buf[n] = 2 - x;
return x;
}
int main()
{
int i, cnt = 8;
for (i = 1; cnt || !printf(); i++)
if (happy(i)) --cnt, printf(, i);
printf(, cnt = 1000000);
for (i = 1; cnt; i++)
if (happy(i)) --cnt || printf(, i);
return 0;
} | 771Happy numbers
| 5c
| uacv4 |
def haversine(lat1, lon1, lat2, lon2) {
def R = 6372.8 | 766Haversine formula
| 7groovy
| ue4v9 |
print("Goodbye, World!") | 761Hello world/Newline omission
| 16scala
| gqp4i |
void gsplot (cairo_t *cr,int x,int y,double s) {
cairo_set_source_rgb (cr,s,s,s);
cairo_move_to (cr,x+0.5,y);
cairo_rel_line_to (cr,0,1);
cairo_stroke (cr);
}
gboolean expose_event (GtkWidget *widget,GdkEventExpose *event,gpointer data) {
int r,c,x=0;
cairo_t *cr;
cr = gdk_cairo_create (widget->window);
cairo_scale (cr,5,50);
cairo_set_line_width (cr,1);
for (r=0;r<4;r++) {
c = (r&1)*64-(r%2);
do gsplot (cr,x++%64,r,c/(1<<(3-r))/(8*(1<<r)-1.0));
while ((c+=2*!(r%2)-1)!=(!(r%2))*64-(r%2));
} cairo_destroy (cr);
return FALSE;
}
int main (int argc, char *argv[]) {
GtkWidget *window;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (window, ,G_CALLBACK (expose_event), NULL);
g_signal_connect (window, , G_CALLBACK(gtk_main_quit), NULL);
gtk_window_set_default_size (GTK_WINDOW(window), 320, 200);
gtk_widget_set_app_paintable (window, TRUE);
gtk_widget_show_all (window);
gtk_main ();
return 0;
} | 772Greyscale bars/Display
| 5c
| gx245 |
import Control.Monad (join)
import Data.Bifunctor (bimap)
import Text.Printf (printf)
haversine :: Float -> Float
haversine = (^ 2) . sin . (/ 2)
greatCircleDistance ::
(Float, Float) ->
(Float, Float) ->
Float
greatCircleDistance = distDeg 6371
where
distDeg radius p1 p2 =
distRad
radius
(deg2rad p1)
(deg2rad p2)
distRad radius (lat1, lng1) (lat2, lng2) =
(2 * radius)
* asin
( min
1.0
( sqrt $
haversine (lat2 - lat1)
+ ( (cos lat1 * cos lat2)
* haversine (lng2 - lng1)
)
)
)
deg2rad = join bimap ((/ 180) . (pi *))
main :: IO ()
main =
printf
"The distance between BNA and LAX is about%0.f km.\n"
(greatCircleDistance bna lax)
where
bna = (36.12, -86.67)
lax = (33.94, -118.40) | 766Haversine formula
| 8haskell
| 8ci0z |
null | 762Harshad or Niven series
| 11kotlin
| 09fsf |
print("Goodbye, World!", terminator: "") | 761Hello world/Newline omission
| 17swift
| 217lj |
keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]
hash = Hash[keys.zip(vals)]
p hash
puts hash[ [1,2,3] ] | 759Hash from two arrays
| 14ruby
| rsegs |
use std::collections::HashMap;
fn main() {
let keys = ["a", "b", "c"];
let values = [1, 2, 3];
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
} | 759Hash from two arrays
| 15rust
| 70wrc |
package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0") | 770GUI component interaction
| 0go
| sywqa |
(defn happy? [n]
(loop [n n, seen #{}]
(cond
(= n 1) true
(seen n) false
:else
(recur (->> (str n)
(map #(Character/digit % 10))
(map #(* % %))
(reduce +))
(conj seen n)))))
(def happy-numbers (filter happy? (iterate inc 1)))
(println (take 8 happy-numbers)) | 771Happy numbers
| 6clojure
| 7s5r0 |
val keys = List(1, 2, 3)
val values = Array("A", "B", "C") | 759Hash from two arrays
| 16scala
| kishk |
function isHarshad(n)
local s=0
local n_str=tostring(n)
for i=1,#n_str do
s=s+tonumber(n_str:sub(i,i))
end
return n%s==0
end
local count=0
local harshads={}
local n=1
while count<20 do
if isHarshad(n) then
count=count+1
table.insert(harshads, n)
end
n=n+1
end
print(table.concat(harshads, " "))
local h=1001
while not isHarshad(h) do
h=h+1
end
print(h) | 762Harshad or Niven series
| 1lua
| 8ct0e |
import Graphics.UI.WX
import System.Random
main :: IO ()
main = start $ do
frm <- frame [text:= "Interact"]
fld <- textEntry frm [text:= "0", on keyboard:= checkKeys]
inc <- button frm [text:= "increment", on command:= increment fld]
ran <- button frm [text:= "random", on command:= (randReplace fld frm)]
set frm [layout:= margin 5 $ floatCentre $ column 2
[centre $ widget fld, row 2 [widget inc, widget ran]]]
increment :: Textual w => w -> IO ()
increment field = do
val <- get field text
when ((not . null) val) $ set field [text:= show $ 1 + read val]
checkKeys :: EventKey -> IO ()
checkKeys (EventKey key _ _) =
when (elem (show key) $ "Backspace": map show [0..9]) propagateEvent
randReplace :: Textual w => w -> Window a -> IO ()
randReplace field frame = do
answer <- confirmDialog frame "Random" "Generate a random number?" True
when answer $ getStdRandom (randomR (1,100)) >>= \num ->
set field [text:= show (num :: Int)] | 770GUI component interaction
| 8haskell
| 9h6mo |
import tkinter as tk
class MyForm(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack(expand=True, fill=, padx=10, pady=10)
self.master.title()
self.setupUI()
def setupUI(self):
self.value_entry = tk.Entry(self, justify=tk.CENTER)
self.value_entry.grid(row=0, column=0, columnspan=2,
padx=5, pady=5, sticky=)
self.value_entry.insert('end', '0')
self.value_entry.bind(, self.eventHandler)
self.decre_btn = tk.Button(self, text=, state=tk.DISABLED)
self.decre_btn.grid(row=1, column=0, padx=5, pady=5)
self.decre_btn.bind(, self.eventHandler)
self.incre_btn = tk.Button(self, text=)
self.incre_btn.grid(row=1, column=1, padx=5, pady=5)
self.incre_btn.bind(, self.eventHandler)
def eventHandler(self, event):
value = int(self.value_entry.get())
if event.widget == self.value_entry:
if value > 10:
self.value_entry.delete(, )
self.value_entry.insert(, )
elif value == 10:
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.DISABLED)
self.decre_btn.config(state=tk.NORMAL)
elif value == 0:
self.value_entry.config(state=tk.NORMAL)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.DISABLED)
elif (value > 0) and (value < 10):
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.NORMAL)
else:
if event.widget == self.incre_btn:
if (value >= 0) and (value < 10):
value += 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete(, )
self.value_entry.insert(, str(value))
if value > 0:
self.decre_btn.config(state=tk.NORMAL)
self.value_entry.config(state=tk.DISABLED)
if value == 10:
self.incre_btn.config(state=tk.DISABLED)
elif event.widget == self.decre_btn:
if (value > 0) and (value <= 10):
value -= 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete(, )
self.value_entry.insert(, str(value))
self.value_entry.config(state=tk.DISABLED)
if (value) < 10:
self.incre_btn.config(state=tk.NORMAL)
if (value) == 0:
self.decre_btn.config(state=tk.DISABLED)
self.value_entry.config(state=tk.NORMAL)
def main():
app = MyForm()
app.mainloop()
if __name__ == :
main() | 768GUI enabling/disabling of controls
| 3python
| olo81 |
package main
import (
"fmt"
"sort"
)
func main() {
lower, upper := 0, 100
fmt.Printf(`Instructions:
Think of integer number from%d (inclusive) to%d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
answer := sort.Search(upper-lower, func (i int) bool {
fmt.Printf("Is your number less than or equal to%d? ", lower+i)
s := ""
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is%d.\n", lower+answer)
} | 769Guess the number/With feedback (player)
| 0go
| 1dbp5 |
public class Haversine {
public static final double R = 6372.8; | 766Haversine formula
| 9java
| ezxa5 |
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interact extends JFrame{
final JTextField numberField;
final JButton incButton, randButton;
public Interact(){ | 770GUI component interaction
| 9java
| t5nf9 |
library(gWidgets)
options(guiToolkit="RGtk2")
w <- gwindow("Disable components")
g <- ggroup(cont=w, horizontal=FALSE)
e <- gedit("0", cont=g, coerce.with=as.numeric)
bg <- ggroup(cont=g)
down_btn <- gbutton("-", cont=bg)
up_btn <- gbutton("+", cont=bg)
update_ctrls <- function(h,...) {
val <- svalue(e)
enabled(down_btn) <- val >= 0
enabled(up_btn) <- val <= 10
}
rement <- function(h,...) {
svalue(e) <- svalue(e) + h$action
update_ctrls(h,...)
}
addHandlerChanged(e, handler=update_ctrls)
addHandlerChanged(down_btn, handler=rement, action=-1)
addHandlerChanged(up_btn, handler=rement, action=1) | 768GUI enabling/disabling of controls
| 13r
| qyqxs |
package main
import (
"github.com/fogleman/gg"
"math"
)
func greyBars(dc *gg.Context) {
run := 0
colorComp := 0.0 | 772Greyscale bars/Display
| 0go
| ilqog |
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.GC
import Control.Monad.Trans (liftIO)
main = do
initGUI
window <- windowNew
buf <- pixbufNewFromXPMData bars
widgetAddEvents window [ButtonPressMask]
on window objectDestroy mainQuit
on window exposeEvent (paint buf)
on window buttonPressEvent $
liftIO $ do { widgetDestroy window; return True }
windowFullscreen window
widgetShowAll window
mainGUI
paint :: Pixbuf -> EventM EExpose Bool
paint buf = do
pix <- eventWindow
liftIO $ do
(sx, sy) <- drawableGetSize pix
newBuf <- pixbufScaleSimple buf sx sy InterpNearest
gc <- gcNewWithValues pix newGCValues
drawPixbuf pix gc newBuf 0 0 0 0 (-1) (-1) RgbDitherNone 0 0
return True
bars :: [String]
bars = [
"64 4 65 1 1 1"," c None","A c #000000",
"C c #080808","D c #0C0C0C","E c #101010","F c #141414",
"G c #181818","H c #1C1C1C","I c #202020","J c #242424",
"K c #282828","L c #2C2C2C","M c #303030","N c #343434",
"O c #383838","P c #3C3C3C","Q c #404040","R c #444444",
"S c #484848","T c #4C4C4C","U c #505050","V c #545454",
"W c #585858","X c #5C5C5C","Y c #606060","Z c #646464",
"a c #686868","b c #6C6C6C","c c #707070","d c #747474",
"e c #787878","f c #7C7C7C","g c #808080","h c #848484",
"i c #888888","j c #8C8C8C","k c #909090","l c #949494",
"m c #989898","n c #9C9C9C","o c #A0A0A0","p c #A4A4A4",
"q c #A8A8A8","r c #ACACAC","s c #B0B0B0","t c #B4B4B4",
"u c #B8B8B8","v c #BCBCBC","w c #C0C0C0","x c #C4C4C4",
"y c #C8C8C8","z c #CCCCCC","0 c #D0D0D0","1 c #D4D4D4",
"2 c #D8D8D8","3 c #DCDCDC","4 c #E0E0E0","5 c #E4E4E4",
"6 c #E8E8E8","7 c #ECECEC","8 c #F0F0F0","9 c #F4F4F4",
". c #F8F8F8","+ c #FCFCFC","* c #FFFFFF",
"AAAAAAAAJJJJJJJJRRRRRRRRZZZZZZZZhhhhhhhhppppppppxxxxxxxx********",
"****88881111xxxxttttppppllllhhhhddddZZZZVVVVRRRRNNNNJJJJFFFFAAAA",
"AADDFFHHJJLLNNPPRRTTVVXXZZbbddffhhjjllnnpprrttvvxxzz11336688..**",
"*+.9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCA"
] | 772Greyscale bars/Display
| 8haskell
| v1m2k |
main :: IO ()
main = do
putStrLn "Please enter the range:"
putStr "From: "
from <- getLine
putStr "To: "
to <- getLine
case (from, to) of
(_) | [(from', "")] <- reads from
, [(to' , "")] <- reads to
, from' < to' -> loop from' to'
(_) -> putStrLn "Invalid input." >> main
loop :: Integer -> Integer -> IO ()
loop from to = do
let guess = (to + from) `div` 2
putStrLn $ "Is it " ++ show guess ++ "? ((l)ower, (c)orrect, (h)igher)"
answer <- getLine
case answer of
"c" -> putStrLn "Awesome!"
"l" -> loop from guess
"h" -> loop guess to
(_) -> putStrLn "Invalid answer." >> loop from to | 769Guess the number/With feedback (player)
| 8haskell
| t5df7 |
function haversine() {
var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });
var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];
var R = 6372.8; | 766Haversine formula
| 10javascript
| 09osz |
package main
import "github.com/mattn/go-gtk/gtk"
func main() {
gtk.Init(nil)
win := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
win.SetTitle("Goodbye, World!")
win.SetSizeRequest(300, 200)
win.Connect("destroy", gtk.MainQuit)
button := gtk.NewButtonWithLabel("Goodbye, World!")
win.Add(button)
button.Connect("clicked", gtk.MainQuit)
win.ShowAll()
gtk.Main()
} | 767Hello world/Graphical
| 0go
| 9kcmt |
import java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.*
class Interact : JFrame() {
val numberField = JTextField()
val incButton = JButton("Increment")
val randButton = JButton("Random")
val buttonPanel = JPanel()
init {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
numberField.text = "0"
numberField.addKeyListener(object : KeyListener {
override fun keyTyped(e : KeyEvent) : Unit {
if (!Character.isDigit(e.keyChar)) e.consume()
}
override fun keyReleased(e : KeyEvent?) {}
override fun keyPressed(e : KeyEvent) {}
})
incButton.addActionListener {
val num = (numberField.text ?: "").toDouble()
numberField.text = (num + 1).toString()
}
randButton.addActionListener(object : ActionListener {
fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?")
override fun actionPerformed(e : ActionEvent) {
if(proceedOrNot() == JOptionPane.YES_OPTION)
numberField.text = (Math.random() * Long.MAX_VALUE).toString()
}
})
layout = GridLayout(2, 1)
buttonPanel.layout = GridLayout(1, 2)
buttonPanel.add(incButton)
buttonPanel.add(randButton)
add(numberField)
add(buttonPanel)
pack()
}
}
fun main(args : Array<String>) {
Interact().isVisible = true
} | 770GUI component interaction
| 11kotlin
| ocs8z |
import groovy.swing.SwingBuilder
import javax.swing.JFrame
new SwingBuilder().edt {
optionPane().showMessageDialog(null, "Goodbye, World!")
frame(title:'Goodbye, World!', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show: true) {
flowLayout()
button(text:'Goodbye, World!')
textArea(text:'Goodbye, World!')
}
} | 767Hello world/Graphical
| 7groovy
| zg3t5 |
import javax.swing.* ;
import java.awt.* ;
public class Greybars extends JFrame {
private int width ;
private int height ;
public Greybars( ) {
super( "grey bars example!" ) ;
width = 640 ;
height = 320 ;
setSize( width , height ) ;
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ;
setVisible( true ) ;
}
public void paint ( Graphics g ) {
int run = 0 ;
double colorcomp = 0.0 ; | 772Greyscale bars/Display
| 9java
| y7f6g |
import java.lang.Math.*
const val R = 6372.8 | 766Haversine formula
| 11kotlin
| kiph3 |
let keys = ["a","b","c"]
let vals = [1,2,3]
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
hash[key] = val
} | 759Hash from two arrays
| 17swift
| gqa49 |
int main(void)
{
int n;
int g;
char c;
srand(time(NULL));
n = 1 + (rand() % 10);
puts();
puts();
while (1) {
if (scanf(, &g) != 1) {
scanf(, &c);
continue;
}
if (g == n) {
puts();
return 0;
}
puts();
}
} | 773Guess the number
| 5c
| 2p6lo |
typedef struct Range {
int start, end, sum;
} Range;
Range maxSubseq(const int sequence[], const int len) {
int maxSum = 0, thisSum = 0, i = 0;
int start = 0, end = -1, j;
for (j = 0; j < len; j++) {
thisSum += sequence[j];
if (thisSum < 0) {
i = j + 1;
thisSum = 0;
} else if (thisSum > maxSum) {
maxSum = thisSum;
start = i;
end = j;
}
}
Range r;
if (start <= end && start >= 0 && end >= 0) {
r.start = start;
r.end = end + 1;
r.sum = maxSum;
} else {
r.start = 0;
r.end = 0;
r.sum = 0;
}
return r;
}
int main(int argc, char **argv) {
int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1};
int alength = sizeof(a)/sizeof(a[0]);
Range r = maxSubseq(a, alength);
printf(, r.sum);
int i;
for (i = r.start; i < r.end; i++)
printf(, a[i]);
printf();
return 0;
} | 774Greatest subsequential sum
| 5c
| n2xi6 |
<html><body>
<script type="text/javascript">
var width = 640; var height = 400;
var c = document.createElement("canvas");
c.setAttribute('id', 'myCanvas');
c.setAttribute('style', 'border:1px solid black;');
c.setAttribute('width', width);
c.setAttribute('height', height);
document.body.appendChild(c);
var ctx = document.getElementById('myCanvas').getContext("2d");
var columnCount = 8; | 772Greyscale bars/Display
| 10javascript
| 2pylr |
import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
public class GuessNumber {
public static final int LOWER = 0, UPPER = 100;
public static void main(String[] args) {
System.out.printf("Instructions:\n" +
"Think of integer number from%d (inclusive) to%d (exclusive) and\n" +
"I will guess it. After each guess, you respond with L, H, or C depending\n" +
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
int result = Collections.binarySearch(new AbstractList<Integer>() {
private final Scanner in = new Scanner(System.in);
public int size() { return UPPER - LOWER; }
public Integer get(int i) {
System.out.printf("My guess is:%d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
String s = in.nextLine();
assert s.length() > 0;
switch (Character.toLowerCase(s.charAt(0))) {
case 'l':
return -1;
case 'h':
return 1;
case 'c':
return 0;
}
return -1;
}
}, 0);
if (result < 0)
System.out.println("That is impossible.");
else
System.out.printf("Your number is%d.\n", result);
}
} | 769Guess the number/With feedback (player)
| 9java
| 89s06 |
import Graphics.UI.Gtk
import Control.Monad
messDialog = do
initGUI
dialog <- messageDialogNew Nothing [] MessageInfo ButtonsOk "Goodbye, World!"
rs <- dialogRun dialog
when (rs == ResponseOk || rs == ResponseDeleteEvent) $ widgetDestroy dialog
dialog `onDestroy` mainQuit
mainGUI | 767Hello world/Graphical
| 8haskell
| bnpk2 |
typedef unsigned char luminance;
typedef luminance pixel1[1];
typedef struct {
unsigned int width;
unsigned int height;
luminance *buf;
} grayimage_t;
typedef grayimage_t *grayimage;
grayimage alloc_grayimg(unsigned int, unsigned int);
grayimage tograyscale(image);
image tocolor(grayimage); | 775Grayscale image
| 5c
| j0270 |
Shoes.app do
@number = edit_line
@number.change {update_controls}
@incr = button('Increment') {update_controls(@number.text.to_i + 1)}
@decr = button('Decrement') {update_controls(@number.text.to_i - 1)}
def update_controls(value = @number.text.to_i)
@number.text = value
@incr.state = value.to_i >= 10? : nil
@decr.state = value.to_i <= 0? : nil
end
update_controls 0
end | 768GUI enabling/disabling of controls
| 14ruby
| nvnit |
int main(){
int number, guess;
srand( time( 0 ) );
number = lower_limit + rand() % (upper_limit - lower_limit + 1);
printf( , lower_limit, upper_limit );
while( scanf( , &guess ) == 1 ){
if( number == guess ){
printf( );
break;
}
printf( , number < guess ? : );
}
return 0;
} | 776Guess the number/With feedback
| 5c
| afg11 |
null | 772Greyscale bars/Display
| 11kotlin
| fu8do |
#!/usr/bin/env js
var DONE = RIGHT = 0, HIGH = 1, LOW = -1;
function main() {
showInstructions();
while (guess(1, 100) !== DONE);
}
function guess(low, high) {
if (low > high) {
print("I can't guess it. Perhaps you changed your number.");
return DONE;
}
var g = Math.floor((low + high) / 2);
var result = getResult(g);
switch (result) {
case RIGHT:
return DONE;
case LOW:
return guess(g + 1, high);
case HIGH:
return guess(low, g - 1);
}
}
function getResult(g) {
while(true) {
putstr('Is it ' + g + '? ');
var ans = readline().toUpperCase().replace(/^\s+/, '') + ' ';
switch (ans[0]) {
case 'R':
print('I got it! Thanks for the game.');
return RIGHT;
case 'L':
return LOW;
case 'H':
return HIGH;
default:
print('Please tell me if I am "high", "low" or "right".');
}
}
}
function showInstructions() {
print('Think of a number between 1 and 100 and I will try to guess it.');
print('After I guess, type "low", "high" or "right", and then press enter.');
putstr("When you've thought of a number press enter.");
readline();
}
main(); | 769Guess the number/With feedback (player)
| 10javascript
| fundg |
main() {
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
int count=0;
int i=0;
while(count<8) {
if(happy[i]==null) {
int j=i;
Set<int> sequence=new Set<int>();
while(happy[j]==null &&!sequence.contains(j)) {
sequence.add(j);
int sum=0;
int val=j;
while(val>0) {
int digit=val%10;
sum+=digit*digit;
val=(val/10).toInt();
}
j=sum;
}
bool sequenceHappy=happy[j];
Iterator<int> it=sequence.iterator();
while(it.hasNext()) {
happy[it.next()]=sequenceHappy;
}
}
if(happy[i]) {
print(i);
count++;
}
i++;
}
} | 771Happy numbers
| 18dart
| mjzyb |
local function haversine(x1, y1, x2, y2)
r=0.017453292519943295769236907684886127;
x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;
a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c;
return d;
end | 766Haversine formula
| 1lua
| bn1ka |
package main
import (
"fmt"
"sort"
)
type graph struct {
nn int | 777Graph colouring
| 0go
| gxy4n |
(import '[java.io File]
'[javax.imageio ImageIO]
'[java.awt Color]
'[java.awt.image BufferedImage]))
(defn rgb-to-gray [color-image]
(let [width (.getWidth color-image)]
(partition width
(for [x (range width)
y (range (.getHeight color-image))]
(let [rgb (.getRGB color-image x y)
rgb-object (new Color rgb)
r (.getRed rgb-object)
g (.getGreen rgb-object)
b (.getBlue rgb-object)
a (.getAlpha rgb-object)]
(+ (* r 0.2126) (* g 0.7152) (* b 0.0722)))))))
(defn write-matrix-to-image [matrix filename]
(ImageIO/write
(let [height (count matrix)
width (count (first matrix))
output-image (new BufferedImage width height BufferedImage/TYPE_BYTE_GRAY)]
(doseq [row-index (range height)
column-index (range width)]
(.setRGB output-image column-index row-index (.intValue (nth (nth matrix row-index) column-index))))
output-image)
"png"
(new File filename)))
(println
(write-matrix-to-image
(rgb-to-gray
(ImageIO/read (new File "test.jpg")))
"test-gray-cloj.png")) | 775Grayscale image
| 6clojure
| 1dgpy |
' Go Fish ~ Pesca!
Const cartas =
Declare Sub Reparto_Cartas
Declare Sub Pescar_Carta_Jug
Declare Sub Pescar_Carta_CPU
Declare Sub Comprobar_Libro_Jug
Declare Sub Comprobar_Libro_CPU
Declare Sub Comprobar_Fin_Partida
Declare Sub Intro
Dim Shared As Integer play(13), compu(13), deck(13), guess(13), poss(13), asked(13)
Dim Shared As String nombre, Snombre, CartaPedida
Dim Shared puntos(2) As Byte = {0,0}
Dim Shared As Integer remca = 4*Len(cartas)
Dim Shared As Integer i, k, j, cn
For i = 1 To 13
deck(i) = 4
Next i
For i = 1 To 9
Reparto_Cartas
deck(k) -= 1
compu(k) += 1
Reparto_Cartas
deck(k) -= 1
play(k) += 1
Next i
Dim As Integer v, po
Sub Reparto_Cartas
remca -= 1
Dim As Integer sc = remca * Rnd + 1
For k = 1 To 13
sc -= deck(k)
If sc <= 0 Then Return
Next k
End Sub
Sub Pescar_Carta_Jug
Reparto_Cartas
Print &Mid(cartas,k,1) &
deck(k) -= 1
play(k) += 1
End Sub
Sub Pescar_Carta_CPU
Reparto_Cartas
Print
deck(k) -= 1
compu(k) += 1
End Sub
Sub Comprobar_Libro_Jug
For i = 1 To 13
If play(i) <> 4 Then
Else
Color 11: Print Snombre & &Mid(cartas,i,1) &: Color 7
play(i) = 0
puntos(0) += 1
End If
Next i
End Sub
Sub Comprobar_Libro_CPU
For i = 1 To 13
If compu(i) <> 4 Then
Else
Color 11: Print Snombre & &Mid(cartas,i,1) &: Color 7
compu(i) = 0
puntos(1) += 1
End If
Next i
End Sub
Sub Comprobar_Fin_Partida
Dim As Integer np = 0, nc = 0
For i = 1 To 13
np += play(i)
nc += compu(i)
Next i
If remca = 0 Or np = 0 Or nc = 0 Then
Color 15: Print
Print
Print
If puntos(0) < puntos(1) Then
Print
Elseif puntos(0) > puntos(1) Then
Print nombre &
Else
Print
End If
Sleep: End
End If
End Sub
Sub Intro
Color 15
Print
Print
Print
Print
Print
Print
Print
Color 14: Locate 10, 2: Input , nombre
End Sub
'--- Programa Principal ---
Cls
Randomize Timer
Intro
Do
Dim As boolean MuestraMano = false
While MuestraMano = false
Color 15: Print Chr(10) & &nombre &; puntos(0); ; puntos(1)
Color 13: Print Chr(10) &space(10) &remca &
Color 14: Print Chr(10) &;
For i = 1 To 13
If Not play(i) Then
For j = 1 To play(i)
Print Mid(cartas,i,1); ;
Next j
End If
Next i
Print
Dim As boolean PideCarta = false
While PideCarta = false
Comprobar_Fin_Partida
Snombre = nombre
Color 7: Print
Input ; CartaPedida
Print
If CartaPedida <> Then cn = Instr(cartas, Ucase(CartaPedida)): PideCarta = true
If cn = 0 Then
Print : PideCarta = false
Elseif play(cn) = 0 Then Color 12: Print : Color 7: PideCarta = false
End If
Wend
guess(cn) = 1
If compu(cn) = 0 Then
Print Snombre &;
Color 15: Print
Color 7: Print Snombre &;: Pescar_Carta_Jug
Comprobar_Libro_Jug
MuestraMano = true
Else
v = compu(cn)
compu(cn) = 0
play(cn) += v
Print Snombre & &v &
Comprobar_Libro_Jug
MuestraMano = false
End If
Wend
Snombre =
For i = 1 To 13
asked(i) = 0
Next i
Dim As boolean Turno_CPU_2 = false
While Turno_CPU_2 = false
Comprobar_Fin_Partida
po = 0
For i = 1 To 13
If (compu(i) > 0) And (guess(i) > 0) Then poss(i) = 1: po += 1
Next i
If po = 0 Then
Do
k = (Rnd*12)+1
Loop While compu(k) = 0 Or asked(k)
Else
Do
k = (Rnd*12)+1
Loop While poss(k) = 0
guess(k) = 0
asked(k) = 1
End If
Print: Print Snombre & &Mid(cartas,k,1) &
asked(k) = 1
If play(k) = 0 Then
Print Snombre &;
Color 15: Print
Color 7:Print Snombre &;: Pescar_Carta_CPU
Comprobar_Libro_CPU
Turno_CPU_2 = true
Else
v = play(k)
play(k) = 0
compu(k) += v
Print Snombre & &v &
Comprobar_Libro_CPU
Turno_CPU_2 = false
End If
Wend
Loop
End | 778Go Fish
| 5c
| v1f2o |
(def target (inc (rand-int 10))
(loop [n 0]
(println "Guess a number between 1 and 10 until you get it right:")
(let [guess (read)]
(if (= guess target)
(printf "Correct on the%d guess.\n" n)
(do
(println "Try again")
(recur (inc n)))))) | 773Guess the number
| 6clojure
| gxl4f |
import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField }
import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }
object Enabling extends swing.SimpleSwingApplication {
def top = new swing.MainFrame {
title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala"
val numberField = new TextField {
text = "0" | 768GUI enabling/disabling of controls
| 16scala
| zgztr |
null | 769Guess the number/With feedback (player)
| 11kotlin
| wzaek |
use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
my $value = 0;
my $mw = MainWindow->new;
$mw->title( 'GUI component interaction' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
$lf->Entry( -width => 10, -textvariable => \$value,
-validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ },
)->pack(-fill => 'x', -expand => 1);
$mw->Button( -text => 'increment', -command => sub { $value++ },
)->pack( -side => 'left' );
$mw->Button( -text => 'random', -command => sub {
$mw->Dialog(
-text => 'Change to a random value?',
-title => 'Confirm',
-buttons => [ qw(Yes No) ]
)->Show eq 'Yes' and $value = int rand 1e9; }
)->pack( -side => 'right' );
MainLoop; | 770GUI component interaction
| 2perl
| gxu4e |
import Data.Maybe
import Data.List
import Control.Monad.State
import qualified Data.Map as M
import Text.Printf
type Node = Int
type Color = Int
type Graph = M.Map Node [Node]
nodes :: Graph -> [Node]
nodes = M.keys
adjacentNodes :: Graph -> Node -> [Node]
adjacentNodes g n = fromMaybe [] $ M.lookup n g
degree :: Graph -> Node -> Int
degree g = length . adjacentNodes g
fromList :: [(Node, [Node])] -> Graph
fromList = foldr add M.empty
where
add (a, bs) g = foldr (join [a]) (join bs a g) bs
join = flip (M.insertWith (++))
readGraph :: String -> Graph
readGraph = fromList . map interprete . words
where
interprete s = case span (/= '-') s of
(a, "") -> (read a, [])
(a, '-':b) -> (read a, [read b])
uncolored :: Node -> State [(Node, Color)] Bool
uncolored n = isNothing <$> colorOf n
colorOf :: Node -> State [(Node, Color)] (Maybe Color)
colorOf n = gets (lookup n)
greedyColoring :: Graph -> [(Node, Color)]
greedyColoring g = mapM_ go (nodes g) `execState` []
where
go n = do
c <- colorOf n
when (isNothing c) $ do
adjacentColors <- nub . catMaybes <$> mapM colorOf (adjacentNodes g n)
let newColor = head $ filter (`notElem` adjacentColors) [1..]
modify ((n, newColor):)
filterM uncolored (adjacentNodes g n) >>= mapM_ go
wpColoring :: Graph -> [(Node, Color)]
wpColoring g = go [1..] nodesList `execState` []
where
nodesList = sortOn (negate . degree g) (nodes g)
go _ [] = pure ()
go (c:cs) ns = do
mark c ns
filterM uncolored ns >>= go cs
mark c [] = pure () :: State [(Node, Color)] ()
mark c (n:ns) = do
modify ((n, c):)
mark c (filter (`notElem` adjacentNodes g n) ns) | 777Graph colouring
| 8haskell
| syhqk |
(defn max-subseq-sum [coll]
(->> (take-while seq (iterate rest coll))
(mapcat #(reductions conj [] %))
(apply max-key #(reduce + %)))) | 774Greatest subsequential sum
| 6clojure
| 3gozr |
function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
table.batch = function(t,n,f) for i=1,#t,n do local s=T{} for j=1,n do s[j]=t[i+j-1] end f(s) end return t end
function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, n^0.5, 6 do
if n%f==0 or n%(f+2)==0 then return false end
end
return true
end
function goldbach(n)
local count = 0
for i = 1, n/2 do
if isprime(i) and isprime(n-i) then
count = count + 1
end
end
return count
end
print("The first 100 G numbers:")
g = T{}:range(100):map(function(n) return goldbach(2+n*2) end)
g:map(function(n) return string.format("%2d ",n) end):batch(10,function(t) print(t:concat()) end)
print("G(1000000) = "..goldbach(1000000)) | 779Goldbach's comet
| 1lua
| sy7q8 |
typedef unsigned long long ham;
size_t alloc = 0, n = 1;
ham *q = 0;
void qpush(ham h)
{
int i, j;
if (alloc <= n) {
alloc = alloc ? alloc * 2 : 16;
q = realloc(q, sizeof(ham) * alloc);
}
for (i = n++; (j = i/2) && q[j] > h; q[i] = q[j], i = j);
q[i] = h;
}
ham qpop()
{
int i, j;
ham r, t;
for (r = q[1]; n > 1 && r == q[1]; q[i] = t) {
for (i = 1, t = q[--n]; (j = i * 2) < n;) {
if (j + 1 < n && q[j] > q[j+1]) j++;
if (t <= q[j]) break;
q[i] = q[j], i = j;
}
}
return r;
}
int main()
{
int i;
ham h;
for (qpush(i = 1); i <= 1691; i++) {
h = qpop();
qpush(h * 2);
qpush(h * 3);
qpush(h * 5);
if (i <= 20 || i == 1691)
printf(, i, h);
}
return 0;
} | 780Hamming numbers
| 5c
| mjsys |
function wait(waittime) | 769Guess the number/With feedback (player)
| 1lua
| x3ewz |
use strict;
use warnings;
no warnings 'uninitialized';
use feature 'say';
use constant True => 1;
use List::Util qw(head uniq);
sub GraphNodeColor {
my(%OneMany, %NodeColor, %NodePool, @ColorPool);
my(@data) = @_;
for (@data) {
my($a,$b) = @$_;
push @{$OneMany{$a}}, $b;
push @{$OneMany{$b}}, $a;
}
@ColorPool = 0 .. -1 + scalar %OneMany;
$NodePool{$_} = True for keys %OneMany;
if ($OneMany{''}) {
delete $NodePool{$_} for @{$OneMany{''}};
delete $NodePool{''};
}
while (%NodePool) {
my $color = shift @ColorPool;
my %TempPool = %NodePool;
while (my $n = head 1, sort keys %TempPool) {
$NodeColor{$n} = $color;
delete $TempPool{$n};
delete $TempPool{$_} for @{$OneMany{$n}} ;
delete $NodePool{$n};
}
if ($OneMany{''}) {
$NodeColor{$_} = head 1, sort values %NodeColor for @{$OneMany{''}};
}
}
%NodeColor
}
my @DATA = (
[ [1,2],[2,3],[3,1],[4,undef],[5,undef],[6,undef] ],
[ [1,6],[1,7],[1,8],[2,5],[2,7],[2,8],[3,5],[3,6],[3,8],[4,5],[4,6],[4,7] ],
[ [1,4],[1,6],[1,8],[3,2],[3,6],[3,8],[5,2],[5,4],[5,8],[7,2],[7,4],[7,6] ],
[ [1,6],[7,1],[8,1],[5,2],[2,7],[2,8],[3,5],[6,3],[3,8],[4,5],[4,6],[4,7] ]
);
for my $d (@DATA) {
my %result = GraphNodeColor @$d;
my($graph,$colors);
$graph .= '(' . join(' ', @$_) . '), ' for @$d;
$colors .= ' ' . $result{$$_[0]} . '-' . ($result{$$_[1]} // '') . ' ' for @$d;
say 'Graph : ' . $graph =~ s/,\s*$//r;
say 'Colors: ' . $colors;
say 'Nodes : ' . keys %result;
say 'Edges : ' . @$d;
say 'Unique: ' . uniq values %result;
say '';
} | 777Graph colouring
| 2perl
| t5xfg |
use strict;
use warnings;
use feature 'say';
use List::Util 'max';
use GD::Graph::bars;
use ntheory 'is_prime';
sub table { my $t = shift() * (my $c = 1 + max map {length} @_); ( sprintf( ('%'.$c.'s')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub G {
my($n) = @_;
scalar grep { is_prime($_) and is_prime($n - $_) } 2 .. $n/2;
}
my @y;
push @y, G(2*$_ + 4) for my @x = 0..1999;
say $_ for table 10, @y;
printf "G $_:%d", G($_) for 1e6;
my @data = ( \@x, \@y);
my $graph = GD::Graph::bars->new(1200, 400);
$graph->set(
title => q/Goldbach's Comet/,
y_max_value => 170,
x_tick_number => 10,
r_margin => 10,
dclrs => [ 'blue' ],
) or die $graph->error;
my $gd = $graph->plot(\@data) or die $graph->error;
open my $fh, '>', 'goldbachs-comet.png';
binmode $fh;
print $fh $gd->png();
close $fh; | 779Goldbach's comet
| 2perl
| v1d20 |
import 'dart:math';
import 'dart:io';
main() {
final n = (1 + new Random().nextInt(10)).toString();
print("Guess which number I've chosen in the range 1 to 10");
do { stdout.write(" Your guess: "); } while (n!= stdin.readLineSync());
print("\nWell guessed!");
} | 773Guess the number
| 18dart
| 6rn34 |
sub partition {
my($all, $div) = @_;
my @marks = 0;
push @marks, $_/$div * $all for 1..$div;
my @copy = @marks;
$marks[$_] -= $copy[$_-1] for 1..$
@marks[1..$
}
sub bars {
my($h,$w,$p,$rev) = @_;
my (@nums,@vals,$line,$d);
$d = 2**$p;
push @nums, int $_/($d-1) * (2**16-1) for $rev ? reverse 0..$d-1 : 0..$d-1;
push @vals, ($nums[$_]) x (partition($w, $d))[$_] for 0..$
$line = join(' ', @vals) . "\n";
$line x $h;
}
my($w,$h) = (1280,768);
open my $pgm, '>', 'Greyscale-bars-perl5.pgm' or die "Can't create Greyscale-bars-perl5.pgm: $!";
print $pgm <<"EOH";
P2
$w $h
65535
EOH
my ($h1,$h2,$h3,$h4) = partition($h,4);
print $pgm
bars($h1,$w,3,0),
bars($h2,$w,4,1),
bars($h3,$w,5,0),
bars($h4,$w,6,1); | 772Greyscale bars/Display
| 2perl
| h84jl |
(defn guess-run []
(let [start 1
end 100
target (+ start (rand-int (inc (- end start))))]
(printf "Guess a number between%d and%d" start end)
(loop [i 1]
(printf "Your guess%d:\n" i)
(let [ans (read)]
(if (cond
(not (number? ans)) (println "Invalid format")
(or (< ans start) (> ans end)) (println "Out of range")
(< ans target) (println "too low")
(> ans target) (println "too high")
:else true)
(println "Correct")
(recur (inc i))))))) | 776Guess the number/With feedback
| 6clojure
| sykqr |
import javax.swing.*;
import java.awt.*;
public class OutputSwing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog (null, "Goodbye, World!"); | 767Hello world/Graphical
| 9java
| gqr4m |
import re
from collections import defaultdict
from itertools import count
connection_re = r
class Graph:
def __init__(self, name, connections):
self.name = name
self.connections = connections
g = self.graph = defaultdict(list)
matches = re.finditer(connection_re, connections,
re.MULTILINE | re.VERBOSE)
for match in matches:
n1, n2, n = match.groups()
if n:
g[n] += []
else:
g[n1].append(n2)
g[n2].append(n1)
def greedy_colour(self, order=None):
if order is None:
order = self.graph
colour = self.colour = {}
neighbours = self.graph
for node in order:
used_neighbour_colours = (colour[nbr] for nbr in neighbours[node]
if nbr in colour)
colour[node] = first_avail_int(used_neighbour_colours)
self.pp_colours()
return colour
def pp_colours(self):
print(f)
c = self.colour
e = canonical_edges = set()
for n1, neighbours in sorted(self.graph.items()):
if neighbours:
for n2 in neighbours:
edge = tuple(sorted([n1, n2]))
if edge not in canonical_edges:
print(f)
canonical_edges.add(edge)
else:
print(f)
lc = len(set(c.values()))
print(f)
def first_avail_int(data):
d = set(data)
for i in count():
if i not in d:
return i
if __name__ == '__main__':
for name, connections in [
('Ex1', ),
('Ex2', ),
('Ex3', ),
('Ex4', ),
]:
g = Graph(name, connections)
g.greedy_colour() | 777Graph colouring
| 3python
| z4qtt |
from matplotlib.pyplot import scatter, show
from sympy import isprime
def g(n):
assert n > 2 and n% 2 == 0, 'n in goldbach function g(n) must be even'
count = 0
for i in range(1, n
if isprime(i) and isprime(n - i):
count += 1
return count
print('The first 100 G numbers are:')
col = 1
for n in range(4, 204, 2):
print(str(g(n)).ljust(4), end = '\n' if (col% 10 == 0) else '')
col += 1
print('\nThe value of G(1000000) is', g(1_000_000))
x = range(4, 4002, 2)
y = [g(i) for i in x]
colors = [[, , ][(i
scatter([i
show() | 779Goldbach's comet
| 3python
| uafvd |
#!/usr/bin/perl
use strict; # https: | 778Go Fish
| 0go
| syjqa |
alert("Goodbye, World!"); | 767Hello world/Graphical
| 10javascript
| kibhq |
import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry()
options = { :5, :5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno(, ):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input!')
return
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text=, command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text=, command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop() | 770GUI component interaction
| 3python
| rq5gq |
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Go_Fish
use warnings;
use List::Util qw( first shuffle );
my $pat = qr/[atjqk2-9]/; # ranks
my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) }
qw( a t j q k ), 2 .. 9;
my $mebooks = my $youbooks = 0;
my $me = substr $deck, 0, 2 * 9, '';
my $mepicks = join '', $me =~ /$pat/g;
arrange($me);
$mebooks++ while $me =~ s/($pat).\1.\1.\1.//;
my $you = substr $deck, 0, 2 * 9, '';
my $youpicks = join '', $you =~ /$pat/g;
arrange($you);
$youbooks++ while $you =~ s/($pat).\1.\1.\1.//;
while( $mebooks + $youbooks < 13 )
{
play( \$you, \$youbooks, \$youpicks, \$me, \$mebooks, 1 );
$mebooks + $youbooks == 13 and last;
play( \$me, \$mebooks, \$mepicks, \$you, \$youbooks, 0 );
}
print "me $mebooks you $youbooks\n";
sub arrange { $_[0] = join '', sort $_[0] =~ /../g }
sub human
{
my $have = shift =~ s/($pat).\K(?!\1)/ /gr;
local $| = 1;
my $pick;
do
{
print "You have $have, enter request: ";
($pick) = lc(<STDIN>) =~ /$pat/g;
} until $pick and $have =~ /$pick/;
return $pick;
}
sub play
{
my ($me, $mb, $lastpicks, $you, $yb, $human) = @_;
my $more = 1;
while( arrange( $$me ), $more and $$mb + $$yb < 13 )
{
# use Data::Dump 'dd'; dd \@_, "deck $deck";
if( $$me =~ s/($pat).\1.\1.\1.// )
{
print "book of $&\n";
$$mb++;
}
elsif( $$me )
{
my $pick = $human ? do { human($$me) } : do
{
my %picks;
$picks{$_}++ for my @picks = $$me =~ /$pat/g;
my $pick = first { $picks{$_} } split(//, $$lastpicks), shuffle @picks;
print "pick $pick\n";
$$lastpicks =~ s/$pick//g;
$$lastpicks .= $pick;
$pick;
};
if( $$you =~ s/(?:$pick.)+// )
{
$$me .= $&;
}
else
{
print "GO FISH!!\n";
$$me .= substr $deck, 0, 2, '';
$more = 0;
}
}
elsif( $deck )
{
$$me .= substr $deck, 0, 2, '';
}
else
{
$more = 0;
}
}
arrange( $$me );
} | 778Go Fish
| 8haskell
| 9homo |
(defn smerge [xs ys]
(lazy-seq
(let [x (first xs),
y (first ys),
[z xs* ys*]
(cond
(< x y) [x (rest xs) ys]
(> x y) [y xs (rest ys)]
:else [x (rest xs) (rest ys)])]
(cons z (smerge xs* ys*)))))
(def hamming
(lazy-seq
(->> (map #(*' 5 %) hamming)
(smerge (map #(*' 3 %) hamming))
(smerge (map #(*' 2 %) hamming))
(cons 1)))) | 780Hamming numbers
| 6clojure
| v1n2f |
from livewires import *
horiz=640; vert=480; pruh=vert/4; dpp=255.0
begin_graphics(width=horiz,height=vert,title=,background=Colour.black)
def ty_pruhy(each):
hiy=each[0]*pruh; loy=hiy-pruh
krok=horiz/each[1]; piecol=255.0/(each[1]-1)
for x in xrange(0,each[1]):
barva=Colour(piecol*x/dpp,piecol*x/dpp,piecol*x/dpp ); set_colour(barva)
if each[2]:
box(x*krok,hiy,x*krok+krok,loy,filled=1)
else:
box(horiz-x*krok,hiy,horiz-((x+1)*krok),loy,filled=1)
source=[[4,8,True],[3,16,False],[2,32,True],[1,64,False]]
for each in source:
ty_pruhy(each)
while keys_pressed() != [' ']:
pass | 772Greyscale bars/Display
| 3python
| koghf |
mat <- matrix(c(rep(1:8, each = 8) / 8,
rep(16:1, each = 4) / 16,
rep(1:32, each = 2) / 32,
rep(64:1, each = 1) / 64),
nrow = 4, byrow = TRUE)
par(mar = rep(0, 4))
image(t(mat[4:1, ]), col = gray(1:64/64), axes = FALSE) | 772Greyscale bars/Display
| 13r
| rqvgj |
use strict ;
use warnings ;
use List::Util qw ( sum ) ;
sub createHarshads {
my @harshads ;
my $number = 1 ;
do {
if ( $number % sum ( split ( // , $number ) ) == 0 ) {
push @harshads , $number ;
}
$number++ ;
} until ( $harshads[ -1 ] > 1000 ) ;
return @harshads ;
}
my @harshadnumbers = createHarshads ;
for my $i ( 0..19 ) {
print "$harshadnumbers[ $i ]\n" ;
}
print "The first Harshad number greater than 1000 is $harshadnumbers[ -1 ]!\n" ; | 762Harshad or Niven series
| 2perl
| 5whu2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.