title: Convert singular to plural

text:
# Question
Title: Convert singular to plural
There are two forms of nouns, singular and plural. The conversion between these two is quite easy.

1. Normally, you end it with `s`. ex. `car` =\> `cars`.
2. If it ends with `s`,`x`,`z`,`ch` or `sh`, end it with `es`. ex. `bus`=\>`buses`.
3. If it ends with `y` with a consonant just before it, change the `y` to `ies`. ex. `penny` =\> `pennies`.
4. If it ends with `f` or `fe`, change it to `ves`. ex. `knife` =\> `knives`.
5. If it ends with `o` with a consonant just before it, change it to `oes`. ex.`potato` =\> `potatoes`.

---

# Task

You will be given a singular noun. You have to convert the given noun to plural and output it.

---

# Rules

* You will not be given irregular nouns, like `mouse` and `moose`.
* You will not be given exceptions, such as `safe` (`safes`; violating #4), `piano` (`pianos`; violating #5) and `o` (`oes`, violating #5).
* You will not be given words which have two or more possible plural forms, such as `mosquito` (`mosquitos` or `mosquitoes`) and `roof` (`roofs` or `rooves`).
* You will not be given uncountable nouns.
* `y` doesn't count as a vowel.

---

# Examples

```
car => cars
bus => buses
potato => potatoes
knife => knives
penny => pennies
exception => exceptions
wolf => wolves
eye => eyes
decoy => decoys
radio => radios

```

# Answer
> 47 votes
# Mathematica, 9 bytes

```
Pluralize

```

Yes, there is a built-in for this!

**Sample output**

```
Pluralize["car"]

```

> `cars`

```
Pluralize /@ {"bus", "potato", "knife", "penny", "exception", "wolf", "eye"}

```

> `{"buses", "potatoes", "knives", "pennies", "exceptions", "wolves", "eyes"}`

# Answer
> 19 votes
# Retina, ~~57~~ ~~53~~ ~~56~~ ~~55~~ ~~58~~ 57 bytes

*Thanks to MartinEnder for some golfing suggestions*

*Thanks to BusinessCat for golfing 1 byte*

```
([^aeiou]o|sh?|ch|z|x)$
$1e
fe?$
ve
([^aeiou])y$
$1ie
$
s

```

Try it online!

### Explanation (outdated)

```
([^aeiou])y$
$1ie

```

Changes `{consonant}y` to `{consonant}ie`

```
([^aeiou]o|[fxzs]|[sc]h)$
$&e

```

Appends an `e` to when the word ends with an `{consonant}o`, `f`,`x`,`z`,`s`,`sh` or `ch`.

```
fe$
ve

```

Changes an ending `fe` to `ve`

```
$
s

```

Finally append an `s` to the word.

### Edits

* Added bytes because I forgot the second rule
* Added bytes to update with `eye` as an example

# Answer
> 16 votes
# JavaScript (ES6),  ~~109~~  97 bytes

```
s=>s[R='replace'](/([^aeiou])y$/,'$1ie')[R](/fe?$/,'ve')[R](/([^aeiou]o|[sxz]|[cs]h)$/,'$1e')+'s'

```

Try it online!

# Answer
> 11 votes
## Batch, 325 bytes

```
@set/ps=
@for %%v in (a e i o u)do @(
for %%e in (o y)do @if %s:~-2%==%%v%%e goto s
if %s:~-2%==%%vf set s=%s:~,-1%ve&goto s
if %s:~-3%==%%vfe set s=%s:~,-2%ve&goto s
)
@if %s:~-1%==y set s=%s:~,-1%ie
@for %%e in (o s x z)do @if %s:~-1%==%%e set s=%s%e
@for %%e in (c s)do @if %s:~-2%==%%eh set s=%s%e
:s
@echo %s%s

```

# Answer
> 7 votes
# Haskell, 216 207 205 bytes

Thanks to @Lynn, @user1472751 and @Laikoni for the help!

```
import Data.List
(!)s=or.map(\x->x`isSuffixOf`s)
c=['b'..'z']\\"eiou"
p s|s!(words"s x z ch sh"++map(:"o")c)=s++"es"|s!map(:"y")c=init s++"ies"|s!["f"]=init s++"ves"|s!["fe"]=(init.init)s++"ves"|0<1=s++"s"

```

## Readable

```
import Data.List;

endsWithOneOf :: String -> [String] -> Bool
endsWithOneOf str ends = (or . map (\end -> end `isSuffixOf` str)) ends

consonants :: [Char]
consonants = ['a'..'z'] \\ "aeiou"

pluralize :: String -> String
pluralize str
    | str `endsWithOneOf` (words "s x z ch sh" ++ (map (:"o") consonants)) = str ++ "es"
    | str `endsWithOneOf` (map (:"y") consonants) = init str ++ "ies"
    | str `endsWithOneOf` ["f"] = init str ++ "ves"
    | str `endsWithOneOf` ["fe"] = (init.init) str ++ "ves"
    | otherwise = str ++ "s"

```

## Explanation

`import Data.List` for the function `isSuffixOf`. `endsWithOneOf` ( in the golfed version) returns whether one of the list elements is an ending of the string. `consonants(c)` is just a list of all consonants.

Finally, `pluralize(p)` checks for the endings and returns the proper pluralization.

Example:

```
p "potato" == "potatoes"

```

# Answer
> 5 votes
# PHP, ~~103~~ 100 bytes

```
<?=preg_replace(['/([^aeiou]o|sh?|x|z|ch)$/','/(?<![aeiou])y$/','/fe?$/'],['\1e',ie,ve],$argv[1]).s;

```

Try it online!

The `preg_replace` function takes in an array of patterns and replacements.

* Saved 2 bytes thanks to Titus.
* Saved 1 byte thanks to Dewi Morgan.

# Answer
> 5 votes
# Röda, 80 bytes

```
f&s{s~="([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve"s.="s"}

```

The function modifies its argument. Usage: `main word { f word; print word }` Here's a version that uses a return value (83 bytes):

```
f s{s~="([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve";[s.."s"]}

```

And below is a function that reads infinitely many values from the input stream and pushes plural forms to the output stream (~~87~~ 83 bytes):

```
{replace"([^aeiou])y$","$1ie","([sxz]|[cs]h|[^aeiuo]o)$","$1e","fe?$","ve","$","s"}

```

It's an anonymous function, as that is shorter than creating a named function.

# Answer
> 5 votes
# Perl, 66 + 2 (`-pl` flag) = 68 bytes

```
$_.=/(ch|sh?|x|z|[^aeiou]o)$/+s/([^aeiou])y$/$1i/+s/fe?$/v/?es:"s"

```

Using:

```
perl -ple '$_.=/(ch|sh?|x|z|[^aeiou]o)$/+s/([^aeiou])y$/$1i/+s/fe?$/v/?es:"s"' <<< car

```

Try it on Ideone.

# Answer
> 4 votes
# Python 3, ~~271~~ ~~239~~ 199 bytes

Thanks to @ovs for reducing it by 72 bytes!

```
lambda s,v="aeiou":(s[-2:]=="fe"and s[:-2]+"ve"or s[:-1]+((s[-1]=="y"and s[-2]not in v)*"ie"or s[-1]=="f"and"ve"or s[-1]+((s[-1]in"sxz"or s[-2:]in["ch","sh"])+(s[-1]=="o"and s[-2]not in v))*"e"))+"s"

```

Try it online!

# Answer
> 4 votes
# Python 3, ~~131~~ ~~125~~ ~~118~~ 121 bytes

*Thanks to The Thonnu for -6 bytes!
Golfed 7 bytes!
Fixed an issue for +3 bytes!*

```
lambda x:S("([sc]h?|x|z)$","\\1e",S(V+"y$","ie",S("fe?$","ve",S(V+"o$","oe",x))))+"s"
import re;S,V=re.sub,"(?<![aeiou])"

```

Try it online!

My first submission on here! Let me know if I did anything wrong.

# Answer
> 3 votes
# sed, 70 ~~79~~ bytes

69 ~~78~~ \+ 1 for `-E` (BSD)/`-r` (GNU) flag

```
s/([^aeiou])y$/\1ie/
s/([^aeiou]o|[fxzs]|[sc]h)$/&e/
s/fe/ve/
s/$/s/

```

Direct port of the retina answer.

# Answer
> 2 votes
# Pip, ~~63~~ 61 bytes

```
Y`[^aeiou]`OaR[C`sh?|x|z|ch`Cy.'y`fe?`y.'o].'$[_B.'i'v_].'e's

```

*So close* to catching Retina! But it's probably not going to happen. :(

Try it online!

### Explanation

Basic strategy: `R`eplace performs several replacements one after the other when given lists of patterns and replacements. We want to make the following replacements:

* `(sh?|x|z|ch)$` -\> add an `e`
* `[^aeiou]y` -\> change the `y` to `i` and add an `e`
* `fe?` -\> change to `v` and add an `e`
* `[^aeiou]o` -\> add an `e`

Then we want to tack on an `s` regardless.

Tricks:

* The `C` operator, given a regex, wraps it in a capturing group; `C`xyz`` is one byte shorter than ``(xyz)``.
* A list of regexes or replacements that all end with the same character can be created by concatenating the character to the list instead of including it in all the items. Concatenating a Scalar (string) to a Pattern (regex/replacement) coerces to a Pattern.
* Instead of concatenating the `s` (and having to deal with the precedence ordering of `R` and `.`), we can simply `O`utput the main part of the word and then print the `s` separately.

Spaced and commented code:

```
                  a is 1st cmdline input (implicit)
Y`[^aeiou]`       Yank the consonant regex into the y variable
O a R             Output (without newline): a, with the following replacements:
 [                List of regexes to replace:
  C `sh?|x|z|ch`    (sh?|x|z|ch)
  Cy . 'y           ([^aeiou])y
  `fe?`             fe?
  y . 'o            [^aeiou]o
 ] . '$           End of list; concatenate $ to each item
 [                List of replacements:
  _                 Identity function (replace with whole match)
  B                 B is short for {b}, a function returning its second argument; as a
                    callback function for regex replacement, the second argument is
                    the value of capturing group 1 (the consonant before y)
    . 'i            To that, concatenate i
  'v                Scalar literal v
  _                 Identity function
 ] . 'e           End of list; concatenate e to each item
's                Return Scalar literal s, which is autoprinted

```

# Answer
> 2 votes
## C#, ~~73~~ 163 bytes:

```
Func<string,string>p=System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentCulture).Pluralize

```

Yes, another language with it built-in (although you need to add a reference to `System.Data.Entity.Design.dll`)

To use:

```
var words = new[] { "car", "bus", "potato", "knife", "penny", "exception", "wolf", "eye", "decoy", "radio" };
foreach (var word in words)
{
    var plural = p(word);
    Console.Out.WriteLine($"{word} => {plural}");
}

```

Output:

> ```
> car => cars
> bus => buses
> potato => potatoes
> knife => knives
> penny => pennies
> exception => exceptions
> wolf => wolves
> eye => eyes
> decoy => decoys
> radio => radios
>
> ```

# Answer
> 2 votes
# Python ~~199~~ ~~187~~ 176 Bytes

```
lambda s:s+'\bve'*(s[-1]=='f')+'\b\bve'*(s[-2:]=='fe')+'e'*(s[-1]in'sxz'or s[-2:]in('ch','sh')or s[-1]=='o'and s[-2]not in'aiueo')+'\bie'*(s[-1]=='y'and s[-2]not in'aiueo')+'s'

```

# Answer
> 2 votes
## Rails runner, 18 bytes

```
$><<gets.pluralize

```

Example:

```
$ echo knife | rails r filename.rb
knives

```

# Answer
> 1 votes
**Python,** **296** **bytes**

```
z = input()
if z[-1]in['s','x','z','ch','sh']:print(z+'es')
elif z[-1]=='y'and z[-2]not in['a','e','i','o','u']:print(z[:-1]+'ies')
elif z[-2:]=='fe':print(z[:-2]+'ves')
elif z[-1]=='f':print(z[:-1]+'ves')
elif z[-1]=='o'and z[-2]not in['a','e','i','o','u']:print(z[:-1]+'oes')
else:print(z+'s')

```

# Answer
> 1 votes
# Lexurgy, 102 bytes

```
Class v {a,e,i,o,u}
p:
*=>es/{s,x,z,ch,zh,!@v o} _ $
y=>ies/!@v _ $
f e?=>ves/_ $
Else:
*=>s/_ $

```

Ungolfed explanation:

```
# define vowels
Class vowel {a,e,i,o,u}

plural:
*=>es/{s,x,z,ch,zh,!@vowel o} _ $ # 2,5
y=>ies/!@vowel _ $                # 3
{f,fe}=>ves/_ $                   # 4
Else:                             # Run the rules below if the above rules don't apply
*=>s/_ $                          # 1

```

# Answer
> 0 votes
## Java 7, 408 bytes

**Golfed:**

```
boolean b="bcdfghjklmnpqrstvwxyzs".contains(String.valueOf(s.charAt(s.length()-2))); String x=s.substring(0,s.length()-1);if(s.endsWith("s")||s.endsWith("x")||s.endsWith("z")||s.endsWith("ch")||s.endsWith("sh"))return s+"es";if(s.endsWith("y")&&b)return x+"ies";if(s.endsWith("f")) return x+"ves";if(s.endsWith("fe"))return s.substring(0,s.length()-2)+"ves";if(s.endsWith("o")&&b)return s+"es";return s+="s";

```

Basically testing what the end of the String is and adding / replacing letters depending on what case it is. The boolean and String at the beginning are just for removing repetition in the test cases and making the code smaller.

**Readable version:**

```
public static String pluralize(String s){

// Consonant at the 2nd last position?
boolean b = "bcdfghjklmnpqrstvwxyzs".contains(String.valueOf(s.charAt(s.length()-2)));

// Substring for cases where last letter needs to be replaced
String x = s.substring(0,s.length()-1);

if(s.endsWith("s") || s.endsWith("x") || s.endsWith("z") || s.endsWith("ch") || s.endsWith("sh"))
    return s + "es";
if(s.endsWith("y") && b)
    return x + "ies";
if(s.endsWith("f"))
    return x + "ves";
if(s.endsWith("fe"))
    return s.substring(0,s.length()-2) + "ves";
if(s.endsWith("o") && b)
    return s + "es";

return s += "s";
}

```

# Answer
> 0 votes
# C, 321 bytes

```
#define E else if(
#define C unsigned char
C*p(C*b){static C r[999],i,w,n,m;for(n=w=i=0;r[i]=b[i];n=w,w=b[i++]);m=!strchr("aeiou",n);if(strchr("sxz",w)||(w=='h'&&strchr("cs",n))||(w=='o'&&m))r[i++]='e';E'y'==w&&m)r[i-1]='i',r[i++]='e';E'f'==w)r[i-1]='v',r[i++]='e';E'f'==n&&w=='e')r[i-2]='v';r[i++]='s';r[i]=0;return r;}

```

test:

```
C*mx[]={"car","bus","potato","knife","penny","exception","wolf","eye","decoy","radio",0};

main()
{unsigned i;
 for(i=0;mx[i];++i)
    printf("[%s] [%s]\n", mx[i], p(mx[i]));
 return 0;
}

```

results:

```
[car] [cars]
[bus] [buses]
[potato] [potatoes]
[knife] [knives]
[penny] [pennies]
[exception] [exceptions]
[wolf] [wolves]
[eye] [eyes]
[decoy] [decoys]
[radio] [radios]
[radio] [radios]

```

# Answer
> 0 votes
Direct port of Retina:

# Ruby, 111 bytes

```
'sub(/([^aeiou])y/){"#{$1}ie"};sub(/(.*)([^aeiou]o|[fxzs]|[sc]h)$/){"#{$1}#{$2}e"};sub(/fe/,"ve");sub(/$/,"s")'

```

Try it online!

Invoke via `ruby -lpe` and supply a file as `input.txt` for first CLI argument.

---
Tags: code-golf, string, natural-language
---


title: A bit, a nibble or byte?

text:
# Question
Title: A bit, a nibble or byte?
Inspired by this challenge

Given an integer in the range `0 <= n < 2**64`, output the minimum sized container it can fit in out of

* bit: 1
* nibble: 4
* byte: 8
* short: 16
* int: 32
* long: 64

## Testcases:

```
0 -> 1
1 -> 1
2 -> 4
15 -> 4
16 -> 8
123 -> 8
260 -> 16
131313 -> 32
34359750709 -> 64

```

This is , so the shortest answer in bytes wins.

# Answer
# 05AB1E, 10 bytes

```
bg.²îD1Q+o

```

## Explanation

```
bg         Push the length of the binary representation of input without leading zeros
  .²î      Push x = ceil(log2(length))
     D1Q+  Add 1 if x == 1 or add 0 otherwise
         o Push pow(2,x) and implicitly display it

```

Try it online!
> 4 votes

# Answer
## Python, 39 bytes

```
f=lambda n:4**(n>1)*(n<16)or 2*f(n**.5)

```

Counts how many times one must take the square root for `n` to be below `16`, with some special-casing to avoid outputs of 2.

If 2 were included, we could do

```
f=lambda n:n<2or 2*f(n**.5)

```

with True for 1.

---

**41 bytes:**

```
f=lambda n,i=1:i*(2**i>n)or f(n,i<<1+i%2)

```

Repeatedly doubles the exponent `i` until `2**i>n`. Skips from `i=1` to `i=4` by shifting an additional bit when `i` is odd.

Alt 45 bytes:

```
f=lambda n,i=4:4**(n>1)*(2**i>n)or 2*f(n,i*2)

```
> 21 votes

# Answer
# J, 19 bytes

Monadic verb taking the number on the right and spitting out the container size. There are a couple of equivalent ways of writing it so I've included both.

```
2^2(>.+1=>.)@^.#@#:
2^s+1=s=.2>.@^.#@#:

```

Explained by explosion:

```
2^2(>.+1=>.)@^.#@#: NB. takes one argument on the right...
                 #: NB. write it in binary
               #@   NB. length (i.e. how many bits did that take?)
  2          ^.     NB. log base 2 of that
   (>.     )@       NB. ceiling
      +1=>.         NB. +1 if needed (since no container is two bits wide)
2^                  NB. base 2 exponential

```

What's cool is we see two different ways of taking log base 2 in J. The first is the obvious `2^.`, which is a numerical logarithm. The second is `#@#:`, which can be read as "length of base-2 representation". This is almost equivalent to one-plus-floor-of-log-base-2, except that `#:0` is the one-element list `0`, which is exactly what we want. This beats `1+2<.@^.1&>.` by 8 bytes.

In use at the REPL:

```
   f =: 2^2(>.+1=>.)@^.#@#:
   f 131313
32
   f 34359750709
64
   (,.f"0) 0 1 2 15 16 123 260
  0  1
  1  1
  2  4
 15  4
 16  8
123  8
260 16

```

---

Old, overly clever 20 byte solution.

```
2&^.(>.+1=>.&.)@#@#: NB. takes one argument on the right...
                #@#: NB. how many bits
2&^.                 NB. log base 2 of that
     >.              NB. ceiling
       +1=>.         NB. +1 if needed (since no container is two bits wide)
    (       &.)      NB. undo log base 2

```
> 12 votes

# Answer
# Python, 53 50 49 bytes

```
lambda n:[w for w in[1,4,8,16,32,64]if n<2**w][0]

```
> 9 votes

# Answer
# Mathematica, ~~44~~ ~~39~~ 38 bytes

Thanks @orlp for 5 bytes and @MartinEnder for 1 byte.

```
FirstCase[{1,4,8,16,32,64},x_/;2^x>#]&

```

Finds the first the elements in the list `{1, 4, 8, 16, 32, 64}` such that 2^number is greater than the input.
> 8 votes

# Answer
# Pip, 19 bytes

```
(a<2**_FI2**,7RM2i)

```

Try it online!

### How it works

```
                     a is 1st cmdline arg, i is 0 (implicit)
         2**,7       Construct powers of 2 from 0 to 6 [1 2 4 8 16 32 64]
              RM2    Remove 2
       FI            Filter for elements for which:
 a<2**_                a is less than 2 to that element
(                i)  Get 0th item of resulting list and autoprint

```
> 8 votes

# Answer
## JavaScript (ES7), 35 bytes

```
n=>[1,4,8,16,32,64].find(b=>2**b>n)

```
> 7 votes

# Answer
# Mathematica, ~~46~~ ~~43~~ 38 bytes

*Thanks to JungHwan Min and Martin Ender for saving 3 bytes!* *Thanks to ngenisis for a big 5-byte savings!*

```
2^⌈Log2@BitLength@#⌉/.{2->4,0->1}&

```

Unnamed function taking a nonnegative integer as input and returning a positive integer. `BitLength@#` computes the number of bits in the input, and then `2^⌈Log2@...⌉` computes the smallest power of 2 that's at least as large as the number of bits. Finally, `/.{2->4,0->1}` takes care of the special case that there's no "niblit" between bit and nybble, and also fixes the answer for the weird input `0`.
> 6 votes

# Answer
# Julia, 40 bytes

```
n->filter(x->n<big(2)^x,[1;2.^(2:6)])[1]

```

This is an anonymous function that generates an array of the powers of 2 from 0 to 6, excluding 2, and filters it to only those elements *x* such that 2<sup>*x*</sup> is greater than the input. The first such element is the answer. Unfortunately this requires promoting 2 to a `BigInt` to avoid overflow on *x* = 64.

This is actually quite similar to orlp's Python answer, though I didn't see it before concocting this approach.

Try it online!
> 4 votes

# Answer
# Perl 6, 30 bytes

```
{first 1+<*>$_,1,4,8,16,32,64}

```

`+<` is Perl 6's left bit shift operator, which many other languages call `<<`.
> 4 votes

# Answer
## Haskell, 31 bytes

```
f n=[2^i|i<-0:[2..],2^2^i>n]!!0

```

32-byte alt:

```
f n|n<2=1|n<16=4|1>0=2*f(sqrt n)

```
> 4 votes

# Answer
# Java, 143 bytes.

```
int f(long a){a=Long.toBinaryString(a).length();if(a<2)return 1;if(a<5)return 4;if(a<9)return 8;if(a<17)return 16;if(a<33)return 32;return 64;}

```
> 2 votes

# Answer
# Haskell, 43 bytes

```
f x=head$filter((>x).(2^))$[1,4,8,16,32,64]

```
> 2 votes

# Answer
# Java 8, ~~65~~ 55 bytes

This is a lambda expression which takes a `long` and returns an `int`. Never golfed in Java before, so this should be easily beatable:

```
x->{int i=1;while(Math.pow(2,i)<=x)i<<=1+i%2;return i;}

```

**Try it online!**

---

For **47 bytes**, we could have:

```
x->{int i=1;while(1L<<i<=x)i<<=1+i%2;return i;}

```

However, `1L<<i` overflows for return values larger than 32, so this fails for the final testcase.
> 2 votes

# Answer
# Ruby, ~~39~~ 36 bytes

```
->n{2**[0,*2..6].find{|p|2**2**p>n}}

```

Thanks G B for helping golf
> 2 votes

# Answer
# bash, ~~49 bytes~~ 48 bytes

```
for((y=1;$[y==2|$1>=1<<y];$[y*=2])){ :;};echo $y

```

or

```
for((y=1;$[y==2|$1>=1<<y];)){ y=$[y*2];};echo $y

```

Save in a script and pass the number to be tested as an argument.

*Edit: Replaced || with |, which works because the arguments are always 0 or 1.*

**Note:** This works for integers up to the largest positive integer that your version of bash can handle. If I have time, I'll modify it to work up to 2^64-1 in versions of bash that use 32-bit signed arithmetic.

In the meantime, here's a 64-byte solution that works for arbitrarily large numbers (in any bash version):

```
for((x=`dc<<<2o$1n|wc -c`;$[x==2||x&(x-1)];$[x++])){ :;};echo $x

```
> 2 votes

# Answer
## Racket 45 bytes

```
(findf(λ(x)(>(expt 2 x)m))'(1 4 8 16 32 64))

```

Ungolfed:

```
(define (f m)
  (findf (λ (x) (> (expt 2 x) m))          ; find first function
         '(1 4 8 16 32 64)))

```

Other versions:

```
(define (f1 m)
  (for/last ((i '(1 4 8 16 32 64))         ; using for loop, taking last item
             #:final (> (expt 2 i) m))     ; no further loops if this is true
    i))

```

and using string length:

```
(define (f2 m)
  (for/last
      ((i '(1 4 8 16 32 64))
       #:final (<= (string-length
                    (number->string m 2))  ; convert number to binary string
                   i))
    i))

```

Testing:

```
(f 0)
(f 1)
(f 2)
(f 15)
(f 16)
(f 123)
(f 260)
(f 131313)
(f 34359750709)

```

Output:

```
1
1
4
4
8
8
16
32
64

```
> 2 votes

# Answer
## Mathematica, 30 bytes

```
2^(f=BitLength)[f@#-1]/. 2->4&

```

Explanation:

Let `N` be the set of nonnegative integers. Define two functions on `N`, `BitLength` and `NextPower` as follows:

```
BitLength(n) := min {x in N : 2^x - 1 >= n}
NextPower(n) := 2^(min {x in N : 2^x >= n})

```

This solution essentially calculates `NextPower(BitLength(n))` given an integer `n >= 0`. For `n > 0`, we can see that `NextPower(n) = 2^BitLength(n-1)`, so `NextPower(BitLength(n)) = 2^BitLength(BitLength(n)-1)`.

Now the Mathematica `BitLength` built-in agrees with the definition I gave for `n >= 0`. For `n < 0`, `BitLength[n] == BitLength[BitNot[n]] == BitLength[-1-n]`, so `BitLength[-1] == BitLength[0] == 0`. Thus we get the desired answer of `1` for `n==0`.

Since we skip straight from bit to nibble, we have to replace answers of `2` with `4`.
> 2 votes

# Answer
# Stacked, ~~34~~ 30 bytes

```
@n 1 2 6|>2\^,:n 2 log>keep 0#

```

or

```
{!1 2 6|>2\^,:n 2 log>keep 0#}

```

The first takes input on the TOS and leaves output on TOS; the second is a function. Try it here!

## Explanation

```
@n 1 2 6|>2\^,:n 2 log>keep 0#
@n                               set TOS to `n`
   1 2 6|>2\^,                   equiv. [1, ...2 ** range(2, 6)]
              :                  duplicate it
               n                 push `n`
                 2 log           log base-2
                      >          element-wise `>`
                       keep      keep only truthy values
                            0#   yield the first element

```

Here's an example of it working on the repl:

```
> 8    (* input *)
(8)
> @n 1 2 6|>2\^,:n 2 log>keep 0#    (* function *)
(4)
>    (* output *)
(4)

```

## Test cases

```
> {!1 2 6|>2\^,:n 2 log>keep 0#} @:f
()
> (0 1 2 15 16 123 260 131313 34359750709) $f map
((1 1 4 4 8 8 16 32 64))
>

```

Or, as a full program:

```
{!1 2 6|>2\^,:n 2 log>keep 0#} @:f

(0 1 2 15 16 123 260 131313 34359750709) $f map

out

```
> 2 votes

# Answer
# Thunno, \\$ 13 \log\_{256}(96) \approx \\$ 10.70 bytes

```
bL2AYZmD1=+2@

```

Attempt This Online!

Port of Osable's 05AB1E answer.

#### Explanation

```
bL2AYZmD1=+2@  # Implicit input
bL             # Length of binary representation
  2AY          # Log base 2 of above
     Zm        # Ceil of above
        1=     # Equals one?
       D  +    # If true, add one; else, pass
           2@  # Two to the power of above
               # Implicit output

```
> 2 votes

# Answer
# PHP, ~~49~~ ~~46~~ 44 bytes

```
echo(2**ceil(log(log(1+$argn,2),2))-2?:2)+2;

```

Run like this:

```
echo 16 | php -R 'echo(2**ceil(log(log(1+$argv[1],2),2))-2?:2)+2;';echo

```

# Explanation

```
echo                       # Output the result of the expression
  (
    2**                    # 2 to the power
      ceil(log(            # The ceiling of the power of 2 of bitsize
        log(1+$argn,2),    # Number of bits needed
        2
      ))
      - 2 ?:               # Subtract 2 (will be added back again)
      2;                   # If that results in 0, result in 2 (+2=4).
  ) + 2                    # Add 2.

```

# Tweaks

* Saved 3 bytes by getting rid of the `$r=` assignment
* Saved 2 bytes by using `-R` to make `$argn` available
> 1 votes

# Answer
# Octave, ~~40 36 31~~ 29 bytes

Simple anonymous function. It is assumed that the input value is an integer - see the caveat at the end.

```
@(a)(b=2.^[0 2:6])(a<2.^b)(1)

```

The code works as follows:

* First an array of the allowed bit lengths (1,4,8,16,32,64) is created and saved to `b`.
* Next we find the number of bits required to store the input number `a` by comparing with the maximum size of each container in `b` to see which are big enough.
* We then use the resulting index vector to extract the container size from `b` again.
* Finally we take the first element in the resulting array which will be the smallest container possible.

You can try it online here.

Simply run the following code, and then do `ans(x)`.

---

The only caveat with this is that double precision is used for constants by default which means that it only works with numbers up to the highest value representable by a double precision float that is less than 2^64.

This can be fixed by ensuring that the number that is supplied to the function is an integer rather than a double. This can be achieved by calling the function for example with: `ans(uint64(x))`.
> 1 votes

# Answer
# CJam, 18 bytes

```
2ri2b,2mLm]_({)}|#

```

Try it online!

**Explanation**

```
2                   Push 2
 ri                 Read an integer from input
   2b,              Get the length of its binary representation
      2mLm]         Take the ceiling of the base-2 log of the length
           _(       Duplicate it and decrement it
             {)}|   Pop the top element, if it's 0, increment the next element
                     Effectively, if ceil(log2(input)) was 1, it's incremented to 2,
                     otherwise it stays the same.
                 #  Raise 2 to that power

```
> 1 votes

# Answer
# Vyxal, 9 bytes

```
ʀ~‹E≬E?>c

```

Try it Online!

This took a lot of experimenting to get to 9 bytes. Like at least 20 minutes of trying and trying.

## Explained

```
ʀ~‹E≬E?>c
ʀ          # The range [0, input]
 ~‹        # With 1 removed (filter by decrement, could also be 1o, but that's not as stylish)
   E       # with 2 raised to the power of each item. This creates a list of [1, 4, ...]
    ≬   c  # get the first item of that where
     E     #   2 to the power of the item
      ?>   #   is greater than the input

```
> 1 votes

# Answer
# C, ~~71~~ 52 bytes

```
i;f(long long n){for(i=1;n>>i;i*=2);return i-2?i:4;}

```
> 0 votes

# Answer
## QBIC, 27 bytes

```
:~a<2|_Xq]{~a<2^t|_Xt\t=t*2

```

Explanation

```
:        Get cmd line parameter N, call it 'a'
~a<2     IF 'a' is 0 or 1 (edge case)
|_Xq]    THEN quit, printing 1 ('q' is auto-initialised to 1). ']' is END-IF
{        DO - infinite loop
    2^t  't' is our current number of bits, QBIC sets t=4 at the start of the program.
         2^t gives the maximum number storable in t bytes.
 ~a<     IF the input fits within that number,
|_Xt     THEN quit printing this 't'
\t=t*2   ELSE jump to the next bracket (which are spaced a factor 2 apart, from 4 up)
         DO-loop is auto-closed by QBIC.

```
> 0 votes

# Answer
## Pyke, 13 bytes

```
7Zm@2-#2R^<)h

```

Try it here!

```
7Zm@          -   [set_bit(0, i) for i in range(7)] <- create powers of 2
    2-        -  ^.remove(2)
      #    )h - filter(^, V)[0]
       2R^    -   2 ** i
          <   -  input < ^

```
> 0 votes

# Answer
# PHP, 43 bytes

```
for(;1<<2**$i++<=$argn;);echo 2**$i-=$i!=2;

```

Run with `echo <number> | php -R '<code>'`.

loops `$i` up until `2**(2**$i)` is larger than input. (Tweak: `<<` instead of `**` to eliminate parens)
After the loop, $i is one too high; so it gets a decrement before calculating the output
\- but not for `$i==2`.
> 0 votes

---
Tags: code-golf, number, binary
---


# Question
Title: Join N copies of a snippet to produce N^2 characters
# Challenge

Write the shortest snippet of code possible such that, when N copies of it are concatenated together, the number of characters output is N2. N will be a positive integer.

For example if the snippet was `soln();`, then running `soln();` would print exactly 1 character, and running `soln();soln();` would print exactly 4 characters, and running `soln();soln();soln();` would print exactly 9 characters, etc.

Any characters may be in the output as long as the total number of characters is correct. To avoid cross-OS confusion, `\r\n` newlines are counted as one character.

**Programs may not read their own source or read their file size or use other such loopholes.** Treat this like a strict challenge.

The output may go to stdout or a file or a similar alternative. There is no input.

Comments in the code are fine, as is exiting mid-execution.

Any characters may be in the program. The shortest submission in bytes wins.

# Answer
> 23 votes
# TECO, 4 bytes

```
V1\V

```

`V` prints the contents of the current line in the text buffer. `1\` inserts the string representation of the number 1 at the current position.

So on the *N*th iteration of the program, the first `V` will output *N - 1* copies of the character `1`, then add another `1` to the text, then output *N* `1`s.

# Answer
> 22 votes
# Brainfuck, ~~17~~ 16 bytes

```
[>+>-..+<<-]-.>+

```

You can test it here. Just use the fact that `n<sup>2</sup>+2n+1=(n+1)<sup>2</sup>`.

# Answer
> 22 votes
# Brainfuck, 11

I saw the first Brainfuck answer and thought it's way too long :)

```
[.<]>[.>]+.

```

The output may be easier to see if you replace the plus with a lot more pluses.

On the Nth iteration, each loop outputs N - 1 copies of the character with ASCII value 1, and then one more with `+.`.

# Answer
> 16 votes
# Python 2, 22

```
a='';print a;a+='xx';a

```

Prints the empty string, then two `x`'s, then `x`' four and so on. With the newline after each string, this comes out to `n*n` characters.

One copy: `"\n"` (1 char)
Two copies: `"\nxx\n"` (4 chars)
Three copies: `"\nxx\nxxxx\n"` (9 chars)

In order to stop the initial variable `a` from being reinitialized each run, I end the code with a `;a`, which is benign on its own, but combined with the next loop to create the scapegoat `aa` to be assigned instead. This trick isn't mine; I saw it in a previous answer. I'd appreciate if someone could point me so I could give credit.

# Answer
> 10 votes
# CJam, 6 bytes

```
LLS+:L

```

Uses the fact that `n<sup>2</sup> + n + (n+1) = (n+1)<sup>2</sup>`.

```
L      "Push L. Initially this is an empty string, but its length increases by 1 with each copy
        of the snippet.";
 L     "Push another L.";
  S+   "Add a space to the second copy.";
    :L "Store the lengthened string in L for the next copy of the snippet.";

```

# Answer
> 10 votes
# ///, 21 bytes

I'm sure there is a really short and twisted way to solve this in **///** but I couldn't find anything, beyond the "straightforward" way yet:

```
1/1\//112\///2\//1\//

```

This is based on the approach of printing consecutive odd numbers. The snippet consists of a `1` at the start which is printed, and two replacements which add two more `1`s to that first part of each consecutive copy of the snippet. Let's go through this for `N = 3`. The following should be read in groups of 3 or more lines: 1. the current code, 2. the processed token(s), 3. (and following) a comment what the above token does.

```
1/1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\//
1
is printed
/1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\//
/1\//112\//
replaces all occurrences of 1/ with 112/. This affects the starts of all further snippets
but not the substitution commands, because the slashes in those are always escaped.
It is necessary to put a 2 in there, because otherwise the interpreter goes into an infinite
loop replacing the resulting 1/ again and again.
/2\//1\//112/1\//112\///2\//1\//112/1\//112\///2\//1\//
/2\//1\//
Replace all occurrences of 2/ with 1/, so the the next snippets substitution works again.
111/1\//112\///2\//1\//111/1\//112\///2\//1\//
111
is printed
/1\//112\///2\//1\//111/1\//112\///2\//1\//
/1\//112\//
add two 1s again
/2\//1\//11112/1\//112\///2\//1\//
/2\//1\//
turn the 2 into a 1 again
11111/1\//112\///2\//1\//
11111
print 11111
/1\//112\///2\//1\//
the last two substitutions have nothing to substitute so they do nothing

```

Interestingly, it works just as well if we move the `1` to the end:

```
/1\//112\///2\//1\//1

```

# Answer
> 7 votes
# \>\<\>, 14 bytes

```
1:na*a*';'10p!

```

Uses the "sum of consecutive odd integers starting from 1" idea. It starts off with 1 and multiplies it by 100 each time, increasing the length of the output progressively by increments of 2.

For example, appending 5 copies gives

```
1100100001000000100000000

```

I tested by piping the output to a file, and didn't see a trailing newline.

## Breakdown

```
1                   Push 1, skipped by ! every time except the first
 :n                 Copy top of stack and output as num
   a*a*             Multiply by 10 twice
       ';'10p       Modify the source code so that the first : becomes a ; for termination
             !      Skip the next 1

```

# Answer
> 5 votes
# CJam, ~~10~~ 9 bytes

```
],)_S*a*~

```

This prints N2 spaces where `N` is the number of copies of the code.

**Code eexpansion**:

```
],            "Wrap everything on stack and take length";
  )_          "Increment and take copy";
    S*        "Get that length space string";
      a*      "Wrap that space string in an array and create that many copies";
        ~     "Unwrap so that next code can use to get length";

```

Try it online here

# Answer
> 5 votes
# Python 2, 20 bytes

```
g=0
print'g'*g;g+=2#

```

# Answer
> 5 votes
# Java - 91 bytes

```
{String s=System.getProperty("a","");System.out.println(s);System.setProperty("a","xx"+s);}

```

This solution is equivalent to this other one in Python. It surely won't win, but it was fun :)

# Answer
> 4 votes
## Perl, 14 bytes

```
print;s//__/;

```

This needs to be run with Perl's `-l` command switch, which causes `print` to append new lines.

It prints the default variable `$_`, then prepends two underscores via substitution.

Example:

```
$ perl -le 'print;s//__/;print;s//__/;print;s//__/;print;s//__/;'

__
____
______

```

# Answer
> 4 votes
# Brainfuck, 10 chars

Both previous Brainfuck solutions were *waaay* too long (16 and 11 chars) so here is a shorter one:

```
+[.->+<]>+

```

In the `n`-th block it prints out `2*n-1` characters (with codepoints from `2*n-1` to `1`)

# Answer
> 3 votes
# C, 87 bytes

```
#if!__COUNTER__
#include __FILE__
main(a){a=__COUNTER__-1;printf("%*d",a*a,0);}
#endif

```

This uses two magic macros. `__COUNTER__` is a macro that expands to `0` the first time it is used, `1` the second, etc. It is a compiler extension, but is available in both gcc, clang, and Visual Studio at least. `__FILE__` is the name of the source file. Including a file in C/C++ is literally the same as pasting it directly into your source code, so it was a little tricky to make use of.

It would still be possible to use this technique without `__COUNTER__`. In that case, the standard guard against using code twice could be used for the `#if` statement, and `__LINE__` could be used to count the number of characters needed.

# Answer
> 3 votes
# Prelude, ~~18~~ 12 bytes

```
^1+(9!1-)#2+

```

This prints N2 tabs. It assumes a standard-compliant interpreter which prints characters instead of numbers, so if you use the Python interpreter you'll need to set `NUMERIC_OUTPUT` to `False`.

The idea is simply to use the top of the stack (which is initially 0) as `2(N-1)`, and print `2N-1` tabs, then increment the top of the stack by 2. Hence each repetition prints the next odd number of tabs.

# Answer
> 3 votes
## Java - 59 / 44 (depending on requirements)

```
static String n="1";
static{System.out.print(n);n+="11";}//

```

Apparently we're allowed to assume code runs in a class.

If it can go inside a main method:

```
String n="1";
System.out.print(n);n+="11";//

```

# Answer
> 2 votes
# Dyalog APL, ~~20~~ 19 bytes

A matrix based solution.

```
{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'

```

Try it here. Returns a string of `N<sup>2</sup>` repetitions of `a`. Explanation by explosion for `N = 2`:

```
{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'
                                  ⍪'a'  Wrap 'a' into a 1x1 matrix.
                'a'{            }⍨      Binary function: bind 'a' to ⍵ and the matrix to ⍺.
                    ⍺≢⍵:                The arguments are not identical,
                        ⍵⍪⍵,⍺           so add to the matrix 1 column and 1 row of 'a's.
               ⍪                        Identity function for a matrix.
{            }⍨                         Unary function: bind the matrix to both ⍵ and ⍺.
 ⍺≢⍵:                                   The arguments are identical,
           ∊⍺                           so flatten the matrix into the string 'aaaa'.

```

# Answer
> 2 votes
## T-SQL 117

```
IF OBJECT_ID('tempdb..#')IS NULL CREATE TABLE #(A INT)INSERT INTO # VALUES(1)SELECT REPLICATE('a',COUNT(*)*2-1)FROM #

```

Note the trailing space to ensure that the if condition is properly checked every time.

Uses the odd numbers approach. Not sure if there's a newline on select statements.

Not sure if there's a shorter way to create a table if it doesn't exist.

# Answer
> 2 votes
## STATA 20

```
di _n($a)
gl a=$a+2

```

There is a trailing new line to make sure that the display (di) statement works. First display the current number in $a newlines (and one additional from the default of display). Then add 2 to $a.

Uses the even numbers approach (i.e. odd numbers approach minus 1) with an extra newline every time.

# Answer
> 2 votes
# PostScript, 35 chars

```
count dup 2 mul 1 add string print

```

Each pass "leaks" one thing on the stack, so `count` goes up by 1 each time. Then it justs uses the sum of odd numbers trick.

The bytes output are all `\000` because that's the initial value of strings.

# Answer
> 2 votes
# Haskell, 72

```
putStr$let a="1";aputStr=(\n->take(n^2)$show n++cycle" ").(+1).read in a

```

## Explanation

The apply operator `$` acts as if you place surrounding parentheses around the rest of the line (there are exceptions to this, but it works in this case). `aputStr` is a function that takes a string with the format "abc ...", where "abc" is the square root of the length of the string, including abc. It will parse the string as an integer, and return a string starting with abc+1 and having that length squared. Because of the `$` operator, this will get called recursively on "1" N times.

# Answer
> 2 votes
# Vyxal, 4 bytes

```
:I,⇧

```

Try it Online!

-2 thanks to lyxal.

Note: output is in spaces + newlines.

# Answer
> 1 votes
# Pyth, 8 bytes

```
*d*2Z~Z1

```

This relies on the fact that N2 is equal to the sum of `N` odd numbers. Now Pyth auto prints an new line, so I have to just print `Z * 2` characters in each code where `Z` goes from `0` to `N - 1`.

**Code Expansion**:

```
*d               "Print d whose value is a space character"
  *2Z            "2 * Z times where Z's initial value is 0"
     ~Z1         "Increment the value of Z";

```

Try it online here

# Answer
> 1 votes
# Golflua, 23 bytes

```
X=2+(X|-2)w(S.t("&",X))

```

outputs a combination of `&` and `\n` characters.

### Equivalent Lua code

```
X = 2 + (X or -2)          -- initialize X to 0 the first time, add 2 ever other time

print(string.rep("&", X))

```

Each time the code snippet runs it produces 2 more characters of output than the last time, starting with 1 character. The `print` function appends a newline, so I initialize X to 0 instead of 1.

# Answer
> 0 votes
## ActionScript - 27 / 26 bytes

```
var n=""
trace(n);n+="11"//

```

or

```
var n=1
trace(n);n+="11"//

```

How it works:

```
var n=""
trace(n);n+="11"//var n=""
trace(n);n+="11"//

```

It simply comments out the first line. Note: `trace` adds a newline. Or maybe all the IDE's I use do that automatically.

# Answer
> 0 votes
# GML, 27

```
a=''show_message(a)a+='xx'a

```

# Answer
> 0 votes
# Nim, 24 bytes

```
var s=""
echo s
s&="ss"#

```

Attempt This Online!

Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!

# Answer
> 0 votes
# Zsh, 12 bytes

```
<<<$n
n+=..

```

Try it online!

Same \\$ n^2 = \sum\_{k=1}^n 2k + 1 \\$ as has been used elsewhere. The TIO test has to do some extra work because naively capturing the output in `$(f)` removes trailing newlines, and would output `0`, `3`, `8`, `15`, etc. Instead, we insert a `printf :` to add a character after the last newline, then `${output:0:-1}` to remove it.

# Answer
> 0 votes
# Pyt, 10 bytes

```
0ǰąŁ⁻√⁺²⑴ǰ

```

Try it online!

```
0              pushes 0
 ǰ             ǰoins stack with no delimiter
  ą            convert to ąrray of characters
   Ł           get the Łength
    ⁻          decrement
     √         square root
      ⁺        increment
       ²       square
        ⑴     array of (top of stack) 1s
          ǰ    ǰoin array with no delimiters (implicitly prints at end of code)

```

---
Tags: code-golf, quine, source-layout
---


title: A prime test that's LITERALLY prime

text:
# Question
Title: A prime test that's LITERALLY prime
Write a program that will test the primality of a specified number, and give the output as a Boolean value (True is prime). Your prime test can (but doesn't have to) be valid for the number 1.

Here's the catch: your program itself has to sum to a prime number. Convert every character (including spaces) to its Unicode/ASCII value (table). Then, add all those numbers together to get the sum of your program.

For example, take this not-so-great program I wrote in Python 3.3:

```
q=None
y=int(input())
for x in range(2,int(y**0.5)+1):
    if y%x==0:
        q=False
if not q:
    q=True
print(q)

```

If you convert all the characters to their corresponding Unicode/ASCII value, you get:

```
113 61 78 111 110 101 10 121 61 105 110 116 40 105 110 112 117 116 40 41 41 10 102 111 114 32 120 32 105 110 32 114 97 110 103 101 40 50 44 105 110 116 40 121 42 42 48 46 53 41 43 49 41 58 10 32 32 32 32 105 102 32 121 37 120 61 61 48 58 10 32 32 32 32 32 32 32 32 113 61 70 97 108 115 101 10 105 102 32 110 111 116 32 113 58 10 32 32 32 32 113 61 84 114 117 101 10 112 114 105 110 116 40 113 41

```

You can then find the sum of those numbers manually or with your own program. This specific program sums to 8293, which is a prime number.

Of course, this is Code Golf, so the smaller you can make your program, the better. As pointed out by other users, this program is not very golfy.

A few rules:

Valid inputs include STDIN and prompts (no functions, it's just a way to add free extra code). Spaces are permitted, but only if they are crucial to the functionality of your program. Output must be an output, not just stored in a variable or returned (use print, STDOUT, etc.)

Flags can be used and should be counted literally, not expanded. Comments are not allowed. As for non-ASCII characters, they should be assigned to the value in their respective encoding.

Make sure to list your program's size and the sum of the program. I will test to make sure programs are valid.

Good luck!

Here is a snippet to count the sum of your program and check if it is prime:

```
function isPrime(number) { var start = 2; while (start <= Math.sqrt(number)) { if (number % start++ < 1) return false; } return number > 1; } var inp = document.getElementById('number'); var text = document.getElementById('input'); var out = document.getElementById('output'); function onInpChange() { var msg; var val = +inp.value; if (isNaN(val)) { msg = inp.value.toSource().slice(12, -2) + ' is not a valid number.'; } else if (isPrime(val)) { msg = val + ' is a prime number!'; } else { msg = val + ' is not a prime number.'; } out.innerText = msg; } function onTextChange() { var val = text.value; var total = new Array(val.length).fill().map(function(_, i) { return val.charCodeAt(i); }).reduce(function(a, b) { return a + b; }, 0); inp.value = '' + total; onInpChange(); } text.onkeydown = text.onkeyup = onTextChange; inp.onkeydown = inp.onkeyup = onInpChange;
```

```
body { background: #fffddb; } textarea, input, div { border: 5px solid white; -webkit-box-shadow: inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); -moz-box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1);  padding: 15px; background: rgba(255,255,255,0.5); margin: 0 0 10px 0; font-family: 'Roboto Mono', monospace; font-size: 0.9em; width: 75%; }</style><meta charset="utf-8"><style>/**/
```

```
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet"><textarea id="input" tabindex="0">Insert your (UTF-8 encoded) code here
Or directly input a number below</textarea><br><input id="number" value="6296" tabindex="1"><br><div id="output">6296 is not a prime number.</div>
```

# Answer
> 37 votes
## hello, world!, 13 bytes, `1193`

```
hello, world!

```

# Answer
> 7 votes
# Ruby, sum 3373, 37 bytes

```
require'prime'
g=gets.to_i
p g.prime?

```

# Answer
> 7 votes
# Microscript II, 2 bytes (sum 137)

```
N;

```

# Microscript II, 4 bytes (sum 353)

```
N;ph

```

I'm actually quite surprised that both of these wound up having prime byte sums.

# Answer
> 5 votes
# Python 2, 50 bytes, `4201`

Works for 1. Output is positive if prime, or zero if not.

```
p=input();print all(p%m for m in range(2,p))*~-p;p

```

**Try it online**

---

# Python 2, 44 bytes, `3701`

Doesn't work for 1. Outputs a Boolean.

```
p=input();print all(p%k for k in range(2,p))

```

**Try it online**

# Answer
> 5 votes
# 05AB1E, 2 bytes, `173`

```
p=

```

Explanation:

```
p  # Checks if number is prime - returns 1 if true and 0 if false. Uses implicit input.
 = # Wouldn't usually be required for this sort of program, but I added it to make the sum prime.

```

Try it online!

# Answer
> 5 votes
# Pyth, 2 bytes, `127`

```
/P

```

Try it online

Outputs `1` for primes, `0` for non-primes.

`/` has code point `47`. `P` has code point `80`.

How it works:

```
/P
/PQQ    Implicit variables.
        Q = input
 PQ     Prime factorize Q.
/  Q    Count how many times Q appears. 1 if prime, 0 if not.

```

# Answer
> 5 votes
# Excel, ~~34~~ 30 bytes, sum ~~2039~~ 1759

```
=SUM(--(MOD(A2,ROW(A:A))=0))=2

```

Uses `ROW` instead of `SEQUENCE` which makes it shorter. As a added bonus, it now uses functions available at the time the question was asked.

## Original Answer

```
=SUM(--(MOD(A2,SEQUENCE(A2))=0))=2

```

Uses `SEQUENCE` which was not available when the question was posted.

# Answer
> 5 votes
# Vyxal, 1 byte, sum 23

```
æ

```

Try it Online!

`æ` is the built-in primality checker. Vyxal uses its own codepage, in which the character `æ` is `0x17`, or `23`, which is a prime number.

# Answer
> 4 votes
# Japt, 2 bytes, `191`

```
Uj

```

`U` :`85`

`j` : `106`

Try it online!

# Answer
> 4 votes
# Haskell, 52 bytes, 4421

```
main=do
 k<-readLn
 print$product[1..k-1]`rem`k==k-1

```

Wilson theorem.

# Answer
> 3 votes
# JavaScript (ES6), 40 bytes, `3203`

*Saved 6 bytes thanks to @l4m2*

```
g=x=>m%--x?g(x):x<2;alert(g(m=prompt()))

```

Try it online!

# Answer
> 3 votes
# PHP, 38 bytes, sum 2791

Fun fact: With `$h` instead of `$c`, the sum would be `2801` (also a prime), and its binary representation `101011110001` read as decimal is also a prime number.

```
for($b=$c=$argv[1];$c%--$b;);echo$b<2;

```

takes command line argument, prints `1` or empty string. Run with `-r`.

Code taken from my own prime function (look at the original post if you can).

# Answer
> 2 votes
# R, 27 ~~32~~ bytes, sum 2243 ~~2609~~

Saved a 5 bytes thanks to @rturnbull

```
cat(gmp::isprime(scan(),r=43)>0)

```

This makes use of the gmp library's isprime function.

```
> sum(as.integer(charToRaw('cat(!!gmp::isprime(scan()))')))
[1] 2243
> cat(!!gmp::isprime(scan()))
1: 2243
2:
Read 1 item
TRUE
>

```

# Answer
> 2 votes
# APL (Dyalog Unicode) \+ `dfns`, 7 bytes

## Sum: 569

```
1 pco⌈⎕

```

Try it online! or Verify

The program uses the ceiling function() since it's a no-op on integers, and pads the codepoint sum to a prime number, according to APL's code page.

`pco` is a function from the dfns library which checks for primality.

# Answer
> 2 votes
# Factor \+ `math.primes`, sum 3373, 34 bytes

```
readln string>number prime? pprint

```

Try it online!

Should be pretty self-explanatory I hope!

# Answer
> 1 votes
# Python 2, 44 bytes, byte-sum 3109

This is xnor's 44 byte implementation with the lowest valued variable names that yield a prime byte sum.

Prints `1` if prime and `0` if not.

```
C=B=1
exec"B*=C*C;C+=1;"*~-input()
print B%C

```

# Answer
> 1 votes
# Jelly 6 bytes, byte-sum 691

```
ƓÆḍ,ṠE

```

prints `1` if prime and `0` if not.

**TryItOnline!**

The bytes in hexadecimal are `93 0D D5 2C CD 45` (see the code page), or in decimal are `147 13 213 44 205 69` which sum to 691, which is prime.

### How?

```
ƓÆḍ,ṠE - Main Link: no arguments
Ɠ      - read and evaluate a line from STDIN (integer expected)
 Æḍ    - proper divisor count
   ,   - paired with
    Ṡ  - sign
     E - all equal? - returns a boolean (1 or 0)
       - implicit print

```

The `Æḍ` functionality is such that primes and their negations return one while other integers do not (composites and their negations return numbers greater than one, one and minus one return zero and zero returns, oddly enough, minus one).

The  functionality is such that negative integers return minus one, zero returns zero and positive integers return one.

Thus the two functions only return the same value for the primes.

Note that the 3 byte program `ƓÆP` which directly tests if the input from STDIN is prime is unfortunately not a prime-sum program (240).

Testing for equality using `=`(equals), `e`(exists in), or (non-vectorising equals) for 5 bytes also do not yield prime-sum programs.

---

# Alternative (maybe not acceptable) 4 bytes, sum 571

If the I/O restrictions still allow full programs that take an argument.

```
Æḍ⁼Ṡ

```

...using the same principle as above, where  is non-vectorising equality (the non-vectorising aspect has no effect since there is nothing to vectorise over anyway). The hex values are `0D D5 8C CD` which are `13 213 140 205` in decimal which sum to 571, a prime.

Again note that the 2 byte program `ÆP` does not have a prime sum (93).

# Answer
> 1 votes
# CJam, 4 bytes, byte-sum 439

```
qimp

```

Uses the built-in primality test.

Try it online!

### Alternate solution, 4 bytes, sum 461

```
r~mp

```

# Answer
> 1 votes
# Perl 6, ~~24~~ 22 bytes, `1949`

```
say .is-prime
for +get

```

All three whitespace characters are required.
(Perl 6 doesn't care what *kind* of whitespace character they are, though, so I chose a newline instead of the more commonly used space for the second one...)

# Answer
> 1 votes
## Mathematica, 21 bytes, `1997`

```
Print@*PrimeQ@Input[]

```

`Input[]` reads a line of input (from STDIN if no front end is used, through a dialog box if the Mathematica front end is used), `Print@*PrimeQ` is the composition (`@*`) of the `Print` and `PrimeQ` functions, and `@` is prefix function notation.

# Answer
> 1 votes
## Pyth, 4 bytes, `367`

```
}QPQ

```

Try it here!

# Answer
> 1 votes
# Pip, 8 bytes, `511`

```
0Na%,a=1

```

I wrote a prime checker, and the sum was prime. Convenient. Verify inputs 1-30: Try it online!

### Explanation

```
          a is first command-line argument
    ,a    Numbers from 0 to a-1
  a%      Take a mod each of those numbers (a%0 gives nil)
0N        Count number of times 0 occurs in that list
      =1  If 0 occurs only 1 time (for a%1), then a is prime

```

# Answer
> 1 votes
# C (gcc), ~~62~~ 60 bytes, 4583

Pretty straight-forward. Outputs * if prime, otherwise it outputs a space. Does not work for 1.

-2 thanks to l4m2

```
p;main(i){for(scanf("%d",&p);++i<p;)p=p%i?p:0;puts("*"+!p);}

```

Try it online!

# Answer
> 1 votes
# J, 18 Bytes, `1103`

```
echo 1&p:".(1!:1)1

```

Not far from optimal, the least I could golf a full program primality test to was 17 Bytes: `echo(p:[:".1!:1)1`, which unfortunately sums to 1133 = 11\*103.

Unfortunately I can't figure out how to get keyboard input working on TIO, so no link yet.

### Explanation:

```
echo 1&p:".(1!:1)1  | Full program
           (1!:1)1  | Read a line of input from keyboard
         ".         | Evaluate (converts string to int)
     1&p:           | 1 for prime, 0 for composite
echo                | Print result. The space is required, as 'echo1' would be interpreted as a variable

```

Validating the program:

```
   1 p:+/u:inv'echo 1&p:".(1!:1)1'  NB. Convert to ints, sum, and test primality
1

```

# Answer
> 1 votes
# Pari/GP, 23 bytes, `2111`

```
print(2>=numdiv(input))

```

Try it online!

# Answer
> 1 votes
# AWK, 36 bytes, byte-sum 2239

```
{for(a=1;$0%++a&&a<$0;);$0=(a==$0)}1

```

Try it online!

Outputs `0` if not prime and `1` for prime. Definitely not the most efficient code, since it checks every integer greater than `1` to see if it divides the input.

# Answer
> 1 votes
# Whispers v2, 33 bytes

```
>>> ⊤ℙ∘ℕ
> Input
>> 1∘2

```

Try it online!

1. Score: `44381`
2. Only 6 bytes/2 characters added to make it valid!
3. **1** is not prime

## How it works

This is shown in the order it is executed in:

```
		; Line 3:
>>  ∘		; Compose...
   1            ; Line 1 with
     2          ; The result of line 2

		; Line 2:
> Input		; Retrieve a line of input

		; Line 1:
>>> ⊤		; The input is...
     ℙ		; Prime
      ∘		; And it is...
       ℕ	; Natural

```

# Answer
> 1 votes
# Excel (57 bytes, code sum 3547)

```
=XOR(0<PRODUCT(MOD(A1,ROW(OFFSET(D2,0,,SQRT(A1))))),3>A1)

```

Excel doesn't really have an "input" as such, but this formula expects the number to be tested to be in A1 and outputs to whatever cell you drop it in. It's an array formula, so press Ctrl-Shift-Enter to enter it, rather than Enter.

# Answer
> 1 votes
# TI-Basic, 27 bytes, byte-sum 2843

```
Prompt F
3
For(A,2,sqrt(F
If not(remainder(F,A
0
End
Disp Ans

```

Prints `3` for prime and `0` for composite. Does not work for 1 (prints `3`).

TI-Basic is a tokenized lanugage. `remainder(` is a two-byte token; all others are one-byte tokens.

Explanation:

```
Prompt F             # 0xdd, 0x46, 0x3f # Store input in F
3                    # 0x33, 0x3f       # Store 3 in Ans
For(A,2,sqrt(F       # 0xd3, 0x41, 0x2b, 0x32, 0x2b, 0xbc, 0x46, 0x3f
                        # For each integer A from 2 to sqrt(F)
If not(remainder(F,A # 0xce, 0xb8, (0xef, 0x32), 0x46, 0x2b, 0x41, 0x3f
0                    # 0x30, 0x3f
                        # If F is divisible by A, store 0 in Ans
End                  # 0xd4, 0x3f # end For loop
Disp Ans             # 0xde, 0x72 (no newline) # Print Ans

```

Sum testing with Python:

```
>>> sum(eval(i) for i in ['0xdd', '0x46', '0x3f', '0x33', '0x3f', '0xd3', '0x41', '0x2b', '0x32', '0x2b', '0xbc', '0x46', '0x3f', '0xce', '0xb8', '0xef', '0x32', '0x46', '0x2b', '0x41', '0x3f', '0x30', '0x3f', '0xd4', '0x3f', '0xde', '0x72'])
2843

```

# Answer
> 1 votes
# Java 8, ~~114~~ 105 bytes, Prime 9209

```
interface M{static void main(String[]a){long n=new Long(a[0]),B=n;for(;n%--B>0;);System.out.print(B<2);}}

```

Assumes \\$input\geq2\\$ (will give a division-by-zero error for \\$input=1\\$), since the rule mention "*Your prime test can (but doesn't have to) be valid for the number \\$1\\$.*".

Try it online.

**Explanation:**

```
interface M{                   // Class
  static void main(String[]a){ //  Mandatory main-method
    long n=new Long(a[0]),     //   The first argument as number
    B=n;for(;n%--B>0;);        //   Check if `n` is a prime
    System.out.print(B<2);}}   //   Print whether `n` was a prime
                               //   (if `B` is 1 after the loop, it means it wasn't
                               //   divisible by any other integer in the range [2,n),
                               //   and therefore is a prime)

```

I've used `B` instead of `i` as variable name to make the unicode sum a prime. Verify the unicode sum here.

# Answer
> 1 votes
# Jelly, 4 bytes,  = 239

```
ÆPa1

```

Try it online!

Proof: Try it online! (take the 1-based indices of the program's chars of Jelly's code page, decrement to make them 0-based, sum and then check if the result is prime).

# Answer
> 1 votes
# Help, WarDoq!, 2 bytes, ∑ 127

```
P/

```

**Outputs 1 if it is a prime (positive only) and 0 if it is not a prime**.

Try it online! **Note: Due to technical limitations, this interpreter takes the first line as the code and the second line as STDIN.**

1 is not prime in this.

The code's codepoints are `80 47`, which sums to `127`.

# Answer
> 1 votes
# GolfScript, 14 bytes

```
~.,{*.!+}*.*\%

```

Try it online!

Same solution for the question "Is this number a prime?", the program sums to 887.

# Answer
> 1 votes
# Pyt, 2 bytes, byte sum 149

```
ṗ⁸

```

Try it online!

Uses Pyt's custom encoding, in which the bytes are as follows:

```
8d 08

```

Explanation:

```
ṗ         checks for primality (returns True/False)
⁸         raises top of stack to the 8th power (coerces True/False to 1/0); implicit print

```

# Answer
> 1 votes
# Japt, 2 bytes, `191`

Well, that worked out nicely! :)

```
Uj

```

Try it

# Answer
> 1 votes
# Thunno, 3 bytes (UTF-8), sum = 293

Attempt This Online!

Verify that 293 is prime

Basically, the Thunno interpreter ignores any characters which are not in the printable ASCII set (32-127). As `×` has the codepoint 215, it is ignored and thus the program becomes `N`, which is the prime check program.

## Thunno, \\$ 4 \log\_{256}(96) \approx \\$ 3.29 bytes, sum = 269

```
ND0K

```

Attempt This Online!

Verify that 269 is prime

**Explanation:**

```
ND0K  # Implicit input
N     # Prime check (this is all we need, but unfortunately the ordinal of N is 78, which isn't prime)
 D    # Duplicate (completely unnecessary, but needed to make the sum prime)
  0   # Push a 0
   K  # And pop the 0 (yep, that cancels out)
      # Implicit output

```

# Answer
> 0 votes
# SmileBASIC, 42 bytes, `2687`

```
INPUT N:FOR D=2TO N/2P=P+!(N MOD D)NEXT?!P

```

Outputs 1 (true) if the number is prime, otherwise 0 (false).

The variable names were not just chosen to make the program prime. `N` is the **n**umber to test, `D` is the **d**ivisor, and `P` keeps track of whether N is **p**rime.

# Answer
> 0 votes
# Wonder, 7 bytes, `537`

```
pr rl e

```

There probably is a better way...

# Answer
> 0 votes
# Rust, 190 bytes, 15013 score

```
fn main(){let A=&mut"".into();std::io::stdin().read_line(A);let(B,mut C)=(A.trim().parse::<u64>().unwrap(),true);for H in 2..((B as f64).sqrt()+1.0) as u64{if B%H==0{C=false}}print!("{}",C)}

```

Ungolfed

```
fn main() {
    let input = &mut "".into();
    std::io::stdin().read_line(input);
    let (number, mut prime) = (input.trim().parse::<u64>().unwrap(), true);

    for x in 2..((number as f64).sqrt() + 1.0) as u64 {
        if number % x == 0 {
            prime = false;
        }
    }

    print!("{}", prime);
}

```

Does not work for 1

# Answer
> 0 votes
# Stax, 349

```
|pq

```

Run and debug it

# Answer
> 0 votes
# JavaScript (Node.js), 33 bytes (sum 2237)

```
p=(n,i=1)=>++i*i>n||n%i&&p(n,i,1)

```

Try it online!

# Answer
> 0 votes
## Python, 78 Bytes, `6067`

```
x=lambda a:a and a*x(a-1)or 1
y=lambda b:x(b-1)%b==b-1
print(y(int(input(3))))

```

The `3` is kinda redundant, just there to make the code sum prime. The first `lambda` calculates the factorial of a number and the second `lambda` checks whether a number is prime using Wilson's Theorem.

# Answer
> 0 votes
## vemf, 9 bytes, sum 911

```
{α%├2↕α&☻

```

Prints `1` if \\$\alpha\\$ is prime and `0` if it is not. Somehow *does* work on 1, because an empty list is considered truthy.

In the vemf codepage this is represented as

```
7b e0 25 c3 32 12 e0 26 02

```

which sums to `0x38f` = decimal 911.

## Explanation

```
{α%├2↕α&☻
{         ' define function
 α%    &  ' are all of the remainders nonzero
   ├2↕α   ' between 2 and α-1?
        ☻ ' reprints, just to make the program's sum a prime number

```

---
Tags: code-golf, math, restricted-source, primes
---


# Question
Title: Return the clock emoji closest to the current time when run
I can have a large `if/else` condition for each 30 minutes but I'm looking for more math and Unicode based solution.

Here are clock emojis: . If you lack proper rendering support, you can see them below (they're not in the same order and they may look different to what you see) or at the Unicode chart, page 4. They correspond to Unicode codepoints U+1F550 (CLOCK FACE ONE OCLOCK) through U+1F567 (CLOCK FACE TWELVE-THIRTY).

Your challenge is to write a program that outputs to STDOUT the closest clock face emoji to the current system time (AM and PM should be treated the same). For example if the time `t` is \[5:15 ≤ t \< 5:45), you would display the 5:30 emoji .

This is code-golf, so shortest code in bytes wins. You may want to include a way to easily specify the time to test your code.

# Edge test cases

```
Time   Output  Written
----------------------
11:48         12:00
3:15          3:30
9:45          10:00

```

# Answer
> 11 votes
# Ruby — ~~61~~ 54 bytes

# ~~Python 3 — 79 77 75 74 bytes~~

**edit:** Turns out this is much shorter in Ruby, because `Time` doesn't need to be imported and integer division is the default.

```
a=(Time.now.to_i/900-3)/2%24
puts""<<128336+a/2+a%2*12

```

Arithmetic:

* `Time.now.to_i`: Seconds since epoch.
* `/900`: Combine time into 15-minute segments.
* `-3`: `-4` because characters start at 1 o'clock, `+1` so that rounding is done to nearest half hour, rather than downwards.
* `/2`: Combine into half-hour segments.
* `%24`: Get current half-hour segment out of 12 hours.
* `a/2 + a%2*12`: Account for the fact that whole-hour characters come in a block before half-hour characters.

**Local time version, 69 bytes:**

```
n=Time.now
a=((n.to_i+n.gmtoff)/900-3)/2%24
puts""<<128336+a/2+a%2*12

```

**Original Python 3 version:**

```
import time
a=int((time.time()/900-3)/2%24)
print(chr(128336+a//2+a%2*12))

```

Prints the current time UTC. Python 2's `chr` only accepts 0-255, and `unichr` only 0-65535. In Python 3, `/` is always floating-point division and `//` is always integer division.

# Answer
> 10 votes
# Bash + Coreutils, 60 47

```
date +%I\ 60*%M+45-30/24%%2~C*+16iF09F9590+P|dc

```

Try it online!

Emojis render fine on the OSX terminal, but for Linux (Ubuntu 14.04) you'll have to `sudo apt-get install ttf-ancient-fonts`

For testing different times, insert `-d $time` into the date command. e.g for testing 12:59:

```
date -d 12:59 +%I\ 60*%M+45-30/24%%2~C*+16iF09F9590+P|dc

```

# Answer
> 6 votes
# JavaScript – ~~137~~ ~~117~~ ~~107~~ ~~102~~ 95 bytes

This is going to get easily beaten, but I'll just try my best here.

**EDIT 1**: Now prints in UTC like the Python answer to save 20 bytes.

**EDIT 2:** Changed `new Date().getTime()` to `Date.now()` to save 10 bytes.

**EDIT 3:** Changed `Math.round(x)` to `~~(x+.5)` to save 5 bytes.

**EDIT 4:** Removed unnecessary `(` and `&1023)` left from some old development version where I did a more universal UTF-16 encoding to save 7 bytes.

```
d=~~(Date.now()/18e5+.5)%24;d+=d<2?24:0;alert(String.fromCharCode(55357,56655+(d%2?23+d:d)/2));
```

JavaScript *does* allow for emojis, but in UTF-16 which encodes them as two characters. Luckily, we can simply define them as two characters; the first character is also constant (`0xD83D`), while the other changes.

**Alternative, prints in local time, ~~137~~ ~~132~~ 125:**

```
a=new Date();d=~~(a.getHours()%12*2+a.getMinutes()/30+.5);d+=d<2?24:0;alert(String.fromCharCode(55357,56655+(d%2?23+d:d)/2));
```

# Answer
> 6 votes
# CJam, 31 bytes

```
"")et5<60b675+30/24%2mdC*++

```

You can change the time in the following program to test it:

```
"")[2014 12 19 22 14 1 901 5 -28800000]5<60b675+30/24%2mdC*++

```

# Answer
> 4 votes
# CJam, 50 bytes

```
"":i~et3=C%60*et4=+30d/mo2m24+24%_2%24*+2/+]:c

```

The algorithm is simple, round the time to nearest 30 minutes, count how many 30 minutes have passed since 12 AM/PM, if the number is odd, then add 24 to it, floor divide by 2 and increment the initial unicode by that many code points to get the right clock face.

Also, make sure that you start with 1 AM/PM instead of 12 so take an offset there.

For testing purposes, use the following code:

```
3:H;45:M;"":i~HC%60*M+30d/mo2m48+48%_2%24*+2/+]:c

```

Where the `3:H;` part is the current hour and the `45:M;` part is the current minute of the hour. Simply replace `3` and `45` with the desired value.

Try it online here

*Not all unicode characters might print correctly on the online version depending upon your browser and OS and installed fonts. But for me, all print fine on Firefox with Windows 7.*

# Answer
> 1 votes
# Go, 265 bytes, function

```
import."time"
func f()rune{N,H:=Now(),Hour/2
e,l:=N.Truncate(H),N.Round(H)
if e.Sub(N).Abs()<l.Sub(N).Abs(){N=e}else{N=l}
return []rune("")[N.Hour()%12*2+N.Minute()/30]}

```

Attempt This Online!

Gets the current time, rounds up and down to the nearest half hour, finds the closer one, and returns the emoji that represents it.

# Go, 285 bytes, full program

```
package main
import."time"
func main(){N,H:=Now(),Hour/2
e,l:=N.Truncate(H),N.Round(H)
if e.Sub(N).Abs()<l.Sub(N).Abs(){N=e}else{N=l}
print(string([]rune("")[N.Hour()%12*2+N.Minute()/30]))}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 30 bytes

```
ža60*žb+45-30÷24%2‰`12*+Žü¤·+ç

```

Port of *@jimmy23013*'s CJam answer, so make sure to upvote him as well!

Try it online or verify some manual test times.

**Explanation:**

Uses the following formula to calculate the clock codepoint based on the given \\$h\\$ours and \\$m\\$inutes:

$$d(h,m) = \left\lfloor\frac{60h+m-45}{30}\right\rfloor\bmod{24} \\ C(h,m) = \left\lfloor\frac{d(h,m)}{2}\right\rfloor+12(d(h,m)\bmod{2})+128336$$

```
ža                              # Push the current hours
  60*                           # Multiply them by 60
     žb+                        # Add the current minutes
        45-                     # Subtract 45
           30÷                  # Integer-divided by 30
              24%               # Modulo 24
                 2‰             # Divmod by 2: [n//2,n%2]
                   `            # Pop and push n//2 and n%2 separated to the stack
                    12*         # Multiply n%2 by 12
                       +        # Add it to the n//2
                        Žü¤     # Push compressed integer 64168
                           ·    # Double it to 128336
                            +   # Add it as well
                             ç  # Convert it to a character with this codepoint
                                # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Žü¤` is `64168` (compressed `128336` directly is 1 byte longer: `•1ùθ•`).

# Answer
> 1 votes
# C (gcc) with `-m32`, ~~104~~ ~~100~~ 98 bytes

* -6 thanks to ceilingcat

```
*t;f(i){char a[]="";time(&i);i=1[t=gmtime(&i)]/15;a[3]=144+(t[2]+11+i/4)%12+(i-1U<2)*12;puts(a);}

```

Try it online!

Ungolfed:

```
*t; // broken-down time structure ([1]=minutes, [2]=hours)
f(i){ // time
  char a[]=""; // base emoji in modifiable UTF-8 string
  time(&i); // get time and convert into structure
  i=1[t=gmtime(&i)]/15; // get granular 15-minute chunks
  a[3]=
    144+ // base 4th byte of emoji
    (t[2]+11+i/4)%12+ // convert [0..23] to [1..24]-1 for hour, adding [0:45..1:00)
    (i-1U<2)*12; // add [0:15..0.45) as half-hour
  puts(a);
}

```

# Answer
> 1 votes
# Julia, 81 bytes

```
using Dates
n=now()
M=minute(n)
print(''+mod1(hour(n)+(M>44),12)+12(14<M<45))

```

Attempt This Online!

Julia is generally picky with types, but some common arithmetic statements involving `Char`, `Int`, and `Bool` are permitted. The `Int` values of the clock emojis are the range `128336:128359`. The emojis are encoded in ascending order, with all the twelve that are on the hour coming before the twelve half-past emojis. In this algorithm, the preceding character `''` is incremented by the 12-hour number (plus 1 if it's more than 44 minutes past the hour), and another 12 is added if the minute hand needs to be adjusted.

-17 bytes (!!) thanks to MarcMush: just use `Dates.minute` instead of parsing the time string

# Answer
> 0 votes
## Pascal, 134 characters

This `program` requires a processor supporting the time-related features defined by ISO standard 10206 “Extended Pascal”. Furthermore the *implementation-defined* set of `char` values must include said Unicode characters.

```
program t(output);var t:timeStamp;begin getTimeStamp(t);write(('')[t.hour mod 12*2+round(t.minute/30)+1])end.

```

Ungolfed:

```
program clock(output);
    var
        ts: timeStamp;
    begin
        getTimeStamp(ts);
        { This `program` presumes `ts.timeValid` is set to `true`.
          Otherwise `getTimeStamp` sets the clock to midnight. Insert

            ts.hour := 11;
            ts.minute := 48;

          here to test the functionality of this `program`. }
        writeLn(('')
            [ts.hour mod 12 * 2 + round(ts.minute / 30) + 1]);
    end.

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 98 bytes

```
Print@FromCharacterCode[128336+Quotient[#,2]+12Mod[#,2]&[Mod[Quotient[UnixTime[]-2700,900]/2,24]]]

```

Original Code is

```
a = Mod[Quotient[UnixTime[] - 3 * 900, 900] / 2, 24];
result = FromCharacterCode[128336 + Quotient[a, 2] + Mod[a, 2] * 12];
Print[result]

```

---
Tags: code-golf, date
---


title: Make a Custom Bayer Matrix

text:
# Question
Title: Make a Custom Bayer Matrix
A Bayer matrix is a threshold map used for ordered dithering that gives the illusion of having more shades of color than actually present by using a crosshatch-like pattern.

Bayer matrices are square with a side length that is a power of 2. Here are some examples:

\\$ \displaystyle\frac{1}{4} \times \begin{bmatrix} 0 & 2\\ 3 & 1 \end{bmatrix}\\$

\\$ \displaystyle\frac{1}{16} \times \begin{bmatrix} 0 & 8 & 2 & 10\\ 12 & 4 & 14 & 6\\ 3 & 11 & 1 & 9\\ 15 & 7 & 13 & 5 \end{bmatrix}\\$

\\$ \displaystyle\frac{1}{64} \times \begin{bmatrix} 0 & 32 & 8 & 40 & 2 & 34 & 10 & 42\\ 48 & 16 & 56 & 24 & 50 & 18 & 58 & 26\\ 12 & 44 & 4 & 36 & 14 & 46 & 6 & 38\\ 60 & 28 & 52 & 20 & 62 & 30 & 54 & 22\\ 3 & 35 & 11 & 43 & 1 & 33 & 9 & 41\\ 51 & 19 & 59 & 27 & 49 & 17 & 57 & 25\\ 15 & 47 & 7 & 39 & 13 & 45 & 5 & 37\\ 63 & 31 & 55 & 23 & 61 & 29 & 53 & 21 \end{bmatrix}\\$

The numbers in the matrix are arranged in such a way so that each number is placed as distant from the previous ones as possible, taking account that the edges wrap.

For example, in the second matrix shown above, the 0 is placed in the top left first, then the 1 is placed two to the right and two below the 0, which is the maximum distance away from the 0. Note that the 1 is not placed in the bottom right, because since the edges wrap, the bottom right would be one to the left and one above the 0. Next, the 2 is placed with a distance of 2 from both 0 and 1, and the 3 is placed similarly.

Note that measuring the distances to generate the matrix is not the simplest method.

# Challenge

Your task is to create a program or function, that when given an input side length \\$s\\$, outputs a Bayer matrix that has a side length of \\$s\\$.

# Rules

* For a side length of \\$s\\$, you may take the input as \\$s\\$ or \\$log\_2(s)\\$. You may assume that \\$2\le s\le16\\$ and that \\$log\_2(s)\\$ is an integer. This means you are allowed to hardcode outputs, but in most cases this is not the shortest method.
* The numbers in the output matrix may range from (inclusive) \\$0\\$ to \\$s^2-1\\$, \\$1\\$ to \\$s^2\\$, \\$0\\$ to \\$\frac{s^2-1}{s^2}\\$, or \\$\frac{1}{s^2}\\$ to \\$1\\$. For example, for \\$s=2\\$, all of these are acceptable: \\$ \begin{bmatrix} 0 & 2\\ 3 & 1 \end{bmatrix}\\$, \\$ \begin{bmatrix} 1 & 3\\ 4 & 2 \end{bmatrix}\\$, \\$ \begin{bmatrix} 0 & 0.5\\ 0.75 & 0.25 \end{bmatrix}\\$, \\$ \begin{bmatrix} 0.25 & 0.75\\ 1 & 0.5 \end{bmatrix} \\$
* The output matrix may be offsetted or transposed, reflected, rotated, etc. as long as the general pattern is the same. This means that when there is a tie for maximum distance, any of the tied options may be chosen. For example, for \\$s=2\\$, any matrix with 0 and 1 in opposite corners and 2 and 3 in opposite corners is acceptable.
* Input and output may be in any convenient format.
* This is , so the shortest answer in bytes wins.

# Answer
> 7 votes
# Python NumPy, 75 bytes

```
from numpy import*
f=lambda n:n and kron(c_[[0,3],[2,1]]-4j,1j-f(n-1)).imag

```

Attempt This Online!

### How?

Recursively expands the pattern by "Kroneckering" it with the 2x2 template. The Kronecker product knows which of the inputs must come together in each cell of the output. Only, it takes the product where we want the sum.

In principle we could address this by exponentiating but that would be numerically unsound.

Instead we use a bit of complex number trickery. Principle:

*Have* a,b,times

*Need* a+b

*Do* (1+ai)x(1+bi) = 1-ab + (a+b)i and use imaginary part of result

# Answer
> 7 votes
# Wolfram Language (Mathematica), 48 bytes

```
Nest[ArrayFlatten@{{4#,4#+2},{4#+3,4#+1}}&,0,#]&

```

Try it online!

Input is \\$\log\_2s\\$, output is an integer matrix with entries starting from 0. Modified from the recursive formula on the Wikipedia page for ordered dithering: $$M\_{2s}=\begin{bmatrix}4M\_s&4M\_s+2\\ 4M\_s+3&4M\_s+1 \end{bmatrix}$$

# Answer
> 6 votes
# JavaScript (ES6), 87 bytes

Based on the recursive formula already pointed out by Parcly Taxel, but using a bitwise construction.

```
n=>[...Array(1<<n)].map((_,y,a)=>a.map(g=(k=n,x)=>k--&&4*g(k,x)|2*(x>>k)+3*(y>>k&1)&3))

```

Try it online!

### How?

Given \\$n\\$, we build a square matrix of width \\$2^n\\$:

```
[...Array(1 << n)].map((_, y, a) =>
  a.map(
    ...
  )
)

```

We fill this matrix with a recursive callback function. Because the content of the array we iterate over is not initialized, \\$k\\$ is undefined on the first call and set to the default value \\$n\\$. The second argument \\$x\\$, on the other hand, is well defined right away.

```
g = (k = n, x) =>    // k = counter, x = horizontal position
  k-- &&             // decrement k; if it was not 0:
    4 * g(k, x) |    //   append 4 times the result of a recursive call
    2 * (x >> k) +   //   set bit #1 if the k-th bit of x is set
    3 * (y >> k & 1) //   toggle bits #0 and #1 if the k-th bit of y is set
    & 3              //   ignore the other bits

```

# Answer
> 5 votes
# Python 3, 93 bytes (@alephalpha)

```
lambda n:[[g(x)/4+g(x^y)/2for y in range(n)]for x in range(n)]
g=lambda n:n and n%2+g(n//2)/4

```

Try it online! Link includes test cases. Takes the size of the matrix as input and returns binary fractions. Explanation: `g` takes the bits of `n` from LSB to MSB and interprets them as base `4` digits starting at the quaternary point e.g. `6 = 110₂ => 0.11₄ = 0.3125 = 0.0101₂`. One set of alternate bits depends only on the row while the other set depends on the bitwise XOR of the row and column; this is the equivalent to the `3*` and `2*` approach of the previous versions.

Previous 104-byte Python 3.8 answer (@xnor):

```
lambda n:[[2*(g:=lambda m:int(f"{m:0{n}b}"[::-1],4))(y)^3*g(x)for y in range(2**n)]for x in range(2**n)]

```

Try it online! Link includes test cases. Takes the power of `2` as input and outputs integers.

Previous ~~154~~ 116-byte Python 3 answer:

```
lambda n:[[2*g(y,n)^3*g(x,n)for y in range(2**n)]for x in range(2**n)]
g=lambda m,n:int(bin(m)[2:].zfill(n)[::-1],4)

```

Try it online! Link includes test cases. Takes the power of `2` as input and outputs integers. Explanation: Lots of bit twiddling.

First row of cells:

```
Col Bin Rev Val Binary
  0 000 000   0 000000
  1 001 100  32 100000
  2 010 010   8 001000
  3 011 110  40 101000
  4 100 001   2 000010
  5 101 101  34 100010
  6 110 011  10 001010
  7 111 111  42 101010

```

First column of cells:

```
Row Bin Rev Val Binary
  0 000 000   0 000000
  1 001 100  48 110000
  2 010 010  12 001100
  3 011 110  60 111100
  4 100 001   3 000011
  5 101 101  51 110011
  6 110 011  15 001111
  7 111 111  64 111111

```

Each cell is then the bitwise XOR of the first cell in its row and column.

# Answer
> 4 votes
# Jelly, ~~20~~ ~~18~~ 14 bytes

```
ḶBUz0Zµ+Ḥ^þḤḅ4

```

Try it online!

*-4 porting Neil's Python solution*

Thought something that generates it flat then cuts the rows up at the end might be shorter, but I haven't actually gotten anything like that to work.

```
ḶB                Binary digits of each [0 .. n).
  U               Reverse each
   z0Z            and right-pad with zeroes to the same length.
      µ+Ḥ         Multiply each by 3,
           Ḥ      multiply each by 2,
         ^þ       table XOR,
            ḅ4    convert from base 4.

```

# Answer
> 3 votes
# MATLAB/Octave, 72 bytes

```
function B=f(n),if n,S=f(n-1);B=[4*S,4*S+2;4*S+3,4*S+1];else,B=0;end,end

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~33~~ 29 bytes

```
ＮθＩ⊘ＥθＥθ↨Ｅ⟦⁰λ⟧↨↨⁻｜νι＆νι²⊘⊘¹⊘¹

```

Try it online! Link is to verbose version of code. Takes the size of the matrix as input and outputs binary fractions. Explanation: Now uses @alephalpha's trick of converting from base `¼` to reverse the bit pattern.

```
Ｎθ                            First input as a number
     θ                        Input number
    Ｅ                         Map over implicit range
       θ                      Input number
      Ｅ                       Map over implicit range
          ⟦  ⟧                List of
           ⁰                  Literal integer `0`
            λ                 Inner value
         Ｅ                    Map over list
                ⁻｜νι＆νι       Bitwise XOR with outer value
               ↨       ²      Convert to base `2`
              ↨         ⊘⊘¹   Interpret as base `¼`
        ↨                  ⊘¹ Interpret as base `½`
   ⊘                          Vectorised halved
  Ｉ                           Cast to string
                              Implicitly print

```

Previous 33-byte version:

```
⊞υ⟦⁰⟧ＦＮ«≧×⁴υ≔⁺Ｅυ⁺κ⁺²κＥυ⁺⁺³κ⊕κυ»Ｉυ

```

Try it online! Link is to verbose version of code. Takes the power of `2` as input and outputs integers. Explanation: Another port of @ParclyTaxel's recursive formula.

```
⊞υ⟦⁰⟧

```

Start with a `1×1` matrix for `s=0`.

```
ＦＮ«

```

Repeat `s` times.

```
≧×⁴υ

```

Multiply the matrix by `4`. (Fortunately this function fully vectorises on the version of Charcoal on TIO.)

```
≔⁺Ｅυ⁺κ⁺²κＥυ⁺⁺³κ⊕κυ

```

Concatenate copies of the matrix with itself both horizontally and vertically, with each copy offset by a different integer from `0` to `3` appropriately.

```
»Ｉυ

```

Output the final matrix in Charcoal's default output format for matrices (each element on its own line and rows double-spaced from each other).

# Answer
> 3 votes
# 05AB1E, 18 bytes

```
Ý¨2вí0ζøxs3*δ^εε4β

```

Port of *@Neil*'s previous Python answer.

Outputs the transposed result compared to the challenge description.

Try it online or verify all test cases or try it step-by-step.

**Explanation:**

```
Ý                  # Push a list in the range [0, (implicit) input]
 ¨                 # Remove the last character to make the range [0,input)
  2в               # Convert each integer to binary as lists
    í              # Reverse each inner list
     0ζø           # Right-pad each inner list with 0s:
      ζ            #  Zip/transpose; swapping rows/columns,
     0             #  using 0 as filler character for unequal length rows
       ø           #  Then zip/transpose back
        x          # Double each inner 1 (without popping the matrix)
         s         # Swap so the matrix is at the top again
          3*       # Multiply each 1 by 3
            δ      # Apply double-vectorized using the two matrices:
             ^     #  Bitwise-XOR them together
              ε    # Then map over the list of matrices:
               ε   #  Map over each inner matrix:
                4β #   Convert the current row-list from base-4 to an integer
                   # (after which the resulting matrix is output implicitly)

```

# Answer
> 3 votes
# , ~~65~~ 63 bytes

```
f=function(n)"if"(n,kronecker(matrix(4:1%%4,2),4*f(n-1),"+"),0)

```

Try it online!

-2 bytes thanks to pajonk.

Recursive function. Takes \\$log\_2(s)\\$ as an input and returns the corresponding \\$s\times s\\$ matrix as output. 4 bytes shorter than using `rbind` and `cbind`.

# , 67 bytes

```
f=function(n)"if"(n,cbind(rbind(g<-4*f(n-1),g+3),rbind(g+2,g+1)),0)

```

Try it online!

# Answer
> 2 votes
# PARI/GP, 65 bytes

```
f(n)=matrix(2^n,,i,j,if(n,f(n-1)[-i\-2,-j\-2]+(i%2+j%2*2+1)%4))/4

```

Attempt This Online!

Takes \\$\log\_2(s)\\$ and the output ranges from \\$0\\$ to \\$\frac{s^2-1}{s^2}\\$.

---

# PARI/GP, 68 bytes

```
n->matrix(n,,i,j,g(i--,j--))
g(i,j)=if(k=i+j,i%2+k%2*2+g(i\2,j\2))/4

```

Attempt This Online!

Takes \\$s\\$ and the output ranges from \\$0\\$ to \\$\frac{s^2-1}{s^2}\\$.

---

# PARI/GP, 69 bytes

```
f(n)=if(n,matconcat([m=4*f(n--),m+2*o=matrix(2^n,,i,j,1);m+3*o,m+o]))

```

Attempt This Online!

Takes \\$\log\_2(s)\\$ and the output ranges from \\$0\\$ to \\$s^2-1\\$.

# Answer
> 2 votes
# Java, ~~131~~ 129 bytes

```
n->{int d=1<<n,m[][]=new int[d][d],i=d*d,g,k;for(;i-->0;m[i/d][i%d]=g)for(g=k=0;k<n;)g=4*g|2*(i%d>>k)+3*(i/d>>k++&1)&3;return m;}

```

Port of *@Arnauld*'s JavaScript answer, so will also output a \\$2^n\\$ by \\$2^n\\$ sized matrix based on the given \\$n\\$.
-2 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
n->{                       // Method with integer parameter and int-matrix return-type
  int d=1<<n,              //  Integer `d`, set to 2 to the power `n`
      m[][]=new int[d][d], //  Result-matrix, of size `d` by `d`
      i=d*d,               //  Index-integer, starting at `d` squared
      g,k;                 //  Temp-integers, uninitialized
  for(;i-->0               //  Loop `i` in the range (d*d,0], over all cells:
      ;                    //    After every iteration:
       m[i/d][i%d]=        //     Set the [y,x]'th matrix-value to:
                   g)      //   Value `g`
    for(g=k=0;             //   Reset both `g` and `k` to 0
        k<n;)              //   Inner loop `k` in the range [0,n):
      g=                   //    Set `g` to:
        4*g|               //     Append 4 times the previous `g`;
        2*(i%d>>k)+        //     Set bit #1 if the k'th bit of `x` is set
        3*(i/d>>k++&1)     //     Toggle bits #0 and #1 if the k'th bit of `y` is set
                           //     (and increase `k` by 1 afterwards with `k++`)
        &3;                //     Ignore the other bits
  return m;}               //  Return the resulting matrix after the loops

```

# Answer
> 2 votes
# Nekomata, 18 bytes

```
r2B:ᵒ{ᵈ:-A2*+ç4£Ed

```

Attempt This Online!

Port of @Neil's Python answer. Takes \\$s\\$ and the output ranges from \\$0\\$ to \\$\frac{s^2-1}{s^2}\\$.

```
r2B:ᵒ{ᵈ:-A2*+ç4£Ed
r                      Range from 0 to s-1
 2B                    Convert to base 2. The least significant digit comes first.
   :                   Duplicate
    ᵒ{                 Make a table with the following function
      ᵈ:-                Take the difference between the two arguments
         A               Absolute value
          2*             Multiply by 2
            +            Add the second argument
             ç           Prepend 0
              4£Ed       Convert from base 1/4

```

---

# Nekomata, 21 bytes

```
0UU$ᵑ{4*::3+,$→:→$,ᶻ,

```

Attempt This Online!

Port of @Parcly Taxel's Mathematica answer. Takes \\$\log\_2(s)\\$ and the output ranges from \\$0\\$ to \\$s^2-1\\$.

```
0UU$ᵑ{4*::3+,$→:→$,ᶻ,
0UU                    [[0]]
   $ᵑ{                 Apply the following function n times
      4*                 Multiply by 4
        :                Duplicate
         :               Duplicate
          3+             Add 3
            ,            Join
             $           Swap
              →          Increment
               :         Duplicate
                →        Increment
                 ,       Join
                  ᶻ,     Zip with join

```

# Answer
> 1 votes
# TI-Basic, ~~68~~ 60 bytes

```
Input N
identity(1→[A]
0Ans
For(I,1,N
4Ans
augment(augment(Ans,Ans+3[A])ᵀ,augment(Ans+2[A],Ans+[A])ᵀ→[A]
Fill(1,[A]
End
Ans

```

Takes input as \\$log\_2(s)\\$.
-8 bytes thanks to MarcMush.

---
Tags: code-golf, array, matrix
---


title: Make a Court Transcriber

text:
# Question
Title: Make a Court Transcriber
Discussion in courtrooms often occurs at a high speed and needs to be accurately transcribed in case the text of the decision is needed in future cases. For this purpose, the stenographers who transcribe court discussions use specially designed keyboards with a small set of buttons, which are pressed in groups to spell out words with a single motion. For this challenge, you will write a program that does something quite similar.

## The Challenge

Given a list composed of sequences of three letters, as well as another list of dictionary words, return the shortest word containing all of them in sequence without overlaps. If there are multiple shortest words, you may return any of them. Your program may accept the dictionary and letter sequences in any format conforming to the I/O rules.

## Examples

```
[dic, ion, ary]: dictionary
[tra, scr, ber]: transcriber

```

This is , so shortest answer wins!

*The dictionary used to check answers should be the SCOWL word list, usually available as `/usr/share/dict/words` on Debian GNU/Linux systems.*

# Answer
# Ruby, 40 bytes

-1 byte thanks to Dingus

```
->d,a{d.grep(/#{a*".*"}/).min_by &:size}

```

Attempt This Online!
> 7 votes

# Answer
# Japt `-g`, 9 bytes

```
ñÊfèVq*i.

```

Try it

```
ñÊfèVq*i.     :Implicit input of arrays U=dictionary & V=substrings
ñ             :Sort U by
 Ê            :  Length
  f           :Filter by
   è          :  Count occurrences of
    Vq        :    Join V with
      *i.     :    "*" prepended with "."
              :Implicit output of first element

```
> 6 votes

# Answer
# Python 3.8 (pre-release), ~~76~~ 75 bytes

*-1 bytes thanks to @m90*

```
lambda x,d:min(filter(re.compile('.*'.join(x)).search,d),key=len)
import re

```

Try it online!
> 5 votes

# Answer
# J-uby, 45 bytes

Port of my Ruby answer. Unfortunately lost a few bytes by having to call `Regexp.new` manually instead of using a Regexp literal and interpolation.

```
(:grep|:min_by+:+@)%(~:*&".*"|~(:new&Regexp))

```

Attempt This Online!

## Explanation

```
( :grep | :min_by + :+@ ) % (~:* & ".*" | ~(:new & Regexp))

                            (~:* & ".*" | ~(:new & Regexp))  # Construct regexp by joining array with ".*"
( :grep |                                                    # Search dictionary with it, then
          :min_by + :+@ )                                    # Get the smallest of the results by length

```
> 4 votes

# Answer
# JavaScript (V8), ~~82~~79 bytes

```
d=>x=>d.filter(w=>RegExp(x.join`.*`).test(w)).sort((a,b)=>a.length-b.length)[0]

```

Try it online!

```
d=>x=>d.filter(w=>RegExp(x.join`.*`).test(w)).sort((a,b)=>a.length-b.length)[0]

d=>                                     // given a dictionary d
   x=>                                  // and (via currying) a list of three letter sequences x,
d.filter(w=>RegExp(          ).test(w)) // keep only the words from the dictionary which match
                   x.join`.*`           // a regular expression formed by joining each 3 character sequence with ".*" (explained later)
.sort((a,b)=>a.length-b.length)         // sort the newly filtered dictionary by length
                               [0]      // and return the first word (should be the shortest)

// Generated regex, using x=["tra", "scr", "ber"] as an example

/tra.*scr.*ber/
 tra            // the first sequence of letters that needs to occur in the word anywhere
    .*          // any amount of intermediate characters (including 0)
      scr       // the second sequence that needs to occur
         .*     // 0 or more intermediate characters again
           ber  // the final sequence of characters that needs to occur

```

Might be possible to do this shorter with a reduce, but it escapes me. Maybe `eval` could make the regex shorter, but I don't see it.

LMK if there's a better way to format the TIO page, but I don't know how to import the big dictionary linked in the question. I'll probably make one with a bunch of test cases so you don't have to do your own.

I'm not worried so much though cause this should be theoretically correct assuming there's no weird edge cases :P
> 3 votes

# Answer
# Retina, 33 bytes

```
0G`
,
.$*
~)`^
G`
0A`
N$`
$.&
0G`

```

Try it online! Takes a list of sequences on the first line followed by the dictionary but link includes bash wrapper that automatically appends `/usr/share/dict/words` to the input for you (does make the script slow though). Explanation:

```
0G`

```

Get just the list of sequences.

```
,
.$*

```

Replace the commas with `.*` (`*` is the string repetition operator in Retina 1, so it needs to be escaped.)

```
^
G`

```

Prefix `G``.

```
~)`

```

Execute the result as Retina code on the original input.

```
0A`

```

Delete the list of sequences, which obviously matched itself.

```
N$`
$.&

```

Sort in ascending order of length.

```
0G`

```

Keep only the shortest word.
> 3 votes

# Answer
# Vyxal, 10 bytes

```
'?‛.*jr;Þg

```

Try it Online!

Takes in the dictionary and the partial transcription as lists.
> 3 votes

# Answer
# Pip, ~~23~~ ~~22~~ 20 bytes

*-3 bytes thanks to @DLosc*

```
{@(aJ`.*`N_FIbSK#_)}

```

Try It Online!

```
{@(aJ`.*`N_FIbSK#_)}          ; First argument = substrings = a
                              ; Second argument = dictionary = b
{                  }          ; Create a function that...
 @(               )           ; takes the first element of...
           FIb                ; b, filtered by if...
         N_                   ; each element matches...
   aJ`.*`                     ; the regex formed by joining each substring with ".*"...
              SK#_            ; and sorted by the length of the word.

```
> 2 votes

# Answer
# Bash, ~~88~~ 86 bytes

```
for w in `<$1`;{ echo $w>$w;}
wc -m `printf "*%s*" ${@:2}`|sort -n|head -1|tr -d 0-9\

```

Try it online!

First argument is dictionary file. The followings are the three squence letters.

For each word in dict generate a file containing the word itself. `printf "*%s*" ${@:2}` generates the pattern `**$2**$3**$4**...` with the rest of the arguments. This pattern is used as a glob tu select files and count word length. `wc -m` otuputs length and filenames so `sort -n|head -1|tr -d 0-9\`  so sorts by length, gets first and deletes numbers and space.

Note: If your dictionary file is too large your filesystem has to handle such number of files on same directory (that's why is trimmed down in TIO).
> 2 votes

# Answer
# Perl 5 (`-ap`), ~~58~~, 51 bytes

7 bytes saved thanks to Xcali

```
$"=".*";$_=(sort{$a=~y///c-length$b}grep/@F/,@_)[0]

```

Try it online!
> 1 votes

# Answer
# Thunno, \\$ 22 \log\_{256}(96) \approx \\$ 18.11 bytes

```
g".*"z1jAfkD.LZZz:AJAK

```

Attempt This Online!

#### Explanation

```
g".*"z1jAfkD.LZZz:AJAK  # Implicit input
g         k             # Filter:
       j                #  join
     z1                 #  the second input
 ".*"                   #  by ".*"
        Af              #  regex test
           D.L          # Duplicate, length of each
              ZZz:      # Zip and sort by length
                  AJAK  # Last item of first item
                        # Implicit output

```
> 1 votes

# Answer
# Python 3, 67 bytes

```
lambda x,d:[e for e in d if re.match(".*?".join(x),e)][0]
import re

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 121 bytes

```
MinimalBy[Select[ReadList["/usr/share/dict/words",String],StringMatchQ[#,StringExpression@@Riffle[s,___]]&],StringLength]

```

Try it online!

# Wolfram Language (Mathematica), 82 bytes

```
MinimalBy[Select[d,StringMatchQ[#,StringExpression@@Riffle[s,___]]&],StringLength]

```

Try it online!

---

Original code is:

```
FindShortestWord[sequences_List, dictionary_List] := Module[
  {pattern, matchedWords},
  pattern = StringExpression @@ Riffle[sequences, ___];
  matchedWords = Select[dictionary, StringMatchQ[#, pattern] &];
  MinimalBy[matchedWords, StringLength]
]

(* Load the SCOWL word list *)
scowlWordList = ReadList["/usr/share/dict/words", String];

(* Test the function *)
sequences1 = {"dic", "ion", "ary"};
sequences2 = {"tra", "scr", "ber"};
FindShortestWord[sequences1, scowlWordList]//Print
FindShortestWord[sequences2, scowlWordList]//Print

```
> 1 votes

---
Tags: code-golf, string
---