code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/smtp"
"os"
"strings"
)
type Message struct {
From string
To []string
Cc []string
Subject string
Content string
}
func (m Message) Bytes() (r []byte) {
to := strings.Join(m.To, ",")
cc := strings.Join(m.Cc, ",")
r = append(r, []byte("From: "+m.From+"\n")...)
r = append(r, []byte("To: "+to+"\n")...)
r = append(r, []byte("Cc: "+cc+"\n")...)
r = append(r, []byte("Subject: "+m.Subject+"\n\n")...)
r = append(r, []byte(m.Content)...)
return
}
func (m Message) Send(host string, port int, user, pass string) (err error) {
err = check(host, user, pass)
if err != nil {
return
}
err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port),
smtp.PlainAuth("", user, pass, host),
m.From,
m.To,
m.Bytes(),
)
return
}
func check(host, user, pass string) error {
if host == "" {
return errors.New("Bad host")
}
if user == "" {
return errors.New("Bad username")
}
if pass == "" {
return errors.New("Bad password")
}
return nil
}
func main() {
var flags struct {
host string
port int
user string
pass string
}
flag.StringVar(&flags.host, "host", "", "SMTP server to connect to")
flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on")
flag.StringVar(&flags.user, "user", "", "Username to authenticate with")
flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with")
flag.Parse()
err := check(flags.host, flags.user, flags.pass)
if err != nil {
flag.Usage()
os.Exit(1)
}
bufin := bufio.NewReader(os.Stdin)
fmt.Printf("From: ")
from, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
from = strings.Trim(from, " \t\n\r")
var to []string
for {
fmt.Printf("To (Blank to finish): ")
tmp, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
tmp = strings.Trim(tmp, " \t\n\r")
if tmp == "" {
break
}
to = append(to, tmp)
}
var cc []string
for {
fmt.Printf("Cc (Blank to finish): ")
tmp, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
tmp = strings.Trim(tmp, " \t\n\r")
if tmp == "" {
break
}
cc = append(cc, tmp)
}
fmt.Printf("Subject: ")
subject, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
subject = strings.Trim(subject, " \t\n\r")
fmt.Printf("Content (Until EOF):\n")
content, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
content = bytes.Trim(content, " \t\n\r")
m := Message{
From: from,
To: to,
Cc: cc,
Subject: subject,
Content: string(content),
}
fmt.Printf("\nSending message...\n")
err = m.Send(flags.host, flags.port, flags.user, flags.pass)
if err != nil {
fmt.Printf("Error:%v\n", err)
os.Exit(1)
}
fmt.Printf("Message sent.\n")
} | 300Send email
| 0go
| ldpcw |
typedef unsigned char bool;
void sieve(bool *sv) {
int n = 0, s[8], a, b, c, d, e, f, g, h, i, j;
for (a = 0; a < 2; ++a) {
for (b = 0; b < 10; ++b) {
s[0] = a + b;
for (c = 0; c < 10; ++c) {
s[1] = s[0] + c;
for (d = 0; d < 10; ++d) {
s[2] = s[1] + d;
for (e = 0; e < 10; ++e) {
s[3] = s[2] + e;
for (f = 0; f < 10; ++f) {
s[4] = s[3] + f;
for (g = 0; g < 10; ++g) {
s[5] = s[4] + g;
for (h = 0; h < 10; ++h) {
s[6] = s[5] + h;
for (i = 0; i < 10; ++i) {
s[7] = s[6] + i;
for (j = 0; j < 10; ++j) {
sv[s[7] + j+ n++] = TRUE;
}
}
}
}
}
}
}
}
}
}
}
int main() {
int count = 0;
clock_t begin = clock();
bool *p, *sv = (bool*) calloc(MAX_COUNT, sizeof(bool));
sieve(sv);
printf();
for (p = sv; p < sv + MAX_COUNT; ++p) {
if (!*p) {
if (++count <= 50) printf(, p-sv);
if (count == 100 * MILLION) {
printf(, p-sv);
break;
}
}
}
free(sv);
printf(, (double)(clock() - begin) / CLOCKS_PER_SEC);
return 0;
} | 302Self numbers
| 5c
| vtp2o |
int isPrime(unsigned int n)
{
unsigned int num;
if ( n < 2||!(n & 1))
return n == 2;
for (num = 3; num <= n/num; num += 2)
if (!(n % num))
return 0;
return 1;
}
int main()
{
unsigned int l,u,i,sum=0;
printf();
scanf(,&l,&u);
for(i=l;i<=u;i++){
if(isPrime(i)==1)
{
printf(,i);
sum++;
}
}
printf(,l,u,sum);
return 0;
} | 303Sequence of primes by trial division
| 5c
| uzpv4 |
<?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), ;
echo call_user_func(array($example, $name), 5), ;
?> | 299Send an unknown method call
| 12php
| uzwv5 |
import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = False
for i, n in zip(range(20), primorial_prime()):
print('Primorial prime%2i at primorial index:%3i'% (i+1, n)) | 297Sequence of primorial primes
| 3python
| degn1 |
divisorCount <- function(n) length(Filter(function(x) n %% x == 0, seq_len(n %/% 2))) + 1
smallestWithNDivisors <- function(n)
{
i <- 1
while(divisorCount(i) != n) i <- i + 1
i
}
print(sapply(1:15, smallestWithNDivisors)) | 296Sequence: smallest number with exactly n divisors
| 13r
| txjfz |
null | 293Sequence: smallest number greater than previous term with exactly n divisors
| 17swift
| 2f0lj |
sierpinski.triangle = function(n) {
len <- 2^(n+1)
b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2))
for (i in 1:(len/2))
{
cat(paste(ifelse(b,"*"," "),collapse=""),"\n")
n <- rep(FALSE,len+1)
n[which(b)-1]<-TRUE
n[which(b)+1]<-xor(n[which(b)+1],TRUE)
b <- n
}
}
sierpinski.triangle(5) | 278Sierpinski triangle
| 13r
| 4y45y |
import javax.mail.*
import javax.mail.internet.*
public static void simpleMail(String from, String password, String to,
String subject, String body) throws Exception {
String host = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable",true);
props.setProperty("mail.smtp.ssl.trust", host);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
String s1 = "[email protected]";
String s2 = "";
String s3 = "[email protected]"
simpleMail(s1, s2 , s3, "TITLE", "TEXT"); | 300Send email
| 7groovy
| 6073o |
int semiprime(int n)
{
int p, f = 0;
for (p = 2; f < 2 && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == 2;
}
int main(void)
{
int i;
for (i = 2; i < 100; i++)
if (semiprime(i)) printf(, i);
putchar('\n');
return 0;
} | 304Semiprime
| 5c
| gya45 |
import java.util.Objects;
import java.util.function.Predicate;
public class RealNumberSet {
public enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN,
}
public static class RealSet {
private Double low;
private Double high;
private Predicate<Double> predicate;
private double interval = 0.00001;
public RealSet(Double low, Double high, Predicate<Double> predicate) {
this.low = low;
this.high = high;
this.predicate = predicate;
}
public RealSet(Double start, Double end, RangeType rangeType) {
this(start, end, d -> {
switch (rangeType) {
case CLOSED:
return start <= d && d <= end;
case BOTH_OPEN:
return start < d && d < end;
case LEFT_OPEN:
return start < d && d <= end;
case RIGHT_OPEN:
return start <= d && d < end;
default:
throw new IllegalStateException("Unhandled range type encountered.");
}
});
}
public boolean contains(Double d) {
return predicate.test(d);
}
public RealSet union(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d));
}
public RealSet intersect(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d));
}
public RealSet subtract(RealSet other) {
return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d));
}
public double length() {
if (low.isInfinite() || high.isInfinite()) return -1.0; | 298Set of real numbers
| 9java
| eg6a5 |
class Example(object):
def foo(self, x):
return 42 + x
name =
getattr(Example(), name)(5) | 299Send an unknown method call
| 3python
| 0kcsq |
require 'digest/sha2'
puts Digest::SHA256.hexdigest('Rosetta code') | 290SHA-256
| 14ruby
| gyz4q |
require 'digest'
puts Digest::SHA1.hexdigest('Rosetta Code') | 289SHA-1
| 14ruby
| i1boh |
static void reverse(char *s, int len)
{
int i, j;
char tmp;
for (i = 0, j = len - 1; i < len / 2; ++i, --j)
tmp = s[i], s[i] = s[j], s[j] = tmp;
}
static int strsort(const void *s1, const void *s2)
{
return strcmp(*(char *const *) s1, *(char *const *) s2);
}
int main(void)
{
int i, c, ct = 0, len, sem = 0;
char **words, **drows, tmp[24];
FILE *dict = fopen(, );
while ((c = fgetc(dict)) != EOF)
ct += c == '\n';
rewind(dict);
words = alloca(ct * sizeof words);
drows = alloca(ct * sizeof drows);
for (i = 0; fscanf(dict, , tmp, &len) != EOF; ++i) {
strcpy(words[i] = alloca(len), tmp);
strcpy(drows[i] = alloca(len), tmp);
reverse(drows[i], len - 1);
}
fclose(dict);
qsort(drows, ct, sizeof drows, strsort);
for (c = i = 0; i < ct; ++i) {
while (strcmp(drows[i], words[c]) > 0 && c < ct - 1)
c++;
if (!strcmp(drows[i], words[c])) {
strcpy(tmp, drows[i]);
reverse(tmp, strlen(tmp));
if (strcmp(drows[i], tmp) > 0 && sem++ < 5)
printf(, drows[i], tmp);
}
}
printf(, sem);
return 0;
} | 305Semordnilap
| 5c
| 2fjlo |
>>> def a(answer):
print(% (answer, answer))
return answer
>>> def b(answer):
print(% (answer, answer))
return answer
>>> for i in (False, True):
for j in (False, True):
print ()
x = a(i) and b(j)
print ()
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j) | 284Short-circuit evaluation
| 3python
| tx0fw |
module Main (main) where
import Network.Mail.SMTP
( Address(..)
, htmlPart
, plainTextPart
, sendMailWithLogin'
, simpleMail
)
main:: IO ()
main =
sendMailWithLogin' "smtp.example.com" 25 "user" "password" $
simpleMail
(Address (Just "From Example") "[email protected]")
[Address (Just "To Example") "[email protected]"]
[]
[]
"Subject"
[ plainTextPart "This is plain text."
, htmlPart "<h1>Title</h1><p>This is HTML.</p>"
] | 300Send email
| 8haskell
| 15fps |
function realSet(set1, set2, op, values) {
const makeSet=(set0)=>{
let res = []
if(set0.rangeType===0){
for(let i=set0.low;i<=set0.high;i++)
res.push(i);
} else if (set0.rangeType===1) {
for(let i=set0.low+1;i<set0.high;i++)
res.push(i);
} else if(set0.rangeType===2){
for(let i=set0.low+1;i<=set0.high;i++)
res.push(i);
} else {
for(let i=set0.low;i<set0.high;i++)
res.push(i);
}
return res;
}
let res = [],finalSet=[];
set1 = makeSet(set1);
set2 = makeSet(set2);
if(op==="union")
finalSet = [...new Set([...set1,...set2])];
else if(op==="intersect") {
for(let i=0;i<set1.length;i++)
if(set1.indexOf(set2[i])!==-1)
finalSet.push(set2[i]);
} else {
for(let i=0;i<set2.length;i++)
if(set1.indexOf(set2[i])===-1)
finalSet.push(set2[i]);
for(let i=0;i<set1.length;i++)
if(set2.indexOf(set1[i])===-1)
finalSet.push(set1[i]);
}
for(let i=0;i<values.length;i++){
if(finalSet.indexOf(values[i])!==-1)
res.push(true);
else
res.push(false);
}
return res;
} | 298Set of real numbers
| 10javascript
| 0klsz |
(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn prime? [a]
" Uses trial division to determine if number is prime "
(or (= a 2)
(and (> a 2)
(> (mod a 2) 0)
(not (some #(= 0 (mod a %))
(range 3 (inc (int (Math/ceil (math/sqrt a)))) 2))))))
(defn primes-below [n]
" Finds primes below number n "
(for [a (range 2 (inc n))
:when (prime? a)]
a))
(println (primes-below 100)) | 303Sequence of primes by trial division
| 6clojure
| 79xr0 |
class Example
def foo
42
end
def bar(arg1, arg2, &block)
block.call arg1, arg2
end
end
symbol = :foo
Example.new.send symbol
Example.new.send( :bar, 1, 2 ) { |x,y| x+y }
args = [1, 2]
Example.new.send( , *args ) { |x,y| x+y } | 299Send an unknown method call
| 14ruby
| op28v |
class Example {
def foo(x: Int): Int = 42 + x
}
object Main extends App {
val example = new Example
val meth = example.getClass.getMethod("foo", classOf[Int])
assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.")
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
} | 299Send an unknown method call
| 16scala
| fw4d4 |
require 'prime'
require 'openssl'
i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1)
start = Time.now
prime_array = Prime.first (500)
until urutan > 20
primorial_number *= prime_array[i-1]
if (primorial_number - 1).prime_fasttest? || (primorial_number + 1).prime_fasttest?
puts
urutan += 1
end
i += 1
end | 297Sequence of primorial primes
| 14ruby
| tx7f2 |
require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
def first_with_num_divs(n)
(1..).detect{|i| num_divisors(i) == n }
end
p (1..15).map{|n| first_with_num_divs(n) } | 296Sequence: smallest number with exactly n divisors
| 14ruby
| 9iamz |
use sha2::{Digest, Sha256};
fn hex_string(input: &[u8]) -> String {
input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}
fn main() { | 290SHA-256
| 15rust
| rm3g5 |
object RosettaSHA256 extends App {
def MD5(s: String): String = { | 290SHA-256
| 16scala
| hlmja |
use sha1::Sha1;
fn main() {
let mut hash_msg = Sha1::new();
hash_msg.update(b"Rosetta Code");
println!("{}", hash_msg.digest().to_string());
} | 289SHA-1
| 15rust
| napi4 |
my @c = '
@c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c))
for 1 .. 3;
print join("\n", @c), "\n"; | 283Sierpinski carpet
| 2perl
| i1xo3 |
a <- function(x) {cat("a called\n"); x}
b <- function(x) {cat("b called\n"); x}
tests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0))
invisible(apply(tests, 1, function(row) {
call <- substitute(op(a(x),b(y)), row)
cat(deparse(call), "->", eval(call), "\n\n")
})) | 284Short-circuit evaluation
| 13r
| i1wo5 |
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail
{
protected Session session;
public Mail(String host)
{
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
session = Session.getDefaultInstance(properties);
}
public void send(String from, String tos[], String ccs[], String subject,
String text)
throws MessagingException
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for (String to: tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to));
for (String cc: ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
} | 300Send email
| 9java
| 790rj |
null | 298Set of real numbers
| 11kotlin
| k2dh3 |
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
}
int main() {
int i;
for (i = 1; i < 23; i++)
printf(, nonsqr(i));
printf();
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
assert(j != floor(j));
}
return 0;
} | 306Sequence of non-squares
| 5c
| nayi6 |
typedef unsigned int set_t;
void show_set(set_t x, const char *name)
{
int i;
printf(, name);
for (i = 0; (1U << i) <= x; i++)
if (x & (1U << i))
printf(, i);
putchar('\n');
}
int main(void)
{
int i;
set_t a, b, c;
a = 0;
for (i = 0; i < 10; i += 3)
a |= (1U << i);
show_set(a, );
for (i = 0; i < 5; i++)
printf(, i, (a & (1U << i)) ? :);
b = a;
b |= (1U << 5); b |= (1U << 10);
b &= ~(1U << 0);
show_set(b, );
show_set(a | b, );
show_set(c = a & b, );
show_set(a & ~b, );
show_set(b & ~a, );
printf(, !(b & ~a) ? : );
printf(, !(c & ~a) ? : );
printf(,
((a | b) & ~(a & b)) == ((a & ~b) | (b & ~a))
? : );
return 0;
} | 307Set
| 5c
| jca70 |
import Foundation
class MyUglyClass: NSObject {
@objc
func myUglyFunction() {
print("called myUglyFunction")
}
}
let someObject: NSObject = MyUglyClass()
someObject.perform(NSSelectorFromString("myUglyFunction")) | 299Send an unknown method call
| 17swift
| 8bl0v |
import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self% i == 0 {
return false
}
return true
}
}
let limit = 20
var primorial = 1
var count = 1
var p = 3
var prod = BigInt(2)
print(1, terminator: " ")
while true {
defer {
p += 2
}
guard p.isPrime else {
continue
}
prod *= BigInt(p)
primorial += 1
if (prod + 1).isPrime() || (prod - 1).isPrime() {
print(primorial, terminator: " ")
count += 1
fflush(stdout)
if count == limit {
break
}
}
} | 297Sequence of primorial primes
| 17swift
| fwrdk |
use itertools::Itertools;
const PRIMES: [u64; 15] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];
const MAX_DIVISOR: usize = 64;
struct DivisorSeq {
max_number_of_divisors: u64,
index: u64,
}
impl DivisorSeq {
fn new(max_number_of_divisors: u64) -> DivisorSeq {
DivisorSeq {
max_number_of_divisors,
index: 1,
}
}
}
impl Iterator for DivisorSeq {
type Item = u64;
fn next(&mut self) -> Option<u64> {
if self.max_number_of_divisors < self.index {
return None;
}
#[allow(unused_mut)]
let mut result: u64;
let divisors_of_divisor = get_divisors(self.index);
match divisors_of_divisor.len() {
1 | 2 => { | 296Sequence: smallest number with exactly n divisors
| 15rust
| cne9z |
import java.nio._
case class Hash(message: List[Byte]) {
val defaultHashes = List(0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0)
val hash = {
val padded = generatePadding(message)
val chunks: List[List[Byte]] = messageToChunks(padded)
toHashForm(hashesFromChunks(chunks))
}
def generatePadding(message: List[Byte]): List[Byte] = {
val finalPadding = BigInt(message.length * 8).toByteArray match {
case x => List.fill(8 - x.length)(0.toByte) ++ x
}
val padding = (message.length + 1) % 64 match {
case l if l < 56 =>
message ::: 0x80.toByte :: List.fill(56 - l)(0.toByte)
case l =>
message ::: 0x80.toByte :: List.fill((64 - l) + 56 + 1)(0.toByte)
}
padding ::: finalPadding
}
def toBigEndian(bytes: List[Byte]) =
ByteBuffer.wrap(bytes.toArray).getInt
def messageToChunks(message: List[Byte]) =
message.grouped(64).toList
def chunkToWords(chunk: List[Byte]) =
chunk.grouped(4).map(toBigEndian).toList
def extendWords(words: List[Int]): List[Int] = words.length match {
case i if i < 80 => extendWords(words :+ Integer.rotateLeft(
(words(i - 3) ^ words(i - 8) ^ words(i - 14) ^ words(i - 16)), 1))
case _ => words
}
def generateFK(i: Int, b: Int, c: Int, d: Int) = i match {
case i if i < 20 => (b & c | ~b & d, 0x5A827999)
case i if i < 40 => (b ^ c ^ d, 0x6ED9EBA1)
case i if i < 60 => (b & c | b & d | c & d, 0x8F1BBCDC)
case i if i < 80 => (b ^ c ^ d, 0xCA62C1D6)
}
def generateHash(words: List[Int], prevHash: List[Int]): List[Int] = {
def generateHash(i: Int, currentHashes: List[Int]): List[Int] = i match {
case i if i < 80 => currentHashes match {
case a :: b :: c :: d :: e :: Nil => {
val (f, k) = generateFK(i, b, c, d)
val x = Integer.rotateLeft(a, 5) + f + e + k + words(i)
val t = Integer.rotateLeft(b, 30)
generateHash(i + 1, x :: a :: t :: c :: d :: Nil)
}
}
case _ => currentHashes
}
addHashes(prevHash, generateHash(0, prevHash))
}
def addHashes(xs: List[Int], ys: List[Int]) = (xs, ys).zipped.map(_ + _)
def hashesFromChunks(chunks: List[List[Byte]],
remainingHash: List[Int] = defaultHashes): List[Int] =
chunks match {
case Nil => remainingHash
case x :: xs => {
val words = extendWords(chunkToWords(x))
val newHash = generateHash(words, remainingHash)
hashesFromChunks(xs, newHash)
}
}
def toHashForm(hashes: List[Int]) =
hashes.map(b => ByteBuffer.allocate(4)
.order(ByteOrder.BIG_ENDIAN).putInt(b).array.toList)
.map(bytesToHex).mkString
def bytesToHex(bytes: List[Byte]) =
(for (byte <- bytes) yield (Character.forDigit((byte >> 4) & 0xF, 16) ::
Character.forDigit((byte & 0xF), 16) :: Nil).mkString).mkString
}
object Hash extends App {
def hash(message: String) = new Hash(message.getBytes.toList).hash
println(hash("Rosetta Code"))
} | 289SHA-1
| 16scala
| txefb |
null | 300Send email
| 11kotlin
| uzevc |
(ns example
(:gen-class))
(defn semi-prime? [n]
(loop [a 2
b 0
c n]
(cond
(> b 2) false
(<= c 1) (= b 2)
(= 0 (rem c a)) (recur a (inc b) (int (/ c a)))
:else (recur (inc a) b c))))
(println (filter semi-prime? (range 1 100))) | 304Semiprime
| 6clojure
| k2shs |
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
}
int main()
{
int i;
for (i = 1; i < 100000000; i++)
if (self_desc(i)) printf(, i);
return 0;
} | 308Self-describing numbers
| 5c
| a4s11 |
function createSet(low,high,rt)
local l,h = tonumber(low), tonumber(high)
if l and h then
local t = {low=l, high=h}
if type(rt) == "string" then
if rt == "open" then
t.contains = function(d) return low< d and d< high end
elseif rt == "closed" then
t.contains = function(d) return low<=d and d<=high end
elseif rt == "left" then
t.contains = function(d) return low< d and d<=high end
elseif rt == "right" then
t.contains = function(d) return low<=d and d< high end
else
error("Unknown range type: "..rt)
end
elseif type(rt) == "function" then
t.contains = rt
else
error("Unable to find a range type or predicate")
end
t.union = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) or o.contains(d) end
return createSet(l2, h2, p)
end
t.intersect = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and o.contains(d) end
return createSet(l2, h2, p)
end
t.subtract = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and not o.contains(d) end
return createSet(l2, h2, p)
end
t.length = function()
if h <= l then return 0.0 end
local p = l
local count = 0
local interval = 0.00001
repeat
if t.contains(p) then count = count + 1 end
p = p + interval
until p>=high
return count * interval
end
t.empty = function()
if l == h then
return not t.contains(low)
end
return t.length() == 0.0
end
return t
else
error("Either '"..low.."' or '"..high.."' is not a number")
end
end
local a = createSet(0.0, 1.0, "left")
local b = createSet(0.0, 2.0, "right")
local c = createSet(1.0, 2.0, "left")
local d = createSet(0.0, 3.0, "right")
local e = createSet(0.0, 1.0, "open")
local f = createSet(0.0, 1.0, "closed")
local g = createSet(0.0, 0.0, "closed")
for i=0,2 do
print("(0, 1] union [0, 2) contains "..i.." is "..tostring(a.union(b).contains(i)))
print("[0, 2) intersect (1, 2] contains "..i.." is "..tostring(b.intersect(c).contains(i)))
print("[0, 3) - (0, 1) contains "..i.." is "..tostring(d.subtract(e).contains(i)))
print("[0, 3) - [0, 1] contains "..i.." is "..tostring(d.subtract(f).contains(i)))
print()
end
print("[0, 0] is empty is "..tostring(g.empty()))
print()
local aa = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x * x)) > 0.5 end
)
local bb = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x)) > 0.5 end
)
local cc = aa.subtract(bb)
print("Approx length of A - B is "..cc.length()) | 298Set of real numbers
| 1lua
| bvfka |
use strict;
use English;
use Smart::Comments;
my @ex1 = consolidate( (['A', 'B'], ['C', 'D']) );
my @ex2 = consolidate( (['A', 'B'], ['B', 'D']) );
my @ex3 = consolidate( (['A', 'B'], ['C', 'D'], ['D', 'B']) );
my @ex4 = consolidate( (['H', 'I', 'K'], ['A', 'B'], ['C', 'D'], ['D', 'B'], ['F', 'G', 'H']) );
exit 0;
sub consolidate {
scalar(@ARG) >= 2 or return @ARG;
my @result = ( shift(@ARG) );
my @recursion = consolidate(@ARG);
foreach my $r (@recursion) {
if (set_intersection($result[0], $r)) {
$result[0] = [ set_union($result[0], $r) ];
}
else {
push @result, $r;
}
}
return @result;
}
sub set_union {
my ($a, $b) = @ARG;
my %union;
foreach my $a_elt (@{$a}) { $union{$a_elt}++; }
foreach my $b_elt (@{$b}) { $union{$b_elt}++; }
return keys(%union);
}
sub set_intersection {
my ($a, $b) = @ARG;
my %a_hash;
foreach my $a_elt (@{$a}) { $a_hash{$a_elt}++; }
my @result;
foreach my $b_elt (@{$b}) {
push(@result, $b_elt) if exists($a_hash{$b_elt});
}
return @result;
} | 295Set consolidation
| 2perl
| bv3k4 |
null | 296Sequence: smallest number with exactly n divisors
| 17swift
| mo1yk |
<?php
function isSierpinskiCarpetPixelFilled($x, $y) {
while (($x > 0) or ($y > 0)) {
if (($x % 3 == 1) and ($y % 3 == 1)) {
return false;
}
$x /= 3;
$y /= 3;
}
return true;
}
function sierpinskiCarpet($order) {
$size = pow(3, $order);
for ($y = 0 ; $y < $size ; $y++) {
for ($x = 0 ; $x < $size ; $x++) {
echo isSierpinskiCarpetPixelFilled($x, $y)? '
}
echo PHP_EOL;
}
}
for ($order = 0 ; $order <= 3 ; $order++) {
echo 'N=', $order, PHP_EOL;
sierpinskiCarpet($order);
echo PHP_EOL;
} | 283Sierpinski carpet
| 12php
| rm2ge |
(ns rosettacode.semordnilaps
(:require [clojure.string :as str])
[clojure.java.io:as io ]))
(def dict-file
(or (first *command-line-args*) "unixdict.txt"))
(def dict (-> dict-file io/reader line-seq set))
(defn semordnilap? [word]
(let [rev (str/reverse word)]
(and (not= word rev) (dict rev))))
(def semordnilaps
(->> dict
(filter semordnilap?)
(map #([% (str/reverse %)]))
(filter (fn [[x y]] (<= (compare x y) 0)))))
(printf "There are%d semordnilaps in%s. Here are 5:\n"
(count semordnilaps)
dict-file)
(dorun (->> semordnilaps shuffle (take 5) sort (map println))) | 305Semordnilap
| 6clojure
| gy14f |
def a( bool )
puts
bool
end
def b( bool )
puts
bool
end
[true, false].each do |a_val|
[true, false].each do |b_val|
puts
puts
puts
puts
end
end | 284Short-circuit evaluation
| 14ruby
| 3soz7 |
package main
import (
"fmt"
"time"
)
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func main() {
st := time.Now()
count := 0
var selfs []int
i := 1
pow := 10
digits := 1
offset := 9
lastSelf := 0
for count < 1e8 {
isSelf := true
start := max(i-offset, 0)
sum := sumDigits(start)
for j := start; j < i; j++ {
if j+sum == i {
isSelf = false
break
}
if (j+1)%10 != 0 {
sum++
} else {
sum = sumDigits(j + 1)
}
}
if isSelf {
count++
lastSelf = i
if count <= 50 {
selfs = append(selfs, i)
if count == 50 {
fmt.Println("The first 50 self numbers are:")
fmt.Println(selfs)
}
}
}
i++
if i%pow == 0 {
pow *= 10
digits++
offset = digits * 9
}
}
fmt.Println("\nThe 100 millionth self number is", lastSelf)
fmt.Println("Took", time.Since(st))
} | 302Self numbers
| 0go
| sh6qa |
use charnames ':full';
binmode STDOUT, ':utf8';
sub glyph {
my($n) = @_;
if ($n < 33) { chr 0x2400 + $n }
elsif ($n==124) { '<nowiki>|</nowiki>' }
elsif ($n==127) { 'DEL' }
else { chr $n }
}
print qq[{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"\n];
for (0..127) {
print qq[|-\n] unless $_ % 16;;
printf qq[|%d<br>0x%02X<br><big><big title="%s">%s</big></big>\n],
$_, $_, charnames::viacode($_), glyph($_);
}
}
print qq[|}\n]; | 288Show ASCII table
| 2perl
| wrge6 |
ruby -le'16.times{|y|print*(15-y),*(0..y).map{|x|~y&x>0?:}}' | 278Sierpinski triangle
| 14ruby
| kvkhg |
fn a(foo: bool) -> bool {
println!("a");
foo
}
fn b(foo: bool) -> bool {
println!("b");
foo
}
fn main() {
for i in vec![true, false] {
for j in vec![true, false] {
println!("{} and {} == {}", i, j, a(i) && b(j));
println!("{} or {} == {}", i, j, a(i) || b(j));
println!();
}
}
} | 284Short-circuit evaluation
| 15rust
| 60i3l |
import Control.Monad (forM_)
import Text.Printf
selfs :: [Integer]
selfs = sieve (sumFs [0..]) [0..]
where
sumFs = zipWith (+) [ a+b+c+d+e+f+g+h+i+j
| a <- [0..9] , b <- [0..9]
, c <- [0..9] , d <- [0..9]
, e <- [0..9] , f <- [0..9]
, g <- [0..9] , h <- [0..9]
, i <- [0..9] , j <- [0..9] ]
sieve (f:fs) (n:ns)
| n > f = sieve fs (n:ns)
| n `notElem` take 81 (f:fs) = n: sieve (f:fs) ns
| otherwise = sieve (f:fs) ns
main = do
print $ take 50 selfs
forM_ [1..8] $ \i ->
printf "1e%v\t%v\n" (i :: Int) (selfs !! (10^i-1)) | 302Self numbers
| 8haskell
| 9ijmo |
(use 'clojure.contrib.math)
(defn nonsqr [#^Integer n] (+ n (floor (+ 0.5 (Math/sqrt n)))))
(defn square? [#^Double n]
(let [r (floor (Math/sqrt n))]
(= (* r r) n)))
(doseq [n (range 1 23)] (printf "%s ->%s\n" n (nonsqr n)))
(defn verify [] (not-any? square? (map nonsqr (range 1 1000000))) ) | 306Sequence of non-squares
| 6clojure
| 3s2zr |
object ShortCircuit {
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
def main(args: Array[String]): Unit = {
val boolVals=List(false,true)
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b AND B=%5b -> ".format(aa, bb))
a(aa) && b(bb)
}
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b OR B=%5b -> ".format(aa, bb))
a(aa) || b(bb)
}
println
}
} | 284Short-circuit evaluation
| 16scala
| 9ifm5 |
null | 300Send email
| 1lua
| 53wu6 |
public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {
for (int d = 9, t = s + c; d >= 0; d--) {
dS[i--] = t + d;
}
}
}
}
for (int a = 0, n = 0; a < 103; a++) {
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {
for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {
SV[dS[c] + s++] = true;
}
}
}
}
public static void main(String[] args) {
sieve();
System.out.println("The first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) {
if (!SV[i]) {
count++;
if (count <= 50) {
System.out.printf("%d ", i);
} else {
System.out.printf("%n%n Index Self number%n");
}
}
}
for (int i = 0, limit = 1, count = 0; i < MC; i++) {
if (!SV[i]) {
if (++count == limit) {
System.out.printf("%,12d %,13d%n", count, i);
limit *= 10;
}
}
}
}
} | 302Self numbers
| 9java
| txuf9 |
use utf8;
package BNum;
use overload (
'""' => \&_str,
'<=>' => \&_cmp,
);
sub new {
my $self = shift;
bless [@_], ref $self || $self
}
sub flip {
my @a = @{+shift};
$a[2] = !$a[2];
bless \@a
}
my $brackets = qw/ [ ( ) ] /;
sub _str {
my $v = sprintf "%.2f", $_[0][0];
$_[0][2]
? $v . ($_[0][1] == 1 ? "]" : ")")
: ($_[0][1] == 1 ? "(" : "[" ) . $v;
}
sub _cmp {
my ($a, $b, $swap) = @_;
if ($swap) { return -_ncmp($a, $b) }
if (!ref $b || !$b->isa(__PACKAGE__)) { return _ncmp($a, $b) }
$a->[0] <=> $b->[0] || $a->[1] <=> $b->[1]
}
sub _ncmp {
my ($a, $b) = @_;
$a->[0] <=> $b || $a->[1] <=> 0
}
package RealSet;
use Carp;
use overload (
'""' => \&_str,
'|' => \&_or,
'&' => \&_and,
'~' => \&_neg,
'-' => \&_diff,
'bool' => \¬_empty,
);
my %pm = qw/ [ -1 ( 1 ) -1 ] 1 /;
sub range {
my ($cls, $a, $b, $spec) = @_;
$spec =~ /^( \[ | \( )( \) | \] )$/x or croak "bad spec $spec";
$a = BNum->new($a, $pm{$1}, 0);
$b = BNum->new($b, $pm{$2}, 1);
normalize($a < $b ? [$a, $b] : [])
}
sub normalize {
my @a = @{+shift};
for (my $i = $
splice @a, $i - 1, 2
if $a[$i] <= $a[$i - 1]
}
bless \@a
}
sub not_empty { scalar @{ normalize shift } }
sub _str {
my (@a, @s) = @{+shift} or return '()';
join " ", map { shift(@a).", ".shift(@a) } 0 .. $
}
sub _or {
my $d = 0;
normalize [
map { $_->[2] ? --$d ? () : ($_)
: $d++ ? () : ($_) }
sort{ $a <=> $b } @{+shift}, @{+shift}
];
}
sub _neg {
normalize [
BNum->new('-inf', 1, 0),
map($_->flip, @{+shift}),
BNum->new('inf', -1, 1),
]
}
sub _and {
my $d = 0;
normalize [
map { $_->[2] ? --$d ? ($_) : ()
: $d++ ? ($_) : () }
sort{ $a <=> $b } @{+shift}, @{+shift}
];
}
sub _diff { shift() & ~shift() }
sub has {
my ($a, $b) = @_;
for (my $i = 0; $i < $
return 1 if $a->[$i] <= $b && $b <= $a->[$i + 1]
}
return 0
}
sub len {
my ($a, $l) = shift;
for (my $i = 0; $i < $
$l += $a->[$i+1][0] - $a->[$i][0]
}
return $l
}
package main;
use List::Util 'reduce';
sub rng { RealSet->range(@_) }
my @sets = (
rng(0, 1, '(]') | rng(0, 2, '[)'),
rng(0, 2, '[)') & rng(0, 2, '(]'),
rng(0, 3, '[)') - rng(0, 1, '()'),
rng(0, 3, '[)') - rng(0, 1, '[]'),
);
for my $i (0 .. $
print "Set $i = ", $sets[$i], ": ";
for (0 .. 2) {
print "has $_; " if $sets[$i]->has($_);
}
print "\n";
}
print "\n
sub brev {
my $x = shift;
return $x if length $x < 60;
substr($x, 0, 30)." ... ".substr($x, -30, 30)
}
my $x = reduce { $a | $b }
map(rng(sqrt($_ + 1./6), sqrt($_ + 5./6), '()'), 0 .. 101);
$x &= rng(0, 10, '()');
print "A\t", '= {x | 0 < x < 10 and |sin( x)| > 1/2 }',
"\n\t= ", brev($x), "\n";
my $y = reduce { $a | $b }
map { rng($_ + 1./6, $_ + 5./6, '()') } 0 .. 11;
$y &= rng(0, 10, '()');
print "B\t", '= {x | 0 < x < 10 and |sin( x)| > 1/2 }',
"\n\t= ", brev($y), "\n";
my $z = $x - $y;
print "A - B\t= ", brev($z), "\n\tlength = ", $z->len, "\n";
print $z ? "not empty\n" : "empty\n"; | 298Set of real numbers
| 2perl
| 3sjzs |
(require 'clojure.set)
(def a (set [1 2 3 4]))
(def b #{4 5 6 7})
(a 10)
(clojure.set/union a b)
(clojure.set/intersection a b)
(clojure.set/difference a b)
(clojure.set/subset? a b) | 307Set
| 6clojure
| 15spy |
def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s] | 295Set consolidation
| 3python
| pu6bm |
<?php
echo '+' . str_repeat('----------+', 6), PHP_EOL;
for ($j = 0 ; $j < 16 ; $j++) {
for ($i = 0 ; $i < 6 ; $i++) {
$val = 32 + $i * 16 + $j;
switch ($val) {
case 32: $chr = 'Spc'; break;
case 127: $chr = 'Del'; break;
default: $chr = chr($val) ; break;
}
echo sprintf('|%3d:%3s ', $val, $chr);
}
echo '|', PHP_EOL;
}
echo '+' . str_repeat('----------+', 6), PHP_EOL; | 288Show ASCII table
| 12php
| ldncj |
use std::iter::repeat;
fn sierpinski(order: usize) {
let mut triangle = vec!["*".to_string()];
for i in 0..order {
let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>(); | 278Sierpinski triangle
| 15rust
| bubkx |
private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1
private val SV = BooleanArray(MC + 1)
private fun sieve() {
val dS = IntArray(10000)
run {
var a = 9
var i = 9999
while (a >= 0) {
for (b in 9 downTo 0) {
var c = 9
val s = a + b
while (c >= 0) {
var d = 9
val t = s + c
while (d >= 0) {
dS[i--] = t + d
d--
}
c--
}
}
a--
}
}
var a = 0
var n = 0
while (a < 103) {
var b = 0
val d = dS[a]
while (b < 1000) {
var c = 0
var s = d + dS[b] + n
while (c < 10000) {
SV[dS[c] + s++] = true
c++
}
b++
n += 10000
}
a++
}
}
fun main() {
sieve()
println("The first 50 self numbers are:")
run {
var i = 0
var count = 0
while (count <= 50) {
if (!SV[i]) {
count++
if (count <= 50) {
print("$i ")
} else {
println()
println()
println(" Index Self number")
}
}
i++
}
}
var i = 0
var limit = 1
var count = 0
while (i < MC) {
if (!SV[i]) {
if (++count == limit) {
println("%,12d %,13d".format(count, i))
limit *= 10
}
}
i++
}
} | 302Self numbers
| 11kotlin
| op98z |
scala -e "for(y<-0 to 15){println(\" \"*(15-y)++(0 to y).map(x=>if((~y&x)>0)\" \"else\" *\")mkString)}" | 278Sierpinski triangle
| 16scala
| aga1n |
use Net::SMTP;
use Authen::SASL;
sub send_email
{my %o =
(from => '', to => [], cc => [],
subject => '', body => '',
host => '', user => '', password => '',
@_);
ref $o{$_} or $o{$_} = [$o{$_}] foreach 'to', 'cc';
my $smtp = new Net::SMTP($o{host} ? $o{host} : ())
or die "Couldn't connect to SMTP server";
$o{password} and
$smtp->auth($o{user}, $o{password}) ||
die 'SMTP authentication failed';
$smtp->mail($o{user});
$smtp->recipient($_) foreach @{$o{to}}, @{$o{cc}};
$smtp->data;
$o{from} and $smtp->datasend("From: $o{from}\n");
$smtp->datasend('To: ' . join(', ', @{$o{to}}) . "\n");
@{$o{cc}} and $smtp->datasend('Cc: ' . join(', ', @{$o{cc}}) . "\n");
$o{subject} and $smtp->datasend("Subject: $o{subject}\n");
$smtp->datasend("\n$o{body}");
$smtp->dataend;
return 1;} | 300Send email
| 2perl
| 8bc0w |
class Setr():
def __init__(self, lo, hi, includelo=True, includehi=False):
self.eqn = % (lo,
'=' if includelo else '',
'=' if includehi else '',
hi)
def __contains__(self, X):
return eval(self.eqn, locals())
def __or__(self, b):
ans = Setr(0,0)
ans.eqn = % (self.eqn, b.eqn)
return ans
def __and__(self, b):
ans = Setr(0,0)
ans.eqn = % (self.eqn, b.eqn)
return ans
def __sub__(self, b):
ans = Setr(0,0)
ans.eqn = % (self.eqn, b.eqn)
return ans
def __repr__(self):
return % self.eqn
sets = [
Setr(0,1, 0,1) | Setr(0,2, 1,0),
Setr(0,2, 1,0) & Setr(1,2, 0,1),
Setr(0,3, 1,0) - Setr(0,1, 0,0),
Setr(0,3, 1,0) - Setr(0,1, 1,1),
]
settexts = '(0, 1] [0, 2);[0, 2) (1, 2];[0, 3) (0, 1);[0, 3) [0, 1]'.split(';')
for s,t in zip(sets, settexts):
print(% (t,
', '.join(
% ('in' if v in s else 'ex', v)
for v in range(3)),
s.eqn)) | 298Set of real numbers
| 3python
| 60h3w |
package main
import (
"fmt"
"strconv"
"strings"
) | 308Self-describing numbers
| 0go
| movyi |
use strict;
use warnings;
use feature 'say';
use List::Util qw(max sum);
my ($i, $pow, $digits, $offset, $lastSelf, @selfs)
= ( 1, 10, 1, 9, 0, );
my $final = 50;
while () {
my $isSelf = 1;
my $sum = my $start = sum split //, max(($i-$offset), 0);
for ( my $j = $start; $j < $i; $j++ ) {
if ($j+$sum == $i) { $isSelf = 0 ; last }
($j+1)%10 != 0 ? $sum++ : ( $sum = sum split '', ($j+1) );
}
if ($isSelf) {
push @selfs, $lastSelf = $i;
last if @selfs == $final;
}
next unless ++$i % $pow == 0;
$pow *= 10;
$offset = 9 * $digits++
}
say "The first 50 self numbers are:\n" . join ' ', @selfs; | 302Self numbers
| 2perl
| gyw4e |
require 'set'
tests = [[[:A,:B], [:C,:D]],
[[:A,:B], [:B,:D]],
[[:A,:B], [:C,:D], [:D,:B]],
[[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]]
tests.map!{|sets| sets.map(&:to_set)}
tests.each do |sets|
until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(b)}
end
p sets
end | 295Set consolidation
| 14ruby
| a4m1s |
mail('[email protected]', 'My Subject', , ); | 300Send email
| 12php
| 46x5n |
import Data.Char
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
isSelfDescribing :: Integer -> Bool
isSelfDescribing n = nu == f
where
nu = digitToInt <$> show n
f = (`count` nu) <$> [0 .. length nu - 1]
main :: IO ()
main = do
print $
isSelfDescribing <$>
[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000]
print $ filter isSelfDescribing [0 .. 4000000] | 308Self-describing numbers
| 8haskell
| k2eh0 |
void main(){ | 307Set
| 18dart
| uzjvs |
DIM n AS Integer, k AS Integer, limit AS Integer
INPUT "Enter number to search to: "; limit
DIM flags(limit) AS Integer
FOR n = 2 TO SQR(limit)
IF flags(n) = 0 THEN
FOR k = n*n TO limit STEP n
flags(k) = 1
NEXT k
END IF
NEXT n
' Display the primes
FOR n = 2 TO limit
IF flags(n) = 0 THEN PRINT n; ", ";
NEXT n | 309Sieve of Eratosthenes
| 4bash
| 8bd0a |
object SetConsolidation extends App {
def consolidate[Type](sets: Set[Set[Type]]): Set[Set[Type]] = {
var result = sets | 295Set consolidation
| 16scala
| qj2xw |
for i in range(16):
for j in range(32+i, 127+1, 16):
if j == 32:
k = 'Spc'
elif j == 127:
k = 'Del'
else:
k = chr(j)
print(% (j,k), end=)
print() | 288Show ASCII table
| 3python
| x7rwr |
func a(v: Bool) -> Bool {
print("a")
return v
}
func b(v: Bool) -> Bool {
print("b")
return v
}
func test(i: Bool, j: Bool) {
println("Testing a(\(i)) && b(\(j))")
print("Trace: ")
println("\nResult: \(a(i) && b(j))")
println("Testing a(\(i)) || b(\(j))")
print("Trace: ")
println("\nResult: \(a(i) || b(j))")
println()
}
test(false, false)
test(false, true)
test(true, false)
test(true, true) | 284Short-circuit evaluation
| 17swift
| zq8tu |
package main
import "fmt"
func semiprime(n int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == 2 {
return false
}
nf++
n /= i
}
}
return nf == 2
}
func main() {
for v := 1675; v <= 1680; v++ {
fmt.Println(v, "->", semiprime(v))
}
} | 304Semiprime
| 0go
| i1mog |
int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = ;
int sedol_checksum(const char *sedol6)
{
int len = strlen(sedol6);
int sum = 0, i;
if ( len == 7 ) {
fprintf(stderr, , sedol6);
return sedol6[6] & 0x7f;
}
if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {
fprintf(stderr, , sedol6);
return -1;
}
for(i=0; i < 6; i++) {
if ( isdigit(sedol6[i]) ) {
sum += (sedol6[i]-'0')*sedol_weights[i];
} else if ( isalpha(sedol6[i]) ) {
sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];
} else {
fprintf(stderr, );
return -1;
}
}
return (10 - (sum%10))%10 + '0';
}
int main()
{
char line[MAXLINELEN];
int sr, len;
while( fgets(line, MAXLINELEN, stdin) != NULL ) {
len = strlen(line);
if ( line[len-1] == '\n' ) line[len-1]='\0';
sr = sedol_checksum(line);
if ( sr > 0 )
printf(, line, sr);
}
return 0;
} | 310SEDOLs
| 5c
| vt42o |
class DigitSumer:
def __init__(self):
sumdigit = lambda n: sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000:
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
def self_numbers ():
d = DigitSumer()
s = set([])
i = 1
while 1:
n = i + d( i )
if i in s:
s.discard( i )
else:
yield i
s.add( n )
i += 1
import time
p = 100
t = time.time()
for i,s in enumerate( self_numbers(),1 ):
if i <= 50:
print s,
if i == 50: print
if i == p:
print '%7.1f sec %9dth =%d'%( time.time()-t,i,s )
p *= 10 | 302Self numbers
| 3python
| rmxgq |
class Rset
Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do
def include?(x)
(inc_lo? lo<=x: lo<x) and (inc_hi? x<=hi: x<hi)
end
def length
hi - lo
end
def to_s
end
end
def initialize(lo=nil, hi=nil, inc_lo=false, inc_hi=false)
if lo.nil? and hi.nil?
@sets = []
else
raise TypeError unless lo.is_a?(Numeric) and hi.is_a?(Numeric)
raise ArgumentError unless valid?(lo, hi, inc_lo, inc_hi)
@sets = [Set[lo, hi,!!inc_lo,!!inc_hi]]
end
end
def self.[](lo, hi, inc_hi=true)
self.new(lo, hi, true, inc_hi)
end
def self.parse(str)
raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/
b0, lo, hi, b1 = $~.captures
lo = Rational(lo)
lo = lo.numerator if lo.denominator == 1
hi = Rational(hi)
hi = hi.numerator if hi.denominator == 1
self.new(lo, hi, b0=='[', b1==']')
end
def initialize_copy(obj)
super
@sets = @sets.map(&:dup)
end
def include?(x)
@sets.any?{|set| set.include?(x)}
end
def empty?
@sets.empty?
end
def union(other)
sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]}
work = []
pre = sets.shift
sets.each do |post|
if valid?(pre.hi, post.lo,!pre.inc_hi,!post.inc_lo)
work << pre
pre = post
else
pre.inc_lo |= post.inc_lo if pre.lo == post.lo
if pre.hi < post.hi
pre.hi = post.hi
pre.inc_hi = post.inc_hi
elsif pre.hi == post.hi
pre.inc_hi |= post.inc_hi
end
end
end
work << pre if pre
new_Rset(work)
end
alias | union
def intersection(other)
sets = @sets.map(&:dup)
work = []
other.sets.each do |oset|
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
elsif oset.lo < set.lo and set.hi < oset.hi
work << set
else
lo = [set.lo, oset.lo].max
if set.lo == oset.lo
inc_lo = set.inc_lo && oset.inc_lo
else
inc_lo = (set.lo < oset.lo)? oset.inc_lo: set.inc_lo
end
hi = [set.hi, oset.hi].min
if set.hi == oset.hi
inc_hi = set.inc_hi && oset.inc_hi
else
inc_hi = (set.hi < oset.hi)? set.inc_hi: oset.inc_hi
end
work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi)
end
end
end
new_Rset(work)
end
alias & intersection
def difference(other)
sets = @sets.map(&:dup)
other.sets.each do |oset|
work = []
sets.each do |set|
if set.hi < oset.lo or oset.hi < set.lo
work << set
elsif oset.lo < set.lo and set.hi < oset.hi
else
if set.lo < oset.lo
inc_hi = (set.hi==oset.lo and!set.inc_hi)? false:!oset.inc_lo
work << Set[set.lo, oset.lo, set.inc_lo, inc_hi]
elsif valid?(set.lo, oset.lo, set.inc_lo,!oset.inc_lo)
work << Set[set.lo, set.lo, true, true]
end
if oset.hi < set.hi
inc_lo = (oset.hi==set.lo and!set.inc_lo)? false:!oset.inc_hi
work << Set[oset.hi, set.hi, inc_lo, set.inc_hi]
elsif valid?(oset.hi, set.hi,!oset.inc_hi, set.inc_hi)
work << Set[set.hi, set.hi, true, true]
end
end
end
sets = work
end
new_Rset(sets)
end
alias - difference
def ^(other)
(self - other) | (other - self)
end
def ==(other)
self.class == other.class and @sets == other.sets
end
def length
@sets.inject(0){|len, set| len + set.length}
end
def to_s
end
alias inspect to_s
protected
attr_accessor :sets
private
def new_Rset(sets)
rset = self.class.new
rset.sets = sets
rset
end
def valid?(lo, hi, inc_lo, inc_hi)
lo < hi or (lo==hi and inc_lo and inc_hi)
end
end
def Rset(lo, hi, inc_hi=false)
Rset.new(lo, hi, false, inc_hi)
end | 298Set of real numbers
| 14ruby
| mobyj |
package main
import "fmt"
func NumsFromBy(from int, by int, ch chan<- int) {
for i := from; ; i+=by {
ch <- i
}
}
func Filter(in <-chan int, out chan<- int, prime int) {
for {
i := <-in
if i%prime != 0 { | 303Sequence of primes by trial division
| 0go
| 0k6sk |
import Foundation | 278Sierpinski triangle
| 17swift
| h2hj0 |
import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From:%s\n'% from_addr
header += 'To:%s\n'% ','.join(to_addr_list)
header += 'Cc:%s\n'% ','.join(cc_addr_list)
header += 'Subject:%s\n\n'% subject
message = header + message
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems | 300Send email
| 3python
| opl81 |
library(RDCOMClient)
send.mail <- function(to, title, body) {
olMailItem <- 0
ol <- COMCreate("Outlook.Application")
msg <- ol$CreateItem(olMailItem)
msg[["To"]] <- to
msg[["Subject"]] <- title
msg[["Body"]] <- body
msg$Send()
ol$Quit()
}
send.mail("somebody@somewhere", "Title", "Hello") | 300Send email
| 13r
| qjyxs |
isSemiprime :: Int -> Bool
isSemiprime n = (length factors) == 2 && (product factors) == n ||
(length factors) == 1 && (head factors) ^ 2 == n
where factors = primeFactors n | 304Semiprime
| 8haskell
| vtk2k |
public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0); | 308Self-describing numbers
| 9java
| 46h58 |
#[derive(Debug)]
enum SetOperation {
Union,
Intersection,
Difference,
}
#[derive(Debug, PartialEq)]
enum RangeType {
Inclusive,
Exclusive,
}
#[derive(Debug)]
struct CompositeSet<'a> {
operation: SetOperation,
a: &'a RealSet<'a>,
b: &'a RealSet<'a>,
}
#[derive(Debug)]
struct RangeSet {
range_types: (RangeType, RangeType),
start: f64,
end: f64,
}
#[derive(Debug)]
enum RealSet<'a> {
RangeSet(RangeSet),
CompositeSet(CompositeSet<'a>),
}
impl RangeSet {
fn compare_start(&self, n: f64) -> bool {
if self.range_types.0 == RangeType::Inclusive {
self.start <= n
} else {
self.start < n
}
}
fn compare_end(&self, n: f64) -> bool {
if self.range_types.1 == RangeType::Inclusive {
n <= self.end
} else {
n < self.end
}
}
}
impl<'a> RealSet<'a> {
fn new(start_type: RangeType, start: f64, end: f64, end_type: RangeType) -> Self {
RealSet::RangeSet(RangeSet {
range_types: (start_type, end_type),
start,
end,
})
}
fn operation(&'a self, other: &'a Self, operation: SetOperation) -> Self {
RealSet::CompositeSet(CompositeSet {
operation,
a: self,
b: other,
})
}
fn union(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Union)
}
fn intersection(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Intersection)
}
fn difference(&'a self, other: &'a Self) -> Self {
self.operation(other, SetOperation::Difference)
}
fn contains(&self, n: f64) -> bool {
if let RealSet::RangeSet(range) = self {
range.compare_start(n) && range.compare_end(n)
} else if let RealSet::CompositeSet(range) = self {
match range.operation {
SetOperation::Union => range.a.contains(n) || range.b.contains(n),
SetOperation::Intersection => range.a.contains(n) && range.b.contains(n),
SetOperation::Difference => range.a.contains(n) &&!range.b.contains(n),
}
} else {
unimplemented!();
}
}
}
fn make_contains_phrase(does_contain: bool) -> &'static str {
if does_contain {
"contains"
} else {
"does not contain"
}
}
use RangeType::*;
fn main() {
for (set_name, set) in [
(
"(0, 1] [0, 2)",
RealSet::new(Exclusive, 0.0, 1.0, Inclusive)
.union(&RealSet::new(Inclusive, 0.0, 2.0, Exclusive)),
),
(
"[0, 2) (1, 2]",
RealSet::new(Inclusive, 0.0, 2.0, Exclusive)
.intersection(&RealSet::new(Exclusive, 1.0, 2.0, Inclusive)),
),
(
"[0, 3) (0, 1)",
RealSet::new(Inclusive, 0.0, 3.0, Exclusive)
.difference(&RealSet::new(Exclusive, 0.0, 1.0, Exclusive)),
),
(
"[0, 3) [0, 1]",
RealSet::new(Inclusive, 0.0, 3.0, Exclusive)
.difference(&RealSet::new(Inclusive, 0.0, 1.0, Inclusive)),
),
] {
println!("Set {}", set_name);
for i in [0.0, 1.0, 2.0] {
println!("- {} {}", make_contains_phrase(set.contains(i)), i);
}
}
} | 298Set of real numbers
| 15rust
| 9ipmm |
[n | n <- [2..], []==[i | i <- [2..n-1], rem n i == 0]] | 303Sequence of primes by trial division
| 8haskell
| cnj94 |
def in_carpet(x, y):
while True:
if x == 0 or y == 0:
return True
elif x% 3 == 1 and y% 3 == 1:
return False
x /= 3
y /= 3
def carpet(n):
for i in xrange(3 ** n):
for j in xrange(3 ** n):
if in_carpet(i, j):
print '*',
else:
print ' ',
print | 283Sierpinski carpet
| 3python
| naqiz |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SemiPrime{
private static final BigInteger TWO = BigInteger.valueOf(2);
public static List<BigInteger> primeDecomp(BigInteger a){ | 304Semiprime
| 9java
| y846g |
function is_self_describing(n) {
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)});
var len = digits.length;
var count = digits.map(function(x){return 0});
digits.forEach(function(digit, idx, ary) {
if (digit >= count.length)
return false
count[digit] ++;
});
return digits.equals(count);
}
Array.prototype.equals = function(other) {
if (this === other)
return true; | 308Self-describing numbers
| 10javascript
| hlajh |
import java.util.stream.IntStream;
public class Test {
static IntStream getPrimes(int start, int end) {
return IntStream.rangeClosed(start, end).filter(n -> isPrime(n));
}
public static boolean isPrime(long x) {
if (x < 3 || x % 2 == 0)
return x == 2;
long max = (long) Math.sqrt(x);
for (long n = 3; n <= max; n += 2) {
if (x % n == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
getPrimes(0, 100).forEach(p -> System.out.printf("%d, ", p));
}
} | 303Sequence of primes by trial division
| 9java
| zqutq |
chr <- function(n) {
rawToChar(as.raw(n))
}
idx <- 32
while (idx < 128) {
for (i in 0:5) {
num <- idx + i
if (num<100) cat(" ")
cat(num,": ")
if (num == 32) { cat("Spc "); next }
if (num == 127) { cat("Del "); next }
cat(chr(num)," ")
}
idx <- idx + 6
cat("\n")
} | 288Show ASCII table
| 13r
| 15upn |
(defn sedols [xs]
(letfn [(sedol [ys] (let [weights [1 3 1 7 3 9]
convtonum (map #(Character/getNumericValue %) ys)
check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))]
(str ys check)))]
(map #(sedol %) xs))) | 310SEDOLs
| 6clojure
| rmhg2 |
null | 303Sequence of primes by trial division
| 11kotlin
| i19o4 |
package main
import (
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() { | 305Semordnilap
| 0go
| qjfxz |
require 'base64'
require 'net/smtp'
require 'tmail'
require 'mime/types'
class Email
def initialize(from, to, subject, body, options={})
@opts = {:attachments => [], :server => 'localhost'}.update(options)
@msg = TMail::Mail.new
@msg.from = from
@msg.to = to
@msg.subject = subject
@msg.cc = @opts[:cc] if @opts[:cc]
@msg.bcc = @opts[:bcc] if @opts[:bcc]
if @opts[:attachments].empty?
@msg.body = body
else
@msg.body =
msg_body = TMail::Mail.new
msg_body.body = body
msg_body.set_content_type(,, {:charset => })
@msg.parts << msg_body
octet_stream = MIME::Types['application/octet-stream'].first
@opts[:attachments].select {|file| File.readable?(file)}.each do |file|
mime_type = MIME::Types.type_for(file).first || octet_stream
@msg.parts << create_attachment(file, mime_type)
end
end
end
attr_reader :msg
def create_attachment(file, mime_type)
attach = TMail::Mail.new
if mime_type.binary?
attach.body = Base64.encode64(File.read(file))
attach.transfer_encoding = 'base64'
else
attach.body = File.read(file)
end
attach.set_disposition(, {:filename => file})
attach.set_content_type(mime_type.media_type, mime_type.sub_type, {:name=>file})
attach
end
def send
args = @opts.values_at(:server, :port, :helo, :username, :password, :authtype)
Net::SMTP.start(*args) do |smtp|
smtp.send_message(@msg.to_s, @msg.from[0], @msg.to)
end
end
def self.send(*args)
self.new(*args).send
end
end
Email.send(
'[email protected]',
%w{ [email protected] [email protected] },
'the subject',
,
{
:attachments => %w{ file1 file2 file3 },
:server => 'mail.example.com',
:helo => 'sender.invalid',
:username => 'user',
:password => 'secret'
}
) | 300Send email
| 14ruby
| navit |
null | 304Semiprime
| 11kotlin
| fwldo |
null | 308Self-describing numbers
| 11kotlin
| ld4cp |
inSC <- function(x, y) {
while(TRUE) {
if(!x||!y) {return(1)}
if(x%%3==1&&y%%3==1) {return(0)}
x=x%/%3; y=y%/%3;
} return(0);
}
pSierpinskiC <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="SCR"; dftt="Sierpinski carpet fractal";
n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord);
cat(" *** Plot file:", pf,".png", "title:", ttl, "\n");
for(i in 0:n) {
for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1}
}}
plotmat(M, pf, clr, ttl);
cat(" *** END", abbr, date(), "\n");
}
pSierpinskiC(5); | 283Sierpinski carpet
| 13r
| 0kasg |
def semordnilapWords(source) {
def words = [] as Set
def semordnilaps = []
source.eachLine { word ->
if (words.contains(word.reverse())) semordnilaps << word
words << word
}
semordnilaps
} | 305Semordnilap
| 7groovy
| 158p6 |
import java.util.Properties
import javax.mail.internet.{ InternetAddress, MimeMessage }
import javax.mail.Message.RecipientType
import javax.mail.{ Session, Transport }
class Mail(host: String) {
val session = Session.getDefaultInstance(new Properties() { put("mail.smtp.host", host) })
def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) {
val message = new MimeMessage(session)
message.setFrom(new InternetAddress(from))
for (to <- tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to))
for (cc <- ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc))
message.setSubject(subject)
message.setText(text)
Transport.send(message)
}
} | 300Send email
| 16scala
| zqgtr |
null | 303Sequence of primes by trial division
| 1lua
| naci8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.