code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 610Magic 8-ball
| 11kotlin
| p36b6 |
typedef unsigned uint;
typedef struct { uint i, v; } filt_t;
uint* ludic(uint min_len, uint min_val, uint *len)
{
uint cap, i, v, active = 1, nf = 0;
filt_t *f = calloc(cap = 2, sizeof(*f));
f[1].i = 4;
for (v = 1; ; ++v) {
for (i = 1; i < active && --f[i].i; i++);
if (i < active)
f[i].i = f[i].v;
else if (nf == f[i].i)
f[i].i = f[i].v, ++active;
else {
if (nf >= cap)
f = realloc(f, sizeof(*f) * (cap*=2));
f[nf] = (filt_t){ v + nf, v };
if (++nf >= min_len && v >= min_val) break;
}
}
uint *x = (void*) f;
for (i = 0; i < nf; i++) x[i] = f[i].v;
x = realloc(x, sizeof(*x) * nf);
*len = nf;
return x;
}
int find(uint *a, uint v)
{
uint i;
for (i = 0; a[i] <= v; i++)
if (v == a[i]) return 1;
return 0;
}
int main(void)
{
uint len, i, *x = ludic(2005, 1000, &len);
printf();
for (i = 0; i < 25; i++) printf(, x[i]);
putchar('\n');
for (i = 0; x[i] <= 1000; i++);
printf(, i);
printf();
for (i = 2000; i <= 2005; i++) printf(, x[i - 1]);
putchar('\n');
printf();
for (i = 0; x[i] + 6 <= 250; i++)
if (find(x, x[i] + 2) && find(x, x[i] + 6))
printf(, x[i], x[i] + 2, x[i] + 6);
putchar('\n');
free(x);
return 0;
} | 611Ludic numbers
| 5c
| 2xxlo |
math.randomseed(os.time())
answers = {
"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.",
"As I see it, yes.", "Most likely.", "Outlook good.", "Signs point to yes.", "Yes.",
"Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don't bet on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."
}
while true do
io.write("Q: ")
question = io.read()
print("A: "..answers[math.random(#answers)])
end | 610Magic 8-ball
| 1lua
| 16ypo |
import Foundation
import Numerics
import QDBMP
public typealias Color = (red: UInt8, green: UInt8, blue: UInt8)
public class BitmapDrawer {
public let imageHeight: Int
public let imageWidth: Int
var grid: [[Color?]]
private let bmp: OpaquePointer
public init(height: Int, width: Int) {
self.imageHeight = height
self.imageWidth = width
self.grid = [[Color?]](repeating: [Color?](repeating: nil, count: height), count: width)
self.bmp = BMP_Create(UInt(width), UInt(height), 24)
checkError()
}
deinit {
BMP_Free(bmp)
}
private func checkError() {
let err = BMP_GetError()
guard err == BMP_STATUS(0) else {
fatalError("\(err)")
}
}
public func save(to path: String = "~/Desktop/out.bmp") {
for x in 0..<imageWidth {
for y in 0..<imageHeight {
guard let color = grid[x][y] else { continue }
BMP_SetPixelRGB(bmp, UInt(x), UInt(y), color.red, color.green, color.blue)
checkError()
}
}
(path as NSString).expandingTildeInPath.withCString {s in
BMP_WriteFile(bmp, s)
}
}
public func setPixel(x: Int, y: Int, to color: Color?) {
grid[x][y] = color
}
}
let imageSize = 10_000
let canvas = BitmapDrawer(height: imageSize, width: imageSize)
let maxIterations = 256
let cxMin = -2.0
let cxMax = 1.0
let cyMin = -1.5
let cyMax = 1.5
let scaleX = (cxMax - cxMin) / Double(imageSize)
let scaleY = (cyMax - cyMin) / Double(imageSize)
for x in 0..<imageSize {
for y in 0..<imageSize {
let cx = cxMin + Double(x) * scaleX
let cy = cyMin + Double(y) * scaleY
let c = Complex(cx, cy)
var z = Complex(0.0, 0.0)
var i = 0
for t in 0..<maxIterations {
if z.magnitude > 2 {
break
}
z = z * z + c
i = t
}
canvas.setPixel(x: x, y: y, to: Color(red: UInt8(i), green: UInt8(i), blue: UInt8(i)))
}
}
canvas.save() | 607Mandelbrot set
| 17swift
| drknh |
(defn ints-from [n]
(cons n (lazy-seq (ints-from (inc n)))))
(defn drop-nth [n seq]
(cond
(zero? n) seq
(empty? seq) []
:else (concat (take (dec n) seq) (lazy-seq (drop-nth n (drop n seq))))))
(def ludic ((fn ludic
([] (ludic 1))
([n] (ludic n (ints-from (inc n))))
([n [f & r]] (cons n (lazy-seq (ludic f (drop-nth f r))))))))
(defn ludic? [n] (= (first (filter (partial <= n) ludic)) n))
(print "First 25: ")
(println (take 25 ludic))
(print "Count below 1000: ")
(println (count (take-while (partial > 1000) ludic)))
(print "2000th through 2005th: ")
(println (map (partial nth ludic) (range 1999 2005)))
(print "Triplets < 250: ")
(println (filter (partial every? ludic?)
(for [i (range 250)] (list i (+ i 2) (+ i 6))))) | 611Ludic numbers
| 6clojure
| goo4f |
(ns lychrel.core
(require [clojure.string :as s])
(require [clojure.set :as set-op])
(:gen-class))
(defn palindrome? "Returns true if given number is a palindrome (number on base 10)"
[number]
(let [number-str (str number)]
(= number-str (s/reverse number-str))))
(defn delete-leading-zeros
"Delete leading zeros so that you can read the string"
[number-str]
(read-string (re-find (re-pattern "[1-9]\\d*") number-str))
)
(defn lychrel "Returns T if number is a candidate Lychrel (up to max iterations), and a second value with the sequence of sums"
([number] (lychrel number 500))
([number depth]
(let [next-number (+' number (delete-leading-zeros (s/reverse (str number))))
depth (- depth 1)]
(if (palindrome? next-number) (conj [next-number] number)
(if (not= depth 0) (conj (lychrel next-number depth) number) (conj [] nil))
)
)))
(defn lychrel? "Test if number is a possible lychrel number"
[number]
(= nil (first (lychrel number 500))))
(defn lychrel-up-to-n "Get all lychrels up to N"
[N]
(filter lychrel? (range 1 N)))
(defn make-kin "Removes the starting number of the list, the starting number"
[kin]
(rest (butlast kin)))
(defn calc-seed "The seeding" []
(let [kin-set (atom #{})
seed-set (atom #{})]
(fn [n] (let [lychrel-seed (set #{(last n)})
kins (set (butlast n))]
(if (= kins (clojure.set/difference kins @kin-set))
(do (swap! kin-set clojure.set/union kins)
(swap! seed-set clojure.set/union lychrel-seed)
@kin-set))
@seed-set
))))
(defn filter-seeds "Filtering the seed through the paths"
[]
(let [calc-f (calc-seed)
all-lychrels (for [lychrel-list (filter lychrel? (range 1 10000))]
(filter (fn [x] (> 1000001 x)) (rest (lychrel lychrel-list))))]
(last (for [ll all-lychrels]
(do (calc-f ll))))))
(defn -main
"Here we do the three tasks:
Get all possible Lychrel numbers up to 10000
Count them
Reduce all possible numbers to seed"
[& args]
(let [lychrels-n (filter-seeds)
count-lychrels (count lychrels-n)
related-n (- (count (filter lychrel? (range 1 10000))) count-lychrels)
palindrom-n (filter palindrome? (filter lychrel? (range 1 10000)))
count-palindromes (count palindrom-n)
]
(println count-lychrels "Lychrel seeds:" lychrels-n)
(println related-n "Lychrel related.")
(println count-palindromes "Lychrel palindromes found:" palindrom-n))
) | 612Lychrel numbers
| 6clojure
| xc9wk |
@a = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
"Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful');
while () {
print 'Enter your question:';
last unless <> =~ /\w/;
print @a[int rand @a], "\n";
} | 610Magic 8-ball
| 2perl
| yp16u |
typedef struct {
char *data;
size_t alloc;
size_t length;
} dstr;
inline int dstr_space(dstr *s, size_t grow_amount)
{
return s->length + grow_amount < s->alloc;
}
int dstr_grow(dstr *s)
{
s->alloc *= 2;
char *attempt = realloc(s->data, s->alloc);
if (!attempt) return 0;
else s->data = attempt;
return 1;
}
dstr* dstr_init(const size_t to_allocate)
{
dstr *s = malloc(sizeof(dstr));
if (!s) goto failure;
s->length = 0;
s->alloc = to_allocate;
s->data = malloc(s->alloc);
if (!s->data) goto failure;
return s;
failure:
if (s->data) free(s->data);
if (s) free(s);
return NULL;
}
void dstr_delete(dstr *s)
{
if (s->data) free(s->data);
if (s) free(s);
}
dstr* readinput(FILE *fd)
{
static const size_t buffer_size = 4096;
char buffer[buffer_size];
dstr *s = dstr_init(buffer_size);
if (!s) goto failure;
while (fgets(buffer, buffer_size, fd)) {
while (!dstr_space(s, buffer_size))
if (!dstr_grow(s)) goto failure;
strncpy(s->data + s->length, buffer, buffer_size);
s->length += strlen(buffer);
}
return s;
failure:
dstr_delete(s);
return NULL;
}
void dstr_replace_all(dstr *story, const char *replace, const char *insert)
{
const size_t replace_l = strlen(replace);
const size_t insert_l = strlen(insert);
char *start = story->data;
while ((start = strstr(start, replace))) {
if (!dstr_space(story, insert_l - replace_l))
if (!dstr_grow(story)) err();
if (insert_l != replace_l) {
memmove(start + insert_l, start + replace_l, story->length -
(start + replace_l - story->data));
story->length += insert_l - replace_l;
story->data[story->length] = 0;
}
memmove(start, insert, insert_l);
}
}
void madlibs(dstr *story)
{
static const size_t buffer_size = 128;
char insert[buffer_size];
char replace[buffer_size];
char *start,
*end = story->data;
while (start = strchr(end, '<')) {
if (!(end = strchr(start, '>'))) err();
strncpy(replace, start, end - start + 1);
replace[end - start + 1] = '\0';
printf(, replace);
fgets(insert, buffer_size, stdin);
const size_t il = strlen(insert) - 1;
if (insert[il] == '\n')
insert[il] = '\0';
dstr_replace_all(story, replace, insert);
}
printf();
}
int main(int argc, char *argv[])
{
if (argc < 2) return 0;
FILE *fd = fopen(argv[1], );
if (!fd) err(, argv[1]);
dstr *story = readinput(fd); fclose(fd);
if (!story) err();
madlibs(story);
printf(, story->data);
dstr_delete(story);
return 0;
} | 613Mad Libs
| 5c
| w9yec |
<?php
$fortunes = array(
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
);
function cli_prompt( $prompt='> ', $default=false ) {
do {
echo $prompt;
$cmd = chop( fgets( STDIN ) );
} while ( empty( $default ) and empty( $cmd ) );
return $cmd?: $default;
}
$question = cli_prompt( 'What is your question? ' );
echo 'Q: ', $question, PHP_EOL;
echo 'A: ', $fortunes[ array_rand( $fortunes ) ], PHP_EOL; | 610Magic 8-ball
| 12php
| aym12 |
int luckyOdd[LUCKY_SIZE];
int luckyEven[LUCKY_SIZE];
void compactLucky(int luckyArray[]) {
int i, j, k;
for (i = 0; i < LUCKY_SIZE; i++) {
if (luckyArray[i] == 0) {
j = i;
break;
}
}
for (j = i + 1; j < LUCKY_SIZE; j++) {
if (luckyArray[j] > 0) {
luckyArray[i++] = luckyArray[j];
}
}
for (; i < LUCKY_SIZE; i++) {
luckyArray[i] = 0;
}
}
void initialize() {
int i, j;
for (i = 0; i < LUCKY_SIZE; i++) {
luckyEven[i] = 2 * i + 2;
luckyOdd[i] = 2 * i + 1;
}
for (i = 1; i < LUCKY_SIZE; i++) {
if (luckyOdd[i] > 0) {
for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {
luckyOdd[j] = 0;
}
compactLucky(luckyOdd);
}
}
for (i = 1; i < LUCKY_SIZE; i++) {
if (luckyEven[i] > 0) {
for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {
luckyEven[j] = 0;
}
compactLucky(luckyEven);
}
}
}
void printBetween(size_t j, size_t k, bool even) {
int i;
if (even) {
if (luckyEven[j] == 0 || luckyEven[k] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, k);
for (i = 0; luckyEven[i] != 0; i++) {
if (luckyEven[i] > k) {
break;
}
if (luckyEven[i] > j) {
printf(, luckyEven[i]);
}
}
} else {
if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, k);
for (i = 0; luckyOdd[i] != 0; i++) {
if (luckyOdd[i] > k) {
break;
}
if (luckyOdd[i] > j) {
printf(, luckyOdd[i]);
}
}
}
printf();
}
void printRange(size_t j, size_t k, bool even) {
int i;
if (even) {
if (luckyEven[k] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, k);
for (i = j - 1; i < k; i++) {
printf(, luckyEven[i]);
}
} else {
if (luckyOdd[k] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, k);
for (i = j - 1; i < k; i++) {
printf(, luckyOdd[i]);
}
}
printf();
}
void printSingle(size_t j, bool even) {
if (even) {
if (luckyEven[j] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, luckyEven[j - 1]);
} else {
if (luckyOdd[j] == 0) {
fprintf(stderr, );
exit(EXIT_FAILURE);
}
printf(, j, luckyOdd[j - 1]);
}
}
void help() {
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
printf();
}
void process(int argc, char *argv[]) {
bool evenLucky = false;
int j = 0;
int k = 0;
bool good = false;
int i;
for (i = 1; i < argc; ++i) {
if ('-' == argv[i][0]) {
if ('-' == argv[i][1]) {
if (0 == strcmp(, argv[i])) {
evenLucky = false;
} else if (0 == strcmp(, argv[i])) {
evenLucky = true;
} else {
fprintf(stderr, , argv[i]);
exit(EXIT_FAILURE);
}
} else {
if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {
good = true;
j = atoi(&argv[i][3]);
} else if ('k' == argv[i][1] && '=' == argv[i][2]) {
k = atoi(&argv[i][3]);
} else {
fprintf(stderr, , argv[i]);
exit(EXIT_FAILURE);
}
}
} else {
fprintf(stderr, , argv[i]);
exit(EXIT_FAILURE);
}
}
if (!good) {
help();
exit(EXIT_FAILURE);
}
if (k > 0) {
printRange(j, k, evenLucky);
} else if (k < 0) {
printBetween(j, -k, evenLucky);
} else {
printSingle(j, evenLucky);
}
}
void test() {
printRange(1, 20, false);
printRange(1, 20, true);
printBetween(6000, 6100, false);
printBetween(6000, 6100, true);
printSingle(10000, false);
printSingle(10000, true);
}
int main(int argc, char *argv[]) {
initialize();
if (argc < 2) {
help();
return 1;
}
process(argc, argv);
return 0;
} | 614Lucky and even lucky numbers
| 5c
| cep9c |
(ns magic.rosetta
(:require [clojure.string:as str]))
(defn mad-libs
"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story,
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name,
a he or she and a noun (<name> gets replaced both times with the same value). "
[]
(let
[story (do
(println "Please enter story:")
(loop [story []]
(let [line (read-line)]
(if (empty? line)
(str/join "\n" story)
(recur (conj story line))))))
tokens (set (re-seq #"<[^<>]+>" story))
story-completed (reduce
(fn [s t]
(str/replace s t (do
(println (str "Substitute " t ":"))
(read-line))))
story
tokens)]
(println (str
"Here is your story:\n"
"------------------------------------\n"
story-completed)))) | 613Mad Libs
| 6clojure
| 8u205 |
import random
s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
, 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful')
q_and_a = {}
while True:
question = input('Ask your question:')
if len(question) == 0: break
if question in q_and_a:
print('Your question has already been answered')
else:
answer = random.choice(s)
q_and_a[question] = answer
print(answer) | 610Magic 8-ball
| 3python
| m1ayh |
eight_ball <- function()
{
responses <- c("It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful")
question <- ""
cat("Welcome to 8 ball!\n\n", "Please ask yes/no questions to get answers.",
" Type 'quit' to exit the program\n\n")
while(TRUE)
{
question <- readline(prompt="Enter Question: ")
if(question == 'quit')
{
break
}
randint <- runif(1, 1, 20)
cat("Response: ", responses[randint], "\n")
}
}
if(!interactive())
{
eight_ball()
} | 610Magic 8-ball
| 13r
| zhkth |
typedef double **mat;
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }
mat mat_new(_dim)
{
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);
for_i x[i] = x[0] + n * i;
_zero(x);
return x;
}
mat mat_copy(void *s, _dim)
{
mat x = mat_new(n);
for_ij x[i][j] = ((double (*)[n])s)[i][j];
return x;
}
void mat_del(mat x) { free(x[0]); free(x); }
void mat_show(mat x, char *fmt, _dim)
{
if (!fmt) fmt = ;
for_i {
printf(i ? : );
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? : i == n - 1 ? : );
}
}
}
mat mat_mul(mat a, mat b, _dim)
{
mat c = _new(c);
for_ijk c[i][j] += a[i][k] * b[k][j];
return c;
}
void mat_pivot(mat a, mat p, _dim)
{
for_ij { p[i][j] = (i == j); }
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;
if (max_j != i)
for_k { _swap(p[i][k], p[max_j][k]); }
}
}
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
_zero(L); _zero(U);
_pivot(A, P);
mat Aprime = _mul(P, A);
for_i { L[i][i] = 1; }
for_ij {
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}
_del(Aprime);
}
double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
int main()
{
int n = 3;
mat A, L, P, U;
_new(L); _new(P); _new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
printf();
n = 4;
_new(L); _new(P); _new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
return 0;
} | 615LU decomposition
| 5c
| lwpcy |
package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10) | 612Lychrel numbers
| 0go
| 6bk3p |
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
const luckySize = 60000
var luckyOdd = make([]int, luckySize)
var luckyEven = make([]int, luckySize)
func init() {
for i := 0; i < luckySize; i++ {
luckyOdd[i] = i*2 + 1
luckyEven[i] = i*2 + 2
}
}
func filterLuckyOdd() {
for n := 2; n < len(luckyOdd); n++ {
m := luckyOdd[n-1]
end := (len(luckyOdd)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyOdd[j:], luckyOdd[j+1:])
luckyOdd = luckyOdd[:len(luckyOdd)-1]
}
}
}
func filterLuckyEven() {
for n := 2; n < len(luckyEven); n++ {
m := luckyEven[n-1]
end := (len(luckyEven)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyEven[j:], luckyEven[j+1:])
luckyEven = luckyEven[:len(luckyEven)-1]
}
}
}
func printSingle(j int, odd bool) error {
if odd {
if j >= len(luckyOdd) {
return fmt.Errorf("the argument,%d, is too big", j)
}
fmt.Println("Lucky number", j, "=", luckyOdd[j-1])
} else {
if j >= len(luckyEven) {
return fmt.Errorf("the argument,%d, is too big", j)
}
fmt.Println("Lucky even number", j, "=", luckyEven[j-1])
}
return nil
}
func printRange(j, k int, odd bool) error {
if odd {
if k >= len(luckyOdd) {
return fmt.Errorf("the argument,%d, is too big", k)
}
fmt.Println("Lucky numbers", j, "to", k, "are:")
fmt.Println(luckyOdd[j-1 : k])
} else {
if k >= len(luckyEven) {
return fmt.Errorf("the argument,%d, is too big", k)
}
fmt.Println("Lucky even numbers", j, "to", k, "are:")
fmt.Println(luckyEven[j-1 : k])
}
return nil
}
func printBetween(j, k int, odd bool) error {
var r []int
if odd {
max := luckyOdd[len(luckyOdd)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument,%d or%d, is too big", j, k)
}
for _, num := range luckyOdd {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky numbers between", j, "and", k, "are:")
fmt.Println(r)
} else {
max := luckyEven[len(luckyEven)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument,%d or%d, is too big", j, k)
}
for _, num := range luckyEven {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky even numbers between", j, "and", k, "are:")
fmt.Println(r)
}
return nil
}
func main() {
nargs := len(os.Args)
if nargs < 2 || nargs > 4 {
log.Fatal("there must be between 1 and 3 command line arguments")
}
filterLuckyOdd()
filterLuckyEven()
j, err := strconv.Atoi(os.Args[1])
if err != nil || j < 1 {
log.Fatalf("first argument,%s, must be a positive integer", os.Args[1])
}
if nargs == 2 {
if err := printSingle(j, true); err != nil {
log.Fatal(err)
}
return
}
if nargs == 3 {
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatalf("second argument,%s, must be an integer", os.Args[2])
}
if k >= 0 {
if j > k {
log.Fatalf("second argument,%d, can't be less than first,%d", k, j)
}
if err := printRange(j, k, true); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument,%d, can't be less in absolute value than first,%d", k, j)
}
if err := printBetween(j, l, true); err != nil {
log.Fatal(err)
}
}
return
}
var odd bool
switch lucky := strings.ToLower(os.Args[3]); lucky {
case "lucky":
odd = true
case "evenlucky":
odd = false
default:
log.Fatalf("third argument,%s, is invalid", os.Args[3])
}
if os.Args[2] == "," {
if err := printSingle(j, odd); err != nil {
log.Fatal(err)
}
return
}
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatal("second argument must be an integer or a comma")
}
if k >= 0 {
if j > k {
log.Fatalf("second argument,%d, can't be less than first,%d", k, j)
}
if err := printRange(j, k, odd); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument,%d, can't be less in absolute value than first,%d", k, j)
}
if err := printBetween(j, l, odd); err != nil {
log.Fatal(err)
}
}
} | 614Lucky and even lucky numbers
| 0go
| w96eg |
void* mem_alloc(size_t item_size, size_t n_item)
{
size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
x[0] = item_size;
x[1] = n_item;
return x + 2;
}
void* mem_extend(void *m, size_t new_n)
{
size_t *x = (size_t*)m - 2;
x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
if (new_n > x[1])
memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
x[1] = new_n;
return x + 2;
}
inline void _clear(void *m)
{
size_t *x = (size_t*)m - 2;
memset(m, 0, x[0] * x[1]);
}
typedef uint8_t byte;
typedef uint16_t ushort;
typedef struct {
ushort next[256];
} lzw_enc_t;
typedef struct {
ushort prev, back;
byte c;
} lzw_dec_t;
byte* lzw_encode(byte *in, int max_bits)
{
int len = _len(in), bits = 9, next_shift = 512;
ushort code, c, nc, next_code = M_NEW;
lzw_enc_t *d = _new(lzw_enc_t, 512);
if (max_bits > 15) max_bits = 15;
if (max_bits < 9 ) max_bits = 12;
byte *out = _new(ushort, 4);
int out_len = 0, o_bits = 0;
uint32_t tmp = 0;
inline void write_bits(ushort x) {
tmp = (tmp << bits) | x;
o_bits += bits;
if (_len(out) <= out_len) _extend(out);
while (o_bits >= 8) {
o_bits -= 8;
out[out_len++] = tmp >> o_bits;
tmp &= (1 << o_bits) - 1;
}
}
for (code = *(in++); --len; ) {
c = *(in++);
if ((nc = d[code].next[c]))
code = nc;
else {
write_bits(code);
nc = d[code].next[c] = next_code++;
code = c;
}
if (next_code == next_shift) {
if (++bits > max_bits) {
write_bits(M_CLR);
bits = 9;
next_shift = 512;
next_code = M_NEW;
_clear(d);
} else
_setsize(d, next_shift *= 2);
}
}
write_bits(code);
write_bits(M_EOD);
if (tmp) write_bits(tmp);
_del(d);
_setsize(out, out_len);
return out;
}
byte* lzw_decode(byte *in)
{
byte *out = _new(byte, 4);
int out_len = 0;
inline void write_out(byte c)
{
while (out_len >= _len(out)) _extend(out);
out[out_len++] = c;
}
lzw_dec_t *d = _new(lzw_dec_t, 512);
int len, j, next_shift = 512, bits = 9, n_bits = 0;
ushort code, c, t, next_code = M_NEW;
uint32_t tmp = 0;
inline void get_code() {
while(n_bits < bits) {
if (len > 0) {
len --;
tmp = (tmp << 8) | *(in++);
n_bits += 8;
} else {
tmp = tmp << (bits - n_bits);
n_bits = bits;
}
}
n_bits -= bits;
code = tmp >> n_bits;
tmp &= (1 << n_bits) - 1;
}
inline void clear_table() {
_clear(d);
for (j = 0; j < 256; j++) d[j].c = j;
next_code = M_NEW;
next_shift = 512;
bits = 9;
};
clear_table();
for (len = _len(in); len;) {
get_code();
if (code == M_EOD) break;
if (code == M_CLR) {
clear_table();
continue;
}
if (code >= next_code) {
fprintf(stderr, );
_del(out);
goto bail;
}
d[next_code].prev = c = code;
while (c > 255) {
t = d[c].prev; d[t].back = c; c = t;
}
d[next_code - 1].c = c;
while (d[c].back) {
write_out(d[c].c);
t = d[c].back; d[c].back = 0; c = t;
}
write_out(d[c].c);
if (++next_code >= next_shift) {
if (++bits > 16) {
fprintf(stderr, );
_del(out);
goto bail;
}
_setsize(d, next_shift *= 2);
}
}
if (code != M_EOD) fputs(, stderr);
_setsize(out, out_len);
bail: _del(d);
return out;
}
int main()
{
int i, fd = open(, O_RDONLY);
if (fd == -1) {
fprintf(stderr, );
return 1;
};
struct stat st;
fstat(fd, &st);
byte *in = _new(char, st.st_size);
read(fd, in, st.st_size);
_setsize(in, st.st_size);
close(fd);
printf(, _len(in));
byte *enc = lzw_encode(in, 9);
printf(, _len(enc));
byte *dec = lzw_decode(enc);
printf(, _len(dec));
for (i = 0; i < _len(dec); i++)
if (dec[i] != in[i]) {
printf(, i);
break;
}
if (i == _len(dec)) printf();
_del(in);
_del(enc);
_del(dec);
return 0;
} | 616LZW compression
| 5c
| zh4tx |
module Main where
import Data.List
procLychrel :: Integer -> [Integer]
procLychrel a = a: pl a
where
pl n =
let s = n + reverseInteger n
in if isPalindrome s
then [s]
else s: pl s
isPalindrome :: Integer -> Bool
isPalindrome n =
let s = show n
in (s == reverse s)
isLychrel :: Integer -> Bool
isLychrel = not . null . drop 500 . procLychrel
reverseInteger :: Integer -> Integer
reverseInteger = read . reverse . show
seedAndRelated :: (Int, [Integer], [Integer], Int)
seedAndRelated =
let (seed, related, _) = foldl sar ([], [], []) [1 .. 10000]
lseed = length seed
lrelated = length related
totalCount = lseed + lrelated
pal = filter isPalindrome $ seed ++ related
in (totalCount, pal, seed, lrelated)
where
sar (seed, related, lych) x =
let s = procLychrel x
sIsLychrel = not . null . drop 500 $ s
(isIn, isOut) = partition (`elem` lych) . take 501 $ s
newLych = lych ++ isOut
in if sIsLychrel
then if null isIn
then (x: seed, related, newLych)
else (seed, x: related, newLych)
else (seed, related, lych)
main = do
let (totalCount, palindromicLychrel, lychrelSeeds, relatedCount) = seedAndRelated
putStrLn $ "[1..10,000] contains " ++ show totalCount ++ " Lychrel numbers."
putStrLn $ show palindromicLychrel ++ " are palindromic Lychrel numbers."
putStrLn $ show lychrelSeeds ++ " are Lychrel seeds."
putStrLn $ "There are " ++ show relatedCount ++ " related Lychrel numbers." | 612Lychrel numbers
| 8haskell
| jdn7g |
package main
import "fmt" | 611Ludic numbers
| 0go
| qllxz |
import System.Environment
import Text.Regex.Posix
data Lucky = Lucky | EvenLucky
helpMessage :: IO ()
helpMessage = do
putStrLn " what is displayed (on a single line)"
putStrLn " argument(s) (optional verbiage is encouraged)"
putStrLn "======================|==================================================="
putStrLn " j | Jth lucky number "
putStrLn " j , lucky | Jth lucky number "
putStrLn " j , evenLucky | Jth even lucky number "
putStrLn " "
putStrLn " j k | Jth through Kth (inclusive) lucky numbers "
putStrLn " j k lucky | Jth through Kth (inclusive) lucky numbers "
putStrLn " j k evenlucky | Jth through Kth (inclusive) even lucky numbers "
putStrLn " "
putStrLn " j -k | all lucky numbers in the range j -> |k| "
putStrLn " j -k lucky | all lucky numbers in the range j -> |k| "
putStrLn " j -k evenlucky | all even lucky numbers in the range j -> |k| "
putStrLn "======================|==================================================="
oddNumbers :: [Int]
oddNumbers = filter odd [1..]
evenNumbers :: [Int]
evenNumbers = filter even [1..]
luckyNumbers :: [Int] -> [Int]
luckyNumbers xs =
let i = 3 in
sieve i xs
where
sieve i (ln:s:xs) =
ln: sieve (i + 1) (s: [x | (n, x) <- zip [i..] xs, rem n s /= 0])
nth :: Int -> Lucky -> Int
nth j Lucky = luckyNumbers oddNumbers !! (j-1)
nth j EvenLucky = luckyNumbers evenNumbers !! (j-1)
range :: Int -> Int -> Lucky -> [Int]
range x x2 Lucky = drop (x-1) (take x2 (luckyNumbers oddNumbers))
range x x2 EvenLucky = drop (x-1) (take x2 (luckyNumbers evenNumbers))
interval :: Int -> Int -> Lucky -> [Int]
interval x x2 Lucky = dropWhile (<x) (takeWhile (<=x2) (luckyNumbers oddNumbers))
interval x x2 EvenLucky = dropWhile (<x) (takeWhile (<=x2) (luckyNumbers evenNumbers))
lucky :: [String] -> Lucky
lucky xs =
if "evenLucky" `elem` xs
then EvenLucky
else Lucky
readn :: String -> Int
readn s = read s :: Int
isInt :: String -> Bool
isInt s = not (null (s =~ "-?[0-9]{0,10}" :: String))
main :: IO ()
main = do
args <- getArgs
if head args == "
then
helpMessage
else
let l = lucky args in
case map readn (filter isInt args) of
[] -> do
putStrLn "Invalid input, missing arguments"
putStrLn "Type
[x] -> print (nth x l)
[x, x2] -> if x2 > 0
then print (range x x2 l)
else print (interval x (-x2) l)
_ -> do
putStrLn "Invalid input, wrong number of arguments"
putStrLn "Type | 614Lucky and even lucky numbers
| 8haskell
| 6bj3k |
class EightBall
def initialize
print
puts
@responses = [, ,
, ,
, ,
, ,
, ,
, ,
,
,
, ,
, ,
, ]
end
def ask_question
print
question = gets
if question.chomp.eql?
exit(0)
end
puts
end
def run
loop do
ask_question
end
end
end
eight_ball = EightBall.new
eight_ball.run | 610Magic 8-ball
| 14ruby
| cew9k |
extern crate rand;
use rand::prelude::*;
use std::io;
fn main() {
let answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Signs point to yes",
"Yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't bet on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
];
let mut rng = rand::thread_rng();
let mut input_line = String::new();
println!("Please enter your question or a blank line to quit.\n");
loop {
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if input_line.trim() == "" {
break;
}
println!("{}\n", answers.choose(&mut rng).unwrap());
input_line.clear();
}
} | 610Magic 8-ball
| 15rust
| lwxcc |
import Data.List (unfoldr, genericSplitAt)
ludic :: [Integer]
ludic = 1: unfoldr (\xs@(x:_) -> Just (x, dropEvery x xs)) [2 ..]
where
dropEvery n = concatMap tail . unfoldr (Just . genericSplitAt n)
main :: IO ()
main = do
print $ take 25 ludic
(print . length) $ takeWhile (<= 1000) ludic
print $ take 6 $ drop 1999 ludic | 611Ludic numbers
| 8haskell
| m11yf |
typedef int bool;
typedef struct {
int start, stop, incr;
const char *comment;
} S;
S examples[9] = {
{-2, 2, 1, },
{-2, 2, 0, },
{-2, 2, -1, },
{-2, 2, 10, },
{2, -2, 1, },
{2, 2, 1, },
{2, 2, -1, },
{2, 2, 0, },
{0, 0, 0, }
};
int main() {
int i, j, c;
bool empty;
S s;
const int limit = 10;
for (i = 0; i < 9; ++i) {
s = examples[i];
printf(, s.comment);
printf(, s.start, s.stop, s.incr);
empty = TRUE;
for (j = s.start, c = 0; j <= s.stop && c < limit; j += s.incr, ++c) {
printf(, j);
empty = FALSE;
}
if (!empty) printf();
printf();
}
return 0;
} | 617Loops/Wrong ranges
| 5c
| 6bg32 |
import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds:%s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes:%s%n", palin.size(), palin);
}
} | 612Lychrel numbers
| 9java
| usqvv |
import scala.util.Random
object Magic8Ball extends App {
val shake: () => String = {
val answers = List(
"It is certain.", "It is decidedly so.", "Without a doubt.",
"Yes definitely.", "You may rely on it.", "As I see it, yes.",
"Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later", "Better not tell you now.",
"Cannot predict now.", "Concentrate and ask again.", "Don't count on it.",
"My reply is no.", "My sources say no.", "Outlook not so good.",
"Very doubtful."
)
val r = new Random
() => answers(r.nextInt(answers.length))
}
println("Ask the Magic 8-Ball your questions. ('q' or 'quit' to quit)\n")
while (true) {
io.StdIn.readLine("Question: ").toLowerCase match {
case "q" | "quit" =>
println("Goodbye.")
sys.exit()
case _ =>
println(s"Response: ${shake()}\n")
}
}
} | 610Magic 8-ball
| 16scala
| us0v8 |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LuckyNumbers {
private static int MAX = 200000;
private static List<Integer> luckyEven = luckyNumbers(MAX, true);
private static List<Integer> luckyOdd = luckyNumbers(MAX, false);
public static void main(String[] args) { | 614Lucky and even lucky numbers
| 9java
| nguih |
(defn make-dict []
(let [vals (range 0 256)]
(zipmap (map (comp #'list #'char) vals) vals)))
(defn compress [#^String text]
(loop [t (seq text)
r '()
w '()
dict (make-dict)
s 256]
(let [c (first t)]
(if c
(let [wc (cons c w)]
(if (get dict wc)
(recur (rest t) r wc dict s)
(recur (rest t) (cons (get dict w) r) (list c) (assoc dict wc s) (inc s))))
(reverse (if w (cons (get dict w) r) r))))))
(compress "TOBEORNOTTOBEORTOBEORNOT") | 616LZW compression
| 6clojure
| 9ahma |
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func main() {
pat := regexp.MustCompile("<.+?>")
if len(os.Args) != 2 {
fmt.Println("usage: madlib <story template file>")
return
}
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
tmpl := string(b)
s := []string{} | 613Mad Libs
| 0go
| ce19g |
function luckyNumbers(opts={}) {
opts.even = opts.even || false;
if (typeof opts.through == 'number') opts.through = [0, opts.through];
let out = [],
x = opts.even ? 2 : 1,
max = opts.range ? opts.range[1] * 3
: opts.through ? opts.through[1] * 12
: opts.nth ? opts.nth * 15
: 2000;
for (x; x <= max; x = x+2) out.push(x); | 614Lucky and even lucky numbers
| 10javascript
| 3k7z0 |
import System.IO (stdout, hFlush)
import System.Environment (getArgs)
import qualified Data.Map as M (Map, lookup, insert, empty)
getLines :: IO [String]
getLines = reverse <$> getLines_ []
where
getLines_ xs = do
line <- getLine
case line of
[] -> return xs
_ -> getLines_ $ line: xs
prompt :: String -> IO String
prompt p = putStr p >> hFlush stdout >> getLine
getKeyword :: String -> Maybe String
getKeyword ('<':xs) = getKeyword_ xs []
where
getKeyword_ [] _ = Nothing
getKeyword_ (x:'>':_) acc = Just $ '<': reverse ('>': x: acc)
getKeyword_ (x:xs) acc = getKeyword_ xs $ x: acc
getKeyword _ = Nothing
parseText :: String -> M.Map String String -> IO String
parseText [] _ = return []
parseText line@(l:lx) keywords =
case getKeyword line of
Nothing -> (l:) <$> parseText lx keywords
Just keyword -> do
let rest = drop (length keyword) line
case M.lookup keyword keywords of
Nothing -> do
newword <- prompt $ "Enter a word for " ++ keyword ++ ": "
rest_ <- parseText rest $ M.insert keyword newword keywords
return $ newword ++ rest_
Just knownword -> do
rest_ <- parseText rest keywords
return $ knownword ++ rest_
main :: IO ()
main = do
args <- getArgs
nlines <-
case args of
[] -> unlines <$> getLines
arg:_ -> readFile arg
nlines_ <- parseText nlines M.empty
putStrLn ""
putStrLn nlines_ | 613Mad Libs
| 8haskell
| p3tbt |
import java.util.ArrayList;
import java.util.List;
public class Ludic{
public static List<Integer> ludicUpTo(int n){
List<Integer> ludics = new ArrayList<Integer>(n);
for(int i = 1; i <= n; i++){ | 611Ludic numbers
| 9java
| f77dv |
null | 614Lucky and even lucky numbers
| 11kotlin
| s29q7 |
package main
import "fmt"
type matrix [][]float64
func zero(n int) matrix {
r := make([][]float64, n)
a := make([]float64, n*n)
for i := range r {
r[i] = a[n*i : n*(i+1)]
}
return r
}
func eye(n int) matrix {
r := zero(n)
for i := range r {
r[i][i] = 1
}
return r
}
func (m matrix) print(label string) {
if label > "" {
fmt.Printf("%s:\n", label)
}
for _, r := range m {
for _, e := range r {
fmt.Printf("%9.5f", e)
}
fmt.Println()
}
}
func (a matrix) pivotize() matrix {
p := eye(len(a))
for j, r := range a {
max := r[j]
row := j
for i := j; i < len(a); i++ {
if a[i][j] > max {
max = a[i][j]
row = i
}
}
if j != row { | 615LU decomposition
| 0go
| xc6wf |
null | 612Lychrel numbers
| 11kotlin
| 9a1mh |
const makeArr = (s, e) => new Array(e + 1 - s).fill(s).map((e, i) => e + i);
const filterAtInc = (arr, n) => arr.filter((e, i) => (i + 1) % n);
const makeLudic = (arr, result) => {
const iter = arr.shift();
result.push(iter);
return arr.length ? makeLudic(filterAtInc(arr, iter), result) : result;
};
const ludicResult = makeLudic(makeArr(2, 21512), [1]); | 611Ludic numbers
| 10javascript
| ypp6r |
int lucas_lehmer(unsigned long p)
{
mpz_t V, mp, t;
unsigned long k, tlim;
int res;
if (p == 2) return 1;
if (!(p&1)) return 0;
mpz_init_set_ui(t, p);
if (!mpz_probab_prime_p(t, 25))
{ mpz_clear(t); return 0; }
if (p < 23)
{ mpz_clear(t); return (p != 11); }
mpz_init(mp);
mpz_setbit(mp, p);
mpz_sub_ui(mp, mp, 1);
if (p > 3 && p % 4 == 3) {
mpz_mul_ui(t, t, 2);
mpz_add_ui(t, t, 1);
if (mpz_probab_prime_p(t,25) && mpz_divisible_p(mp, t))
{ mpz_clear(mp); mpz_clear(t); return 0; }
}
tlim = p/2;
if (tlim > (ULONG_MAX/(2*p)))
tlim = ULONG_MAX/(2*p);
for (k = 1; k < tlim; k++) {
unsigned long q = 2*p*k+1;
if ( (q%8==1 || q%8==7) &&
q % 3 && q % 5 && q % 7 &&
mpz_divisible_ui_p(mp, q) )
{ mpz_clear(mp); mpz_clear(t); return 0; }
}
mpz_init_set_ui(V, 4);
for (k = 3; k <= p; k++) {
mpz_mul(V, V, V);
mpz_sub_ui(V, V, 2);
if (mpz_sgn(V) < 0) mpz_add(V, V, mp);
mpz_tdiv_r_2exp(t, V, p);
mpz_tdiv_q_2exp(V, V, p);
mpz_add(V, V, t);
while (mpz_cmp(V, mp) >= 0) mpz_sub(V, V, mp);
}
res = !mpz_sgn(V);
mpz_clear(t); mpz_clear(mp); mpz_clear(V);
return res;
}
int main(int argc, char* argv[]) {
unsigned long i, n = 43112609;
if (argc >= 2) n = strtoul(argv[1], 0, 10);
for (i = 1; i <= n; i++) {
if (lucas_lehmer(i)) {
printf(, i);
fflush(stdout);
}
}
printf();
return 0;
} | 618Lucas-Lehmer test
| 5c
| lwhcy |
import Data.List
import Data.Maybe
import Text.Printf
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult a b = [ [ sum $ zipWith (*) ak bj | ak <- (transpose a) ] | bj <- b ]
nth mA i j = (mA !! j) !! i
idMatrixPart n m k = [ [if (i==j) then 1 else 0 | i <- [1..n]] | j <- [k..m]]
idMatrix n = idMatrixPart n n 1
permMatrix n ix1 ix2 =
[ [ if ((i==ix1 && j==ix2) || (i==ix2 && j==ix1) || (i==j && j /= ix1 && i /= ix2))
then 1 else 0| i <- [0..n-1]] | j <- [0..n-1]]
permMatrix_inv n ix1 ix2 = permMatrix n ix2 ix1
elimColumn :: Int -> [[Rational]] -> Int -> [Rational]
elimMatrix :: Int -> [[Rational]] -> Int -> [[Rational]]
elimMatrix_inv :: Int -> [[Rational]] -> Int -> [[Rational]]
elimColumn n mA k = [(let mAkk = (nth mA k k) in if (i>k) then (-(nth mA i k)/mAkk)
else if (i==k) then 1 else 0) | i <- [0..n-1]]
elimMatrix n mA k = (idMatrixPart n k 1) ++ [elimColumn n mA k] ++ (idMatrixPart n n (k+2))
elimMatrix_inv n mA k = (idMatrixPart n k 1) ++
[let c = (mA!!k) in [if (i==k) then 1 else if (i<k) then 0 else (-(c!!i)) | i <- [0..n-1]]]
++ (idMatrixPart n n (k+2))
swapIndx :: [[Rational]] -> Int -> Int
swapIndx mA k = fromMaybe k (findIndex (>0) (drop k (mA!!k)))
paStep_recP :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
paStep_recM :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
lupStep :: Int -> [[Rational]] -> [[[Rational]]]
paStep_recP n mP mA mL cnt =
let mPt = permMatrix n cnt (swapIndx mA cnt) in
let mPtInv = permMatrix_inv n cnt (swapIndx mA cnt) in
if (cnt >= n) then [(mmult mP mL),mA,mP] else
(paStep_recM n (mmult mPt mP) (mmult mPt mA) (mmult mL mPtInv) cnt)
paStep_recM n mP mA mL cnt =
let mMt = elimMatrix n mA cnt in
let mMtInv = elimMatrix_inv n mMt cnt in
paStep_recP n mP (mmult mMt mA) (mmult mL mMtInv) (cnt + 1)
lupStep n mA = paStep_recP n (idMatrix n) mA (idMatrix n) 0
matrixFromRationalToString m = concat $ intersperse "\n"
(map (\x -> unwords $ printf "%8.4f" <$> (x::[Double]))
(transpose (matrixFromRational m))) where
matrixFromRational m = map (\x -> map fromRational x) m
solveTask mY = let mLUP = lupStep (length mY) mY in
putStrLn ("A: \n" ++ matrixFromRationalToString mY) >>
putStrLn ("L: \n" ++ matrixFromRationalToString (mLUP!!0)) >>
putStrLn ("U: \n" ++ matrixFromRationalToString (mLUP!!1)) >>
putStrLn ("P: \n" ++ matrixFromRationalToString (mLUP!!2)) >>
putStrLn ("Verify: PA\n" ++ matrixFromRationalToString (mmult (mLUP!!2) mY)) >>
putStrLn ("Verify: LU\n" ++ matrixFromRationalToString (mmult (mLUP!!0) (mLUP!!1)))
mY1 = [[1, 2, 1], [3, 4, 7], [5, 7, 0]] :: [[Rational]]
mY2 = [[11, 1, 3, 2], [9, 5, 17, 5], [24, 2, 18, 7], [2, 6, 1, 1]] :: [[Rational]]
main = putStrLn "Task1: \n" >> solveTask mY1 >>
putStrLn "Task2: \n" >> solveTask mY2 | 615LU decomposition
| 8haskell
| ypj66 |
use Perl6::GatherTake;
sub luck {
my($a,$b) = @_;
gather {
my $i = $b;
my(@taken,@rotor,$j);
take 0;
push @taken, take $a;
while () {
for ($j = 0; $j < @rotor; $j++) {
--$rotor[$j] or last;
}
if ($j < @rotor) {
$rotor[$j] = $taken[$j+1];
}
else {
take $i;
push @taken, $i;
push @rotor, $i - @taken;
}
$i += 2;
}
}
}
$j = shift || usage();
$k = shift || ',';
$l = shift || 'lucky';
usage() unless $k =~ /,|-?\d+/;
usage() unless $l =~ /^(even)?lucky$/i;
sub usage { print "Args must be: j [,|k|-k] [lucky|evenlucky]\n" and exit }
my $lucky = $l =~ /^l/i ? luck(1,3) : luck(2,4);
if ($k eq ',') {
print $lucky->[$j]
} elsif ($k > $j) {
print $lucky->[$_] . ' ' for $j..$k
} elsif ($k < 0) {
while () { last if abs($k) < $lucky->[$i++] }
print join ' ', grep { $_ >= $j and $_ <= abs($k) } @$lucky
}
print "\n" | 614Lucky and even lucky numbers
| 2perl
| uswvr |
import java.util.*;
public class MadLibs {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String name, gender, noun;
System.out.print("Enter a name: ");
name = input.next();
System.out.print("He or she: ");
gender = input.next();
System.out.print("Enter a noun: ");
noun = input.next();
System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
}
} | 613Mad Libs
| 9java
| ri8g0 |
long prod = 1L, sum = 0L;
void process(int j) {
sum += abs(j);
if (labs(prod) < (1 << 27) && j) prod *= j;
}
long ipow(int n, uint e) {
long pr = n;
int i;
if (e == 0) return 1L;
for (i = 2; i <= e; ++i) pr *= n;
return pr;
}
int main() {
int j;
const int x = 5, y = -5, z = -2;
const int one = 1, three = 3, seven = 7;
long p = ipow(11, x);
for (j = -three; j <= ipow(3, 3); j += three) process(j);
for (j = -seven; j <= seven; j += x) process(j);
for (j = 555; j <= 550 - y; ++j) process(j);
for (j = 22; j >= -28; j -= three) process(j);
for (j = 1927; j <= 1939; ++j) process(j);
for (j = x; j >= y; j -= -z) process(j);
for (j = p; j <= p + one; ++j) process(j);
setlocale(LC_NUMERIC, );
printf(, sum);
printf(, prod);
return 0;
} | 619Loops/With multiple ranges
| 5c
| 7nwrg |
package main
import "fmt"
type S struct {
start, stop, incr int
comment string
}
var examples = []S{
{-2, 2, 1, "Normal"},
{-2, 2, 0, "Zero increment"},
{-2, 2, -1, "Increments away from stop value"},
{-2, 2, 10, "First increment is beyond stop value"},
{2, -2, 1, "Start more than stop: positive increment"},
{2, 2, 1, "Start equal stop: positive increment"},
{2, 2, -1, "Start equal stop: negative increment"},
{2, 2, 0, "Start equal stop: zero increment"},
{0, 0, 0, "Start equal stop equal zero: zero increment"},
}
func sequence(s S, limit int) []int {
var seq []int
for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
seq = append(seq, i)
}
return seq
}
func main() {
const limit = 10
for _, ex := range examples {
fmt.Println(ex.comment)
fmt.Printf("Range(%d,%d,%d) -> ", ex.start, ex.stop, ex.incr)
fmt.Println(sequence(ex, limit))
fmt.Println()
}
} | 617Loops/Wrong ranges
| 0go
| p3ibg |
null | 611Ludic numbers
| 11kotlin
| 8uu0q |
import Data.List
main = putStrLn $ showTable True '|' '-' '+' table
table = [["start","stop","increment","Comment","Code","Result/Analysis"]
,["-2","2","1","Normal","[-2,-1..2] or [-2..2]",show [-2,-1..2]]
,["-2","2","0","Zero increment","[-2,-2..2]","Infinite loop of -2 <=> repeat -2"]
,["-2","2","-1","Increments away from stop value","[-2,-3..2]",show [-2,-3..2]]
,["-2","2","10","First increment is beyond stop value","[-2,8..2]",show [-2,8..2]]
,["2","-2","1","Start more than stop: positive increment","[2,3.. -2]",show [2,3.. -2]]
,["2","2","1","Start equal stop: positive increment","[2,3..2]",show [2,3..2]]
,["2","2","-1","Start equal stop: negative increment","[2,1..2]",show [2,1..2]]
,["2","2","0","Start equal stop: zero increment","[2,2..2]","Infinite loop of 2 <=> repeat 2"]
,["0","0","0","Start equal stop equal zero: zero increment","[0,0..0]", "Infinite loop of 0 <=> repeat 0"]]
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep: replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss | 617Loops/Wrong ranges
| 8haskell
| f7vd1 |
(defn prime? [i]
(cond (< i 4) (>= i 2)
(zero? (rem i 2)) false
:else (not-any? #(zero? (rem i %)) (range 3 (inc (Math/sqrt i))))))))
(defn mersenne? [p] (or (= p 2)
(let [mp (dec (bit-shift-left 1 p))]
(loop [n 3 s 4]
(if (> n p)
(zero? s)
(recur (inc n) (rem (- (* s s) 2) mp)))))))
(filter mersenne? (filter prime? (iterate inc 1))) | 618Lucas-Lehmer test
| 6clojure
| 48a5o |
from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i% lst[n]]
lenlst = len(lst)
for i in lst[n:]:
yield i | 614Lucky and even lucky numbers
| 3python
| 50xux |
import static java.util.Arrays.stream;
import java.util.Locale;
import static java.util.stream.IntStream.range;
public class Test {
static double dotProduct(double[] a, double[] b) {
return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();
}
static double[][] matrixMul(double[][] A, double[][] B) {
double[][] result = new double[A.length][B[0].length];
double[] aux = new double[B.length];
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < B.length; k++)
aux[k] = B[k][j];
for (int i = 0; i < A.length; i++)
result[i][j] = dotProduct(A[i], aux);
}
return result;
}
static double[][] pivotize(double[][] m) {
int n = m.length;
double[][] id = range(0, n).mapToObj(j -> range(0, n)
.mapToDouble(i -> i == j ? 1 : 0).toArray())
.toArray(double[][]::new);
for (int i = 0; i < n; i++) {
double maxm = m[i][i];
int row = i;
for (int j = i; j < n; j++)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row) {
double[] tmp = id[i];
id[i] = id[row];
id[row] = tmp;
}
}
return id;
}
static double[][][] lu(double[][] A) {
int n = A.length;
double[][] L = new double[n][n];
double[][] U = new double[n][n];
double[][] P = pivotize(A);
double[][] A2 = matrixMul(P, A);
for (int j = 0; j < n; j++) {
L[j][j] = 1;
for (int i = 0; i < j + 1; i++) {
double s1 = 0;
for (int k = 0; k < i; k++)
s1 += U[k][j] * L[i][k];
U[i][j] = A2[i][j] - s1;
}
for (int i = j; i < n; i++) {
double s2 = 0;
for (int k = 0; k < j; k++)
s2 += U[k][j] * L[i][k];
L[i][j] = (A2[i][j] - s2) / U[j][j];
}
}
return new double[][][]{L, U, P};
}
static void print(double[][] m) {
stream(m).forEach(a -> {
stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n));
System.out.println();
});
System.out.println();
}
public static void main(String[] args) {
double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};
double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},
{2.0, 5, 7, 1}};
for (double[][] m : lu(a))
print(m);
System.out.println();
for (double[][] m : lu(b))
print(m);
}
} | 615LU decomposition
| 9java
| drun9 |
use strict;
use warnings;
use English;
use Const::Fast;
use Math::AnyNum qw(:overload);
const my $n_max => 10_000;
const my $iter_cutoff => 500;
my(@seq_dump, @seed_lychrels, @related_lychrels);
for (my $n=1; $n<=$n_max; $n++) {
my @seq = lychrel_sequence($n);
if ($iter_cutoff == scalar @seq) {
if (has_overlap(\@seq, \@seq_dump)) { push @related_lychrels, $n }
else { push @seed_lychrels, $n }
@seq_dump = set_union(\@seq_dump, \@seq);
}
}
printf "%45s%s\n", "Number of seed Lychrels <= $n_max:", scalar @seed_lychrels;
printf "%45s%s\n", "Seed Lychrels <= $n_max:", join ', ', @seed_lychrels;
printf "%45s%s\n", "Number of related Lychrels <= $n_max:", scalar @related_lychrels;
printf "%45s%s\n", "Palindromes among seed and related <= $n_max:",
join ', ', sort {$a <=> $b} grep { is_palindrome($ARG) } @seed_lychrels, @related_lychrels;
sub lychrel_sequence {
my $n = shift;
my @seq;
for (1 .. $iter_cutoff) {
return if is_palindrome($n = next_n($n));
push @seq, $n;
}
@seq;
}
sub next_n { my $n = shift; $n + reverse($n) }
sub is_palindrome { my $n = shift; $n eq reverse($n) }
sub has_overlap {
my ($a, $b) = @ARG;
my %h;
$h{$_}++ for @{$a};
exists $h{$_} and return 1 for @{$b};
0;
}
sub set_union {
my ($a, $b) = @ARG;
my %h;
$h{$_}++ for @{$a}, @{$b};
keys %h;
} | 612Lychrel numbers
| 2perl
| w9me6 |
null | 613Mad Libs
| 11kotlin
| vqw21 |
null | 611Ludic numbers
| 1lua
| o558h |
import java.util.ArrayList;
import java.util.List;
public class LoopsWrongRanges {
public static void main(String[] args) {
runTest(new LoopTest(-2, 2, 1, "Normal"));
runTest(new LoopTest(-2, 2, 0, "Zero increment"));
runTest(new LoopTest(-2, 2, -1, "Increments away from stop value"));
runTest(new LoopTest(-2, 2, 10, "First increment is beyond stop value"));
runTest(new LoopTest(2, -2, 1, "Start more than stop: positive increment"));
runTest(new LoopTest(2, 2, 1, "Start equal stop: positive increment"));
runTest(new LoopTest(2, 2, -1, "Start equal stop: negative increment"));
runTest(new LoopTest(2, 2, 0, "Start equal stop: zero increment"));
runTest(new LoopTest(0, 0, 0, "Start equal stop equal zero: zero increment"));
}
private static void runTest(LoopTest loopTest) {
List<Integer> values = new ArrayList<>();
for (int i = loopTest.start ; i <= loopTest.stop ; i += loopTest.increment ) {
values.add(i);
if ( values.size() >= 10 ) {
break;
}
}
System.out.printf("%-45s%s%s%n", loopTest.comment, values, values.size()==10 ? " (loops forever)" : "");
}
private static class LoopTest {
int start;
int stop;
int increment;
String comment;
public LoopTest(int start, int stop, int increment, String comment) {
this.start = start;
this.stop = stop;
this.increment = increment;
this.comment = comment;
}
}
} | 617Loops/Wrong ranges
| 9java
| 0vyse |
const mult=(a, b)=>{
let res = new Array(a.length);
for (let r = 0; r < a.length; ++r) {
res[r] = new Array(b[0].length);
for (let c = 0; c < b[0].length; ++c) {
res[r][c] = 0;
for (let i = 0; i < a[0].length; ++i)
res[r][c] += a[r][i] * b[i][c];
}
}
return res;
}
const lu = (mat) => {
let lower = [],upper = [],n=mat.length;;
for(let i=0;i<n;i++){
lower.push([]);
upper.push([]);
for(let j=0;j<n;j++){
lower[i].push(0);
upper[i].push(0);
}
}
for (let i = 0; i < n; i++) {
for (let k = i; k < n; k++){
let sum = 0;
for (let j = 0; j < i; j++)
sum += (lower[i][j] * upper[j][k]);
upper[i][k] = mat[i][k] - sum;
}
for (let k = i; k < n; k++) {
if (i == k)
lower[i][i] = 1;
else{
let sum = 0;
for (let j = 0; j < i; j++)
sum += (lower[k][j] * upper[j][i]);
lower[k][i] = (mat[k][i] - sum) / upper[i][i];
}
}
}
return [lower,upper];
}
const pivot = (m) =>{
let n = m.length;
let id = [];
for(let i=0;i<n;i++){
id.push([]);
for(let j=0;j<n;j++){
if(i===j)
id[i].push(1);
else
id[i].push(0);
}
}
for (let i = 0; i < n; i++) {
let maxm = m[i][i];
let row = i;
for (let j = i; j < n; j++)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row) {
let tmp = id[i];
id[i] = id[row];
id[row] = tmp;
}
}
return id;
}
const luDecomposition=(A)=>{
const P = pivot(A);
A = mult(P,A);
return [...lu(A),P];
} | 615LU decomposition
| 10javascript
| 6b738 |
null | 617Loops/Wrong ranges
| 11kotlin
| emfa4 |
def generator(even=false, nmax=1000000)
start = even? 2: 1
Enumerator.new do |y|
n = 1
ary = [0] + (start..nmax).step(2).to_a
y << ary[n]
while (m = ary[n+=1]) < ary.size
y << m
(m...ary.size).step(m){|i| ary[i]=nil}
ary.compact!
end
ary[n..-1].each{|i| y << i}
raise StopIteration
end
end
def lucky(argv)
j, k = argv[0].to_i, argv[1].to_i
mode = /even/i=~argv[2]?:'even lucky': :lucky
seq = generator(mode ==:'even lucky')
ord = ->(n){}
if k.zero?
puts
elsif 0 < k
puts ,
else
k = -k
ary = []
loop do
case num=seq.next
when 1...j
when j..k then ary << num
else break
end
end
puts ,
end
end
if __FILE__ == $0
lucky(ARGV)
end | 614Lucky and even lucky numbers
| 14ruby
| gos4q |
for $i (
[ -2, 2, 1],
[ -2, 2, 0],
[ -2, 2, -1],
[ -2, 2, 10],
[ 2, -2, 1],
[ 2, 2, 1],
[ 2, 2, -1],
[ 2, 2, 0],
[ 0, 0, 0],
) {
$iter = gen_seq(@$i);
printf "start:%3d stop:%3d incr:%3d | ", @$i;
printf "%4s", &$iter for 1..10;
print "\n";
}
sub gen_seq {
my($start,$stop,$increment) = @_;
$n = 0;
return sub {
$term = $start + $n++ * $increment;
return $term > $stop ? '' : $term;
}
} | 617Loops/Wrong ranges
| 2perl
| ceh9a |
struct LuckyNumbers: Sequence, IteratorProtocol {
let even: Bool
let through: Int
private var drainI = 0
private var n = 0
private var lst: [Int]
init(even: Bool = false, through: Int = 1_000_000) {
self.even = even
self.through = through
self.lst = Array(stride(from: even? 2: 1, through: through, by: 2))
}
mutating func next() -> Int? {
guard n!= 0 else {
defer { n += 1 }
return lst[0]
}
while n < lst.count && lst[n] < lst.count {
let retVal = lst[n]
lst = lst.enumerated().filter({ ($0.offset + 1)% lst[n]!= 0 }).map({ $0.element })
n += 1
return retVal
}
if drainI == 0 {
lst = Array(lst.dropFirst(n))
}
while drainI < lst.count {
defer { drainI += 1 }
return lst[drainI]
}
return nil
}
} | 614Lucky and even lucky numbers
| 17swift
| 48q5g |
null | 615LU decomposition
| 11kotlin
| 0v9sf |
int is_prime(long long n) {
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
long long d = 5;
while (d * d <= n) {
if (n % d == 0) return 0;
d += 2;
if (n % d == 0) return 0;
d += 4;
}
return 1;
}
int main() {
long long i;
int n;
setlocale(LC_NUMERIC, );
for (i = LIMIT, n = 0; n < LIMIT; i++)
if (is_prime(i)) {
n++;
printf(, n, i);
i += i - 1;
}
return 0;
} | 620Loops/Increment loop index within loop body
| 5c
| f7cd3 |
package main
import (
"fmt"
"log"
"strings"
) | 616LZW compression
| 0go
| ktohz |
import re
from itertools import islice
data = '''
start stop increment Comment
-2 2 1 Normal
-2 2 0 Zero increment
-2 2 -1 Increments away from stop value
-2 2 10 First increment is beyond stop value
2 -2 1 Start more than stop: positive increment
2 2 1 Start equal stop: positive increment
2 2 -1 Start equal stop: negative increment
2 2 0 Start equal stop: zero increment
0 0 0 Start equal stop equal zero: zero increment
'''
table = [re.split(r'\s\s+', line.strip()) for line in data.strip().split('\n')]
for _start, _stop, _increment, comment in table[1:]:
start, stop, increment = [int(x) for x in (_start, _stop, _increment)]
print(f'{comment.upper()}:\n range({start}, {stop}, {increment})')
values = None
try:
values = list(islice(range(start, stop, increment), 999))
except ValueError as e:
print(' !!ERROR!!', e)
if values is not None:
if len(values) < 22:
print(' =', values)
else:
print(' =', str(values[:22])[:-1], '...') | 617Loops/Wrong ranges
| 3python
| lwkcv |
function luhn_validate
{
num=$1
shift 1
len=${
is_odd=1
sum=0
for((t = len - 1; t >= 0; --t)) {
digit=${num:$t:1}
if [[ $is_odd -eq 1 ]]; then
sum=$(( sum + $digit ))
else
sum=$(( $sum + ( $digit != 9? ( ( 2 * $digit ) % 9 ): 9 ) ))
fi
is_odd=$(( ! $is_odd ))
}
return $(( 0 != ( $sum % 10 ) ))
}
function print_result
{
if luhn_validate "$1"; then
echo "$1 is valid"
else
echo "$1 is not valid"
fi
}
print_result "49927398716"
print_result "49927398717"
print_result "1234567812345678"
print_result "1234567812345670" | 621Luhn test of credit card numbers
| 4bash
| qldxu |
def compress = { text ->
def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map }
def w = '', compressed = []
text.each { ch ->
def wc = "$w$ch"
if (dictionary[wc]) {
w = wc
} else {
compressed << dictionary[w]
dictionary[wc] = dictionary.size()
w = "$ch"
}
}
if (w) { compressed << dictionary[w] }
compressed
}
def decompress = { compressed ->
def dictionary = (0..<256).inject([:]) { map, ch -> map[ch] = "${(char)ch}"; map }
int dictSize = 128;
String w = "${(char)compressed[0]}"
StringBuffer result = new StringBuffer(w)
compressed.drop(1).each { k ->
String entry = dictionary[k]
if (!entry) {
if (k != dictionary.size()) throw new IllegalArgumentException("Bad compressed k $k")
entry = "$w${w[0]}"
}
result << entry
dictionary[dictionary.size()] = "$w${entry[0]}"
w = entry
}
result.toString()
} | 616LZW compression
| 7groovy
| gox46 |
from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print(
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in pals)) | 612Lychrel numbers
| 3python
| xc9wr |
package main
import "fmt"
func pow(n int, e uint) int {
if e == 0 {
return 1
}
prod := n
for i := uint(2); i <= e; i++ {
prod *= n
}
return prod
}
func abs(n int) int {
if n >= 0 {
return n
}
return -n
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return " " + s
}
return "-" + s
}
func main() {
prod := 1
sum := 0
const (
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
)
p := pow(11, x)
var j int
process := func() {
sum += abs(j)
if abs(prod) < (1<<27) && j != 0 {
prod *= j
}
}
for j = -three; j <= pow(3, 3); j += three {
process()
}
for j = -seven; j <= seven; j += x {
process()
}
for j = 555; j <= 550-y; j++ {
process()
}
for j = 22; j >= -28; j -= three {
process()
}
for j = 1927; j <= 1939; j++ {
process()
}
for j = x; j >= y; j -= -z {
process()
}
for j = p; j <= p+one; j++ {
process()
}
fmt.Println("sum = ", commatize(sum))
fmt.Println("prod = ", commatize(prod))
} | 619Loops/With multiple ranges
| 0go
| drcne |
seq(from = -2, to = 2, by = 1)
seq(from = -2, to = 2, by = 0)
seq(from = -2, to = 2, by = -1)
seq(from = -2, to = 2, by = 10)
seq(from = 2, to = -2, by = 1)
seq(from = 2, to = 2, by = 1)
seq(from = 2, to = 2, by = -1)
seq(from = 2, to = 2, by = 0)
seq(from = 0, to = 0, by = 0) | 617Loops/Wrong ranges
| 13r
| ypr6h |
import Data.List (elemIndex, tails)
import Data.Maybe (fromJust)
doLZW :: Eq a => [a] -> [a] -> [Int]
doLZW _ [] = []
doLZW as (x:xs) = lzw (return <$> as) [x] xs
where
lzw a w [] = [fromJust $ elemIndex w a]
lzw a w (x:xs)
| w_ `elem` a = lzw a w_ xs
| otherwise = fromJust (elemIndex w a): lzw (a ++ [w_]) [x] xs
where
w_ = w ++ [x]
undoLZW :: [a] -> [Int] -> [a]
undoLZW _ [] = []
undoLZW a cs =
cs >>=
(!!)
(foldl
((.) <$> (++) <*>
(\x xs -> return (((++) <$> head <*> take 1 . last) ((x !!) <$> xs))))
(return <$> a)
(take2 cs))
take2 :: [a] -> [[a]]
take2 xs = filter ((2 ==) . length) (take 2 <$> tails xs)
main :: IO ()
main = do
print $ doLZW ['\0' .. '\255'] "TOBEORNOTTOBEORTOBEORNOT"
print $
undoLZW
['\0' .. '\255']
[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
print $
((==) <*> ((.) <$> undoLZW <*> doLZW) ['\NUL' .. '\255'])
"TOBEORNOTTOBEORTOBEORNOT" | 616LZW compression
| 8haskell
| ng2ie |
library(gmp)
library(magrittr)
cache <- NULL
cache_reset <- function() { cache <<- new.env(TRUE, emptyenv()) }
cache_set <- function(key, value) { assign(key, value, envir = cache) }
cache_get <- function(key) { get(key, envir = cache, inherits = FALSE) }
cache_has_key <- function(key) { exists(key, envir = cache, inherits = FALSE) }
cache_reset()
isPalindromic <- function(num) {
paste0(unlist(strsplit(num,"")), collapse = "") ==
paste0(rev(unlist(strsplit(num,""))),collapse = "")
}
aStep <- function(num) {
num %>%
strsplit("") %>%
unlist() %>%
rev() %>%
paste0(collapse = "") %>%
sub("^0+","",.) %>%
as.bigz() %>%
'+'(num) %>%
as.character
}
max_search <- 10000
limit <- 500
related <- 0
lychrel <- vector("numeric")
palindrome_lychrel <- vector("numeric")
for (candidate in 1:max_search) {
n <- as.character(candidate)
found <- TRUE
for (iteration in 1:limit) {
n <- aStep(n)
if (cache_has_key(n)) {
related <- related + 1
found <- FALSE
if (isPalindromic(as.character(candidate))) palindrome_lychrel <- append(palindrome_lychrel, candidate)
break
}
if (isPalindromic(n)) {
found <- FALSE
break
}
}
if (found) {
if (isPalindromic(as.character(candidate))) palindrome_lychrel <- append(palindrome_lychrel, candidate)
lychrel <- append(lychrel,candidate)
seeds <- seeds + 1
n <- as.character(candidate)
for (iteration in 1:limit) {
cache_set(n,"seen")
n <- aStep(n)
}
}
}
cat("Lychrel numbers in the range [1, ",max_search,"]\n", sep = "")
cat("Maximum iterations =",limit,"\n")
cat("Number of Lychrel seeds:",length(lychrel),"\n")
cat("Lychrel numbers:",lychrel,"\n")
cat("Number of related Lychrel numbers found:",related,"\n")
cat("Number of palindromic Lychrel numbers:",length(palindrome_lychrel),"\n")
cat("Palindromic Lychrel numbers:",palindrome_lychrel,"\n") | 612Lychrel numbers
| 13r
| 163pn |
use warnings;
use strict;
my $template = shift;
open my $IN, '<', $template or die $!;
my $story = do { local $/ ; <$IN> };
my %blanks;
undef $blanks{$_} for $story =~ m/<(.*?)>/g;
for my $blank (sort keys %blanks) {
print "$blank: ";
chomp (my $replacement = <>);
$blanks{$blank} = $replacement;
}
$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story; | 613Mad Libs
| 2perl
| 0vls4 |
def (prod, sum, x, y, z, one, three, seven) = [1, 0, +5, -5, -2, 1, 3, 7]
for (
j in (
((-three) .. (3**3) ).step(three)
+ ((-seven) .. (+seven) ).step(x)
+ (555 .. (550-y) )
+ (22 .. (-28) ).step(three) | 619Loops/With multiple ranges
| 7groovy
| 0v3sh |
use warnings;
use strict;
use feature qw{ say };
{ my @ludic = (1);
my $max = 3;
my @candidates;
sub sieve {
my $l = shift;
for (my $i = 0; $i <= $
splice @candidates, $i, 1;
}
}
sub ludic {
my ($type, $n) = @_;
die "Arg0 Type must be 'count' or 'max'\n"
unless grep $_ eq $type, qw( count max );
die "Arg1 Number must be > 0\n" if 0 >= $n;
return (@ludic[ 0 .. $n - 1 ]) if 'count' eq $type and @ludic >= $n;
return (grep $_ <= $n, @ludic) if 'max' eq $type and $ludic[-1] >= $n;
while (1) {
if (@candidates) {
last if ('max' eq $type and $candidates[0] > $n)
or ($n == @ludic);
push @ludic, $candidates[0];
sieve($ludic[-1] - 1);
} else {
$max *= 2;
@candidates = 2 .. $max;
for my $l (@ludic) {
sieve($l - 1) unless 1 == $l;
}
}
}
return (@ludic)
}
}
my @triplet;
my %ludic;
undef @ludic{ ludic(max => 250) };
for my $i (keys %ludic) {
push @triplet, $i if exists $ludic{ $i + 2 } and exists $ludic { $i + 6 };
}
say 'First 25: ', join ' ', ludic(count => 25);
say 'Count < 1000: ', scalar ludic(max => 1000);
say '2000..2005th: ', join ' ', (ludic(count => 2005))[1999 .. 2004];
say 'triplets < 250: ', join ' ',
map { '(' . join(' ',$_, $_ + 2, $_ + 6) . ')' }
sort { $a <=> $b } @triplet; | 611Ludic numbers
| 2perl
| 4885d |
loop :: (b -> a -> b) -> b -> [[a]] -> b
loop = foldl . foldl
example = let
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
in
loop
(
\(sum, prod) j ->
(
sum + abs j,
if abs prod < 2^27 && j /= 0
then prod * j else prod
)
)
(0, 1)
[ [-three, -three + three .. 3^3]
, [-seven, -seven + x .. seven]
, [555 .. 550 - y]
, [22, 22 - three .. -28]
, [1927 .. 1939]
, [x, x + z .. y]
, [11^x .. 11^x + one] ] | 619Loops/With multiple ranges
| 8haskell
| 50pug |
examples = [
[ -2, 2, 1],
[ -2, 2, 0],
[ -2, 2, -1],
[ -2, 2, 10],
[ 2, -2, 1],
[ 2, 2, 1],
[ 2, 2, -1],
[ 2, 2, 0],
[ 0, 0, 0]
]
examples.each do |start, stop, step|
as = (start..stop).step(step)
puts
end | 617Loops/Wrong ranges
| 14ruby
| vqp2n |
...
const char *list[] = {,,,,};
int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
printf(, list[ix]);
} | 622Loops/Foreach
| 5c
| drynv |
import java.util.*;
public class LZW {
public static List<Integer> compress(String uncompressed) { | 616LZW compression
| 9java
| ql6xa |
import java.util.ArrayList;
import java.util.List;
public class LoopsWithMultipleRanges {
private static long sum = 0;
private static long prod = 1;
public static void main(String[] args) {
long x = 5;
long y = -5;
long z = -2;
long one = 1;
long three = 3;
long seven = 7;
List<Long> jList = new ArrayList<>();
for ( long j = -three ; j <= pow(3, 3) ; j += three ) jList.add(j);
for ( long j = -seven ; j <= seven ; j += x ) jList.add(j);
for ( long j = 555 ; j <= 550-y ; j += 1 ) jList.add(j);
for ( long j = 22 ; j >= -28 ; j += -three ) jList.add(j);
for ( long j = 1927 ; j <= 1939 ; j += 1 ) jList.add(j);
for ( long j = x ; j >= y ; j += z ) jList.add(j);
for ( long j = pow(11, x) ; j <= pow(11, x) + one ; j += 1 ) jList.add(j);
List<Long> prodList = new ArrayList<>();
for ( long j : jList ) {
sum += Math.abs(j);
if ( Math.abs(prod) < pow(2, 27) && j != 0 ) {
prodList.add(j);
prod *= j;
}
}
System.out.printf(" sum =%,d%n", sum);
System.out.printf("prod =%,d%n", prod);
System.out.printf("j values =%s%n", jList);
System.out.printf("prod values =%s%n", prodList);
}
private static long pow(long base, long exponent) {
return (long) Math.pow(base, exponent);
}
} | 619Loops/With multiple ranges
| 9java
| 9armu |
null | 616LZW compression
| 10javascript
| i4lol |
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(, a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf();
}
Done:
printf();
return 0;
} | 623Loops/Nested
| 5c
| em0av |
(doseq [item collection] (println item)) | 622Loops/Foreach
| 6clojure
| 6b23q |
require 'set'
def add_reverse(num, max_iter=1000)
(1..max_iter).each_with_object(Set.new([num])) do |_,nums|
num += reverse_int(num)
nums << num
return nums if palindrome?(num)
end
end
def palindrome?(num)
num == reverse_int(num)
end
def reverse_int(num)
num.to_s.reverse.to_i
end
def split_roots_from_relateds(roots_and_relateds)
roots = roots_and_relateds.dup
i = 1
while i < roots.length
this = roots[i]
if roots[0...i].any?{|prev| this.intersect?(prev)}
roots.delete_at(i)
else
i += 1
end
end
root = roots.map{|each_set| each_set.min}
related = roots_and_relateds.map{|each_set| each_set.min}
related = related.reject{|n| root.include?(n)}
return root, related
end
def find_lychrel(maxn, max_reversions)
series = (1..maxn).map{|n| add_reverse(n, max_reversions*2)}
roots_and_relateds = series.select{|s| s.length > max_reversions}
split_roots_from_relateds(roots_and_relateds)
end
maxn, reversion_limit = 10000, 500
puts
lychrel, l_related = find_lychrel(maxn, reversion_limit)
puts
puts
puts
pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort
puts
puts | 612Lychrel numbers
| 14ruby
| s2lqw |
null | 619Loops/With multiple ranges
| 11kotlin
| zhvts |
int main()
{
int i;
for (i = 1; i <= 10; i++) {
printf(, i);
printf(i == 10 ? : );
}
return 0;
} | 624Loops/N plus one half
| 5c
| xc8wu |
use List::Util qw(sum);
for $test (
[[1, 3, 5],
[2, 4, 7],
[1, 1, 0]],
[[11, 9, 24, 2],
[ 1, 5, 2, 6],
[ 3, 17, 18, 1],
[ 2, 5, 7, 1]]
) {
my($P, $AP, $L, $U) = lu(@$test);
say_it('A matrix', @$test);
say_it('P matrix', @$P);
say_it('AP matrix', @$AP);
say_it('L matrix', @$L);
say_it('U matrix', @$U);
}
sub lu {
my (@a) = @_;
my $n = +@a;
my @P = pivotize(@a);
my $AP = mmult(\@P, \@a);
my @L = matrix_ident($n);
my @U = matrix_zero($n);
for $i (0..$n-1) {
for $j (0..$n-1) {
if ($j >= $i) {
$U[$i][$j] = $$AP[$i][$j] - sum map { $U[$_][$j] * $L[$i][$_] } 0..$i-1;
} else {
$L[$i][$j] = ($$AP[$i][$j] - sum map { $U[$_][$j] * $L[$i][$_] } 0..$j-1) / $U[$j][$j];
}
}
}
return \@P, $AP, \@L, \@U;
}
sub pivotize {
my(@m) = @_;
my $size = +@m;
my @id = matrix_ident($size);
for $i (0..$size-1) {
my $max = $m[$i][$i];
my $row = $i;
for $j ($i .. $size-2) {
if ($m[$j][$i] > $max) {
$max = $m[$j][$i];
$row = $j;
}
}
($id[$row],$id[$i]) = ($id[$i],$id[$row]) if $row != $i;
}
@id
}
sub matrix_zero { my($n) = @_; map { [ (0) x $n ] } 0..$n-1 }
sub matrix_ident { my($n) = @_; map { [ (0) x $_, 1, (0) x ($n-1 - $_) ] } 0..$n-1 }
sub mmult {
local *a = shift;
local *b = shift;
my @p = [];
my $rows = @a;
my $cols = @{ $b[0] };
my $n = @b - 1;
for (my $r = 0 ; $r < $rows ; ++$r) {
for (my $c = 0 ; $c < $cols ; ++$c) {
$p[$r][$c] += $a[$r][$_] * $b[$_][$c] foreach 0 .. $n;
}
}
return [@p];
}
sub say_it {
my($message, @array) = @_;
print "$message\n";
$line = sprintf join("\n" => map join(" " => map(sprintf("%8.5f", $_), @$_)), @{+\@array})."\n";
$line =~ s/\.00000/ /g;
$line =~ s/0000\b/ /g;
print "$line\n";
} | 615LU decomposition
| 2perl
| 50wu2 |
[package]
name = "lychrel"
version = "0.1.0"
authors = ["monsieursquirrel"]
[dependencies]
num = "0.1.27" | 612Lychrel numbers
| 15rust
| 0v2sl |
package main
import(
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func isPrime(n uint64) bool {
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
d := uint64(5)
for d * d <= n {
if n % d == 0 {
return false
}
d += 2
if n % d == 0 {
return false
}
d += 4
}
return true
}
const limit = 42
func main() {
p := message.NewPrinter(language.English)
for i, n := uint64(limit), 0; n < limit; i++ {
if isPrime(i) {
n++
p.Printf("n =%-2d %19d\n", n, i)
i += i - 1
}
}
} | 620Loops/Increment loop index within loop body
| 0go
| jdw7d |
null | 616LZW compression
| 11kotlin
| 16dpd |
import scala.collection.mutable.LinkedHashMap
val range = 1 to 10000
val maxIter = 500;
def lychrelSeq( seed:BigInt ) : Stream[BigInt] = {
def reverse( v:BigInt ) = BigInt(v.toString.reverse)
def isPalindromic( v:BigInt ) = { val s = (v + reverse(v)).toString; s == s.reverse }
def loop( v:BigInt ):Stream[BigInt] = v #:: loop( v + reverse(v) )
val seq = loop(seed)
seq.take( seq.take(maxIter).indexWhere( isPalindromic(_) ) match {
case -1 => maxIter
case n => n + 1
})
} | 612Lychrel numbers
| 16scala
| i45ox |
import Data.List
import Control.Monad (guard)
isPrime :: Int -> Bool
isPrime n
| n <= 3 = n > 1
| n `mod` 2 == 0 || n `mod` 3 == 0 = False
| otherwise = l2 5 n
where l2 d n = x > n || l3 d n
where x = d * d
l3 d n
| n `mod` d == 0 = False
| n `mod` (d + 2) == 0 = False
| otherwise = l2 (d + 6) n
showPrime :: Int -> Int -> [(Int, Int)]
showPrime i n = if isPrime i
then (n, i): showPrime (i+i) (n+1)
else showPrime (i+1) n
digitGroup :: Int -> String
digitGroup = intercalate "," . reverse . map show . unfoldr (\n -> guard (n /= 0) >> pure (n `mod` 1000, n `div` 1000))
display :: (Int, Int) -> String
display (i, p) = show i ++ " " ++ digitGroup p
main = mapM_ (putStrLn . display) $ take 42 $ showPrime 42 1 | 620Loops/Increment loop index within loop body
| 8haskell
| o568p |
use constant one => 1;
use constant three => 3;
use constant seven => 7;
use constant x => 5;
use constant yy => -5;
use constant z => -2;
my $prod = 1;
sub from_to_by {
my($begin,$end,$skip) = @_;
my $n = 0;
grep{ !($n++ % abs $skip) } $begin <= $end ? $begin..$end : reverse $end..$begin;
}
sub commatize {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,(-?)$/$1/;
$s = reverse $s;
}
for my $j (
from_to_by(-three,3**3,three),
from_to_by(-seven,seven,x),
555 .. 550 - yy,
from_to_by(22,-28,-three),
1927 .. 1939,
from_to_by(x,yy,z),
11**x .. 11**x+one,
) {
$sum += abs($j);
$prod *= $j if $j and abs($prod) < 2**27;
}
printf "%-8s%12s\n", 'Sum:', commatize $sum;
printf "%-8s%12s\n", 'Product:', commatize $prod; | 619Loops/With multiple ranges
| 2perl
| bz0k4 |
(apply str (interpose ", " (range 1 11)))
(loop [n 1]
(printf "%d" n)
(if (< n 10)
(do
(print ", ")
(recur (inc n))))) | 624Loops/N plus one half
| 6clojure
| o5f8j |
int i = 1024;
while(i > 0) {
printf(, i);
i /= 2;
} | 625Loops/While
| 5c
| ypc6f |
(ns nested)
(defn create-matrix [width height]
(for [_ (range width)]
(for [_ (range height)]
(inc (rand-int 20)))))
(defn print-matrix [matrix]
(loop [[row & rs] matrix]
(when (= (loop [[x & xs] row]
(println x)
(cond (= x 20):stop
xs (recur xs)
:else:continue))
:continue)
(when rs (recur rs)))))
(print-matrix (create-matrix 10 10)) | 623Loops/Nested
| 6clojure
| 0vdsj |
local function compress(uncompressed) | 616LZW compression
| 1lua
| ayf1v |
from pprint import pprint
def matrixMul(A, B):
TB = zip(*B)
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
n = len(m)
ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
for j in xrange(n):
row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
return ID
def lu(A):
n = len(A)
L = [[0.0] * n for i in xrange(n)]
U = [[0.0] * n for i in xrange(n)]
P = pivotize(A)
A2 = matrixMul(P, A)
for j in xrange(n):
L[j][j] = 1.0
for i in xrange(j+1):
s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
U[i][j] = A2[i][j] - s1
for i in xrange(j, n):
s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P)
a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
pprint(part, width=19)
print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
pprint(part)
print | 615LU decomposition
| 3python
| 48x5k |
import BigInt
public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol {
@usableFromInline
let seed: T
@usableFromInline
var done = false
@usableFromInline
var n: T
@usableFromInline
var iterations: T
@inlinable
public init(seed: T, iterations: T = 500) {
self.seed = seed
self.n = seed
self.iterations = iterations
}
@inlinable
public mutating func next() -> T? {
guard!done && iterations!= 0 else {
return nil
}
guard!isPalindrome(n) || n == seed else {
done = true
return n
}
defer {
n += n.reversed()
iterations -= 1
}
return n
}
}
@inlinable
public func isPalindrome<T: CustomStringConvertible>(_ x: T) -> Bool {
let asString = String(describing: x)
for (c, c1) in zip(asString, asString.reversed()) where c!= c1 {
return false
}
return true
}
public protocol ReversibleNumeric: Numeric {
func reversed() -> Self
}
extension BigInt: ReversibleNumeric {
public func reversed() -> BigInt {
return BigInt(String(description.reversed()))!
}
}
typealias LychrelReduce = (seen: Set<BigInt>, seeds: Set<BigInt>, related: Set<BigInt>)
let (seen, seeds, related): LychrelReduce =
(1...10_000)
.map({ BigInt($0) })
.reduce(into: LychrelReduce(seen: Set(), seeds: Set(), related: Set()), {res, cur in
guard!res.seen.contains(cur) else {
res.related.insert(cur)
return
}
var seen = false
let seq = Lychrel(seed: cur).prefix(while: { seen = res.seen.contains($0); return!seen })
let last = seq.last!
guard!isPalindrome(last) || seen else {
return
}
res.seen.formUnion(seq)
if seq.count == 500 {
res.seeds.insert(cur)
} else {
res.related.insert(cur)
}
})
print("Found \(seeds.count + related.count) Lychrel numbers between 1...10_000 when limited to 500 iterations")
print("Number of Lychrel seeds found: \(seeds.count)")
print("Lychrel seeds found: \(seeds.sorted())")
print("Number of related Lychrel nums found: \(related.count)")
print("Lychrel palindromes found: \(seeds.union(related).filter(isPalindrome).sorted())") | 612Lychrel numbers
| 17swift
| qlcxg |
public class LoopIncrementWithinBody {
static final int LIMIT = 42;
static boolean isPrime(long n) {
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
long d = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
public static void main(String[] args) {
long i;
int n;
for (i = LIMIT, n = 0; n < LIMIT; i++)
if (isPrime(i)) {
n++;
System.out.printf("n =%-2d %,19d\n", n, i);
i += i - 1;
}
}
} | 620Loops/Increment loop index within loop body
| 9java
| w9nej |
library(Matrix)
A <- matrix(c(1, 3, 5, 2, 4, 7, 1, 1, 0), 3, 3, byrow=T)
dim(A) <- c(3, 3)
expand(lu(A)) | 615LU decomposition
| 13r
| 2x1lg |
import re
template = '''<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.'''
def madlibs(template):
print('The story template is:\n' + template)
fields = sorted(set( re.findall('<[^>]+>', template) ))
values = input('\nInput a comma-separated list of words to replace the following items'
'\n %s: '% ','.join(fields)).split(',')
story = template
for f,v in zip(fields, values):
story = story.replace(f, v)
print('\nThe story becomes:\n\n' + story)
madlibs(template) | 613Mad Libs
| 3python
| 8u20o |
def ludic(nmax=100000):
yield 1
lst = list(range(2, nmax + 1))
while lst:
yield lst[0]
del lst[::lst[0]]
ludics = [l for l in ludic()]
print('First 25 ludic primes:')
print(ludics[:25])
print(
% sum(1 for l in ludics if l <= 1000))
print()
print(ludics[2000-1: 2005])
n = 250
triplets = [(x, x+2, x+6)
for x in ludics
if x+6 < n and x+2 in ludics and x+6 in ludics]
print('\nThere are%i triplets less than%i:\n %r'
% (len(triplets), n, triplets)) | 611Ludic numbers
| 3python
| goo4h |
String loopPlusHalf(start, end) {
var result = '';
for(int i = start; i <= end; i++) {
result += '$i';
if(i == end) {
break;
}
result += ', ';
}
return result;
}
void main() {
print(loopPlusHalf(1, 10));
} | 624Loops/N plus one half
| 18dart
| bzek1 |
int luhn(const char* cc)
{
const int m[] = {0,2,4,6,8,1,3,5,7,9};
int i, odd = 1, sum = 0;
for (i = strlen(cc); i--; odd = !odd) {
int digit = cc[i] - '0';
sum += odd ? digit : m[digit];
}
return sum % 10 == 0;
}
int main()
{
const char* cc[] = {
,
,
,
,
0
};
int i;
for (i = 0; cc[i]; i++)
printf(, cc[i], luhn(cc[i]) ? : );
return 0;
} | 621Luhn test of credit card numbers
| 5c
| 0vtst |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.