The Weekly Challenge 004

Pi Digits and Word Finding!

Original | My Solutions

Task 1: Pi with output-sized script

"The Pi Challenge: Match Your Script Size!"

Write a script to output the same number of PI digits as the size of your script.

Perl
#!/usr/bin/env perl
use v5.36;
use Math::BigFloat;

sub pi_prefix ($size) {
    my $precision = $size + 8;
    my $pi_text   = Math::BigFloat->bpi($precision)->bstr();
    return substr $pi_text, 0, $size + 1;
}

my $script_size = -s $0;
say pi_prefix($script_size);
Python
#!/usr/bin/env python3
from decimal import Decimal, getcontext
import os

def pi_prefix(size: int) -> str:
    getcontext().prec = size + 12
    c = Decimal(426880) * Decimal(10005).sqrt()
    m = 1
    linear_term = 13591409
    x = 1
    k = 6
    s = Decimal(linear_term)
    for i in range(1, (size // 14) + 2):
        m = (m * (k * k * k - 16 * k)) // (i * i * i)
        linear_term += 545140134
        x *= -262537412640768000
        s += Decimal(m * linear_term) / Decimal(x)
        k += 12
    return format(c / s, "f")[:size + 1]

print(pi_prefix(os.path.getsize(__file__)))

Task 2: Possible words given chars

"The Word Detective: Find Words in Letters!"

Print each word that can be made using only the given letters.

Perl
#!/usr/bin/perl
use strict;
use warnings;

sub can_build {
    my ($word, $letters) = @_;
    my %need; $need{$_}++ for split //, lc $word;
    my %avail; $avail{$_}++ for split //, lc $letters;
    for my $c (keys %need) {
        return 0 if ($need{$c} // 0) > ($avail{$c} // 0);
    }
    return 1;
}

my $letters = shift;
while (<>) {
    chomp; print "$_\n" if can_build($_, $letters);
}
Python
#!/usr/bin/env python3
from collections import Counter
import sys

def can_build(word, letters):
    return all(Counter(word.lower())[c] <= Counter(letters.lower())[c] for c in word)

letters = sys.argv[1]
for line in sys.stdin:
    word = line.strip()
    if word and can_build(word, letters):
        print(word)